Open History to see the last commit
1import { readFile, readdir } from 'node:fs/promises'
2import path from 'node:path'
3import { describe, expect, test, vi } from 'vitest'
4import { StartCompiler } from '../../src/start-compiler/compiler'
5β
6// Default test options for StartCompiler
7function getDefaultTestOptions(env: 'client' | 'server') {
8 const envName = env === 'client' ? 'client' : 'ssr'
9 return {
10 envName,
11 root: '/test',
12 framework: 'react' as const,
13 providerEnvName: 'ssr',
14 }
15}
16β
17async function getFilenames() {
18 return await readdir(path.resolve(import.meta.dirname, './test-files'))
19}
20β
21async function compile(opts: {
22 env: 'client' | 'server'
23 code: string
24 id: string
25 warn?: (message: string) => void
26}) {
27 const compiler = new StartCompiler({
28 ...opts,
29 ...getDefaultTestOptions(opts.env),
30 loadModule: async () => {
31 // do nothing in test
32 },
33 lookupKinds: new Set(['Middleware']),
34 lookupConfigurations: [
35 {
36 libName: `@tanstack/react-start`,
37 rootExport: 'createMiddleware',
38 kind: 'Root',
39 },
40 {
41 libName: `@tanstack/react-start`,
42 rootExport: 'createStart',
43 kind: 'Root',
44 },
45 ],
46 warn: opts.warn,
47 getKnownServerFns: () => ({}),
48 resolveId: async (id) => {
49 return id
50 },
51 })
52 const result = await compiler.compile({
53 code: opts.code,
54 id: opts.id,
55 })
56 return result
57}
58β
59describe('createMiddleware compiles correctly', async () => {
60 const filenames = await getFilenames()
61β
62 describe.each(filenames)('should handle "%s"', async (filename) => {
63 const file = await readFile(
64 path.resolve(import.meta.dirname, `./test-files/${filename}`),
65 )
66 const code = file.toString()
67β
68 // Note: Middleware compilation only happens on the client
69 test(`should compile for ${filename} client`, async () => {
70 const result = await compile({ env: 'client', code, id: filename })
71β
72 await expect(result!.code).toMatchFileSnapshot(
73 `./snapshots/client/${filename}`,
74 )
75 })
76 })
77β
78 test('should compile validator method', async () => {
79 const code = `
80 import { createMiddleware } from '@tanstack/react-start'
81 const myMiddleware = createMiddleware({ type: 'function' })
82 .validator((input: string) => input)
83 .server(async ({ next }) => {
84 return next()
85 })`
86β
87 const result = await compile({
88 env: 'client',
89 code,
90 id: 'test.ts',
91 })
92β
93 expect(result!.code).toMatchInlineSnapshot(`
94 "import { createMiddleware } from '@tanstack/react-start';
95 const myMiddleware = createMiddleware({ type: 'function' });"
96 `)
97 })
98β
99 // TODO remove upon stable
100 test('should warn for deprecated inputValidator method', async () => {
101 const warn = vi.fn()
102 const code = `
103 import { createMiddleware } from '@tanstack/react-start'
104 const myMiddleware = createMiddleware({ type: 'function' })
105 .inputValidator((input: string) => input)
106 .server(async ({ next }) => {
107 return next()
108 })`
109β
110 await compile({
111 env: 'client',
112 code,
113 id: 'test.ts',
114 warn,
115 })
116β
117 expect(warn).toHaveBeenCalledWith(
118 expect.stringContaining(
119 'createMiddleware().inputValidator() is deprecated. Use createMiddleware().validator() instead.',
120 ),
121 )
122 })
123β
124 test('should use fast path for direct imports from known library (no extra resolveId calls)', async () => {
125 const code = `
126 import { createMiddleware } from '@tanstack/react-start'
127 const myMiddleware = createMiddleware().server(async ({ next }) => {
128 return next()
129 })`
130β
131 const resolveIdMock = vi.fn(async (id: string) => id)
132β
133 const compiler = new StartCompiler({
134 env: 'client',
135 ...getDefaultTestOptions('client'),
136 loadModule: async () => {},
137 lookupKinds: new Set(['Middleware']),
138 lookupConfigurations: [
139 {
140 libName: '@tanstack/react-start',
141 rootExport: 'createMiddleware',
142 kind: 'Root',
143 },
144 ],
145 getKnownServerFns: () => ({}),
146 resolveId: resolveIdMock,
147 })
148β
149 await compiler.compile({
150 code,
151 id: 'test.ts',
152 })
153β
154 // Direct known-library imports use the knownRootImports fast path, so they
155 // do not need resolveId.
156 expect(resolveIdMock).not.toHaveBeenCalled()
157 })
158β
159 test('should use slow path for factory pattern (resolveId called for import resolution)', async () => {
160 // This simulates a factory pattern where createMiddleware is re-exported from a local file
161 const factoryCode = `
162 import { createFooMiddleware } from './factory'
163 const myMiddleware = createFooMiddleware().server(async ({ next }) => {
164 return next()
165 })`
166β
167 const resolveIdMock = vi.fn(async (id: string) => id)
168β
169 const compiler = new StartCompiler({
170 env: 'client',
171 ...getDefaultTestOptions('client'),
172 loadModule: async (id) => {
173 // Simulate the factory module being loaded
174 if (id === './factory') {
175 compiler.ingestModule({
176 code: `
177 import { createMiddleware } from '@tanstack/react-start'
178 export const createFooMiddleware = createMiddleware
179 `,
180 id: './factory',
181 })
182 }
183 },
184 lookupKinds: new Set(['Middleware']),
185 lookupConfigurations: [
186 {
187 libName: '@tanstack/react-start',
188 rootExport: 'createMiddleware',
189 kind: 'Root',
190 },
191 ],
192 getKnownServerFns: () => ({}),
193 resolveId: resolveIdMock,
194 })
195β
196 await compiler.compile({
197 code: factoryCode,
198 id: 'test.ts',
199 })
200β
201 // resolveId should only be called for './factory'. Direct known-library
202 // imports use the knownRootImports fast path.
203 //
204 // Note: The factory module's import from '@tanstack/react-start' ALSO uses
205 // the fast path (knownRootImports), so no additional resolveId call is needed there.
206 expect(resolveIdMock).toHaveBeenCalledTimes(1)
207 expect(resolveIdMock).toHaveBeenNthCalledWith(1, './factory', 'test.ts')
208 })
209β
210 test('should resolve createMiddleware from start-client-core implementation file', async () => {
211 const virtualModules: Record<string, string> = {
212 '@tanstack/start-client-core': `
213 export { createMiddleware } from './createMiddleware'
214 export { createIsomorphicFn } from '@tanstack/start-fn-stubs'
215 `,
216 '/virtual/compiler-known/middleware-factory.ts': `
217 export const createMiddleware = () => ({
218 server: () => createMiddleware(),
219 })
220 `,
221 }
222β
223 const compiler = new StartCompiler({
224 env: 'client',
225 ...getDefaultTestOptions('client'),
226 loadModule: async (id) => {
227 const code = virtualModules[id]
228 if (code) {
229 compiler.ingestModule({ code, id })
230 }
231 },
232 lookupKinds: new Set(['Middleware', 'IsomorphicFn']),
233 lookupConfigurations: [],
234 getKnownServerFns: () => ({}),
235 resolveId: async (source) => {
236 if (source === '@tanstack/start-client-core') {
237 return '@tanstack/start-client-core'
238 }
239β
240 if (source === './createMiddleware') {
241 return '/virtual/compiler-known/middleware-factory.ts'
242 }
243β
244 return null
245 },
246 })
247β
248 const result = await compiler.compile({
249 id: '/repo/packages/start-client-core/src/createCsrfMiddleware.ts',
250 code: `
251 import { createIsomorphicFn } from '@tanstack/start-fn-stubs'
252 import { createMiddleware } from './createMiddleware'
253β
254 const innerCreateCsrfMiddleware = () => {
255 return createMiddleware().server(() => 'server-only-middleware')
256 }
257β
258 export const createCsrfMiddleware = createIsomorphicFn()
259 .server(innerCreateCsrfMiddleware)
260 `,
261 })
262β
263 expect(result).not.toBeNull()
264 expect(result!.code).not.toContain('server-only-middleware')
265 expect(result!.code).not.toContain('createIsomorphicFn')
266 })
267β
268 test('should resolve namespace createMiddleware from start-client-core implementation file', async () => {
269 const virtualModules: Record<string, string> = {
270 '@tanstack/start-client-core': `
271 export { createMiddleware } from './createMiddleware'
272 `,
273 '/virtual/compiler-known/middleware-factory.ts': `
274 export const createMiddleware = () => ({
275 server: () => createMiddleware(),
276 })
277 `,
278 }
279β
280 const compiler = new StartCompiler({
281 env: 'client',
282 ...getDefaultTestOptions('client'),
283 loadModule: async (id) => {
284 const code = virtualModules[id]
285 if (code) {
286 compiler.ingestModule({ code, id })
287 }
288 },
289 lookupKinds: new Set(['Middleware']),
290 lookupConfigurations: [],
291 getKnownServerFns: () => ({}),
292 resolveId: async (source) => {
293 if (source === '@tanstack/start-client-core') {
294 return '@tanstack/start-client-core'
295 }
296β
297 if (source === './createMiddleware') {
298 return '/virtual/compiler-known/middleware-factory.ts'
299 }
300β
301 return null
302 },
303 })
304β
305 const result = await compiler.compile({
306 id: '/repo/packages/start-client-core/src/internal.ts',
307 code: `
308 import * as middlewareModule from './createMiddleware'
309β
310 export const middleware = middlewareModule.createMiddleware().server(() => {
311 return 'server-only-middleware'
312 })
313 `,
314 })
315β
316 expect(result).not.toBeNull()
317 expect(result!.code).not.toContain('server-only-middleware')
318 })
319})