Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

handleCreateMiddleware.ts

69 lines1.9 KB

1import { sourcePosition, stripMethodCall } from './utils'
2import type {
3 CompilationContext,
4 MethodCallInfo,
5 RewriteCandidate,
6} from './types'
7​
8// TODO remove upon stable
9function warnInputValidatorDeprecation(
10 context: CompilationContext,
11 inputValidator: MethodCallInfo,
12): void {
13 const loc = sourcePosition(context.code, inputValidator.call.start)
14 const location = `${context.id}:${loc.line}:${loc.column + 1} `
15​
16 context.warn?.(
17 `${location}createMiddleware().inputValidator() is deprecated. Use createMiddleware().validator() instead.`,
18 )
20​
21/**
22 * Handles createMiddleware transformations for a batch of candidates.
23 *
24 * @param candidates - All Middleware candidates to process
25 * @param context - The compilation context
26 */
27export function handleCreateMiddleware(
28 candidates: Array<RewriteCandidate>,
29 context: CompilationContext,
30): void {
31 if (context.env === 'server') {
32 throw new Error('handleCreateMiddleware should not be called on the server')
33 }
34​
35 for (const candidate of candidates) {
36 const { validator, inputValidator, server } = candidate.methodChain
37​
38 // TODO remove upon stable
39 if (inputValidator) {
40 warnInputValidatorDeprecation(context, inputValidator)
41 }
42​
43 for (const [methodName, methodCall] of [
44 ['validator', validator],
45 // TODO remove upon stable
46 ['inputValidator', inputValidator],
47 ] as const) {
48 if (!methodCall) {
49 continue
50 }
51​
52 const innerInputExpression = methodCall.call.arguments[0]
53​
54 if (!innerInputExpression) {
55 throw new Error(
56 `createMiddleware().${methodName}() must be called with a validator!`,
57 )
58 }
59​
60 // remove the validator call expression
61 stripMethodCall(methodCall.call, context)
62 }
63​
64 if (server) {
65 // remove the server call expression
66 stripMethodCall(server.call, context)
67 }
68 }