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

createServerFn.test.ts

811 lines25.6 KB

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 }
16​
17async function getFilenames() {
18 return await readdir(path.resolve(import.meta.dirname, './test-files'))
20​
21const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split'
22​
23async function compile(opts: {
24 env: 'client' | 'server'
25 code: string
26 parserFilename?: string
27 isProviderFile: boolean
28 mode: 'dev' | 'build'
29 warn?: (message: string) => void
30}) {
31 // Use an absolute path inside the test root to ensure consistent filename output
32 let id = '/test/src/test.ts'
33​
34 if (opts.isProviderFile) {
35 id += `?${TSS_SERVERFN_SPLIT_PARAM}`
36 }
37​
38 const compiler = new StartCompiler({
39 ...opts,
40 ...getDefaultTestOptions(opts.env),
41 loadModule: async (id) => {
42 // do nothing in test
43 },
44 lookupKinds: new Set(['ServerFn']),
45 lookupConfigurations: [
46 {
47 libName: `@tanstack/react-start`,
48 rootExport: 'createServerFn',
49 kind: 'Root',
50 },
51 ],
52 warn: opts.warn,
53 getKnownServerFns: () => ({}),
54 resolveId: async (id) => {
55 return id
56 },
57 })
58 const result = await compiler.compile({
59 code: opts.code,
60 id,
61 parserFilename: opts.parserFilename,
62 })
63 return result
65​
66describe('createServerFn compiles correctly', async () => {
67 const filenames = await getFilenames()
68​
69 describe.each(filenames)('should handle "%s"', async (filename) => {
70 const file = await readFile(
71 path.resolve(import.meta.dirname, `./test-files/${filename}`),
72 )
73 const code = file.toString()
74​
75 test.each([
76 { type: 'client', isProviderFile: false },
77 { type: 'server', isProviderFile: false },
78 { type: 'server', isProviderFile: true },
79 ] as const)(`should compile for ${filename} %s`, async (env) => {
80 const result = await compile({
81 env: env.type,
82 isProviderFile: env.isProviderFile,
83 code,
84 parserFilename: `/test/src/${filename}`,
85 mode: 'build',
86 })
87​
88 const folder =
89 env.type === 'client'
90 ? 'client'
91 : env.isProviderFile
92 ? 'server-provider'
93 : 'server-caller'
94 await expect(result!.code).toMatchFileSnapshot(
95 `./snapshots/${folder}/${filename}`,
96 )
97 })
98 })
99​
100 test('should compile validator method', async () => {
101 const code = `
102 import { createServerFn } from '@tanstack/react-start'
103 const myServerFn = createServerFn()
104 .validator((input: string) => input)
105 .handler(({ input }) => input)`
106​
107 const compiledResultClient = await compile({
108 code,
109 env: 'client',
110 isProviderFile: false,
111 mode: 'build',
112 })
113​
114 expect(compiledResultClient!.code).toMatchInlineSnapshot(`
115 "import { createClientRpc } from '@tanstack/react-start/client-rpc';
116 import { createServerFn } from '@tanstack/react-start';
117 const myServerFn = createServerFn().handler(createClientRpc(\"2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b\"));"
118 `)
119 })
120​
121 // Editors count \n, \r\n, a lone \r, U+2028 and U+2029 as line
122 // terminators, so diagnostic locations must count every one.
123 // TODO remove upon stable with the inputValidator deprecation, after moving
124 // these line terminator cases to another located diagnostic.
125 test.each([
126 ['\\n', '\n'],
127 ['\\r\\n', '\r\n'],
128 ['a lone \\r', '\r'],
129 ['U+2028', '\u2028'],
130 ['U+2029', '\u2029'],
131 ])(
132 'reports the inputValidator deprecation location with %s line endings',
133 async (_name, eol) => {
134 const warn = vi.fn()
135 await compile({
136 code: [
137 `import { createServerFn } from '@tanstack/react-start'`,
138 `export const fn = createServerFn().inputValidator((x: string) => x).handler(async () => 1)`,
139 ].join(eol),
140 env: 'client',
141 isProviderFile: false,
142 mode: 'build',
143 warn,
144 })
145​
146 expect(warn).toHaveBeenCalledWith(
147 '/test/src/test.ts:2:19 createServerFn().inputValidator() is deprecated. Use createServerFn().validator() instead.',
148 )
149 },
150 )
151​
152 // TODO remove upon stable
153 test('should warn for deprecated inputValidator method', async () => {
154 const warn = vi.fn()
155 const code = `
156 import { createServerFn } from '@tanstack/react-start'
157 const myServerFn = createServerFn()
158 .inputValidator((input: string) => input)
159 .handler(({ input }) => input)`
160​
161 await compile({
162 code,
163 env: 'client',
164 isProviderFile: false,
165 mode: 'build',
166 warn,
167 })
168​
169 expect(warn).toHaveBeenCalledWith(
170 expect.stringContaining(
171 'createServerFn().inputValidator() is deprecated. Use createServerFn().validator() instead.',
172 ),
173 )
174 })
175​
176 test.each([
177 ['a lone \\r', '\r'],
178 ['U+2028', '\u2028'],
179 ])(
180 'frames compile errors on the right line with %s line terminators',
181 async (_name, eol) => {
182 const code = [
183 `import { createServerFn } from '@tanstack/react-start'`,
184 `const other = 1`,
185 `const { fn } = createServerFn().handler(async () => other)`,
186 ].join(eol)
187​
188 await expect(
189 compile({ code, env: 'client', isProviderFile: false, mode: 'build' }),
190 ).rejects.toThrow(
191 [
192 `2 | const other = 1`,
193 `3 | const { fn } = createServerFn().handler(async () => other)`,
194 ` | ^ createServerFn must be assigned to a simple identifier, not a destructuring pattern`,
195 ].join('\n'),
196 )
197 },
198 )
199​
200 test('should work with identifiers of functions', async () => {
201 const code = `
202 import { createServerFn } from '@tanstack/react-start'
203 const myFunc = () => {
204 return 'hello from the server'
205 }
206 const myServerFn = createServerFn().handler(myFunc)`
207​
208 const compiledResultClient = await compile({
209 code,
210 env: 'client',
211 isProviderFile: false,
212 mode: 'build',
213 })
214​
215 // Server caller (route file - no split param)
216 // Should NOT have the second argument since implementation comes from extracted chunk
217 const compiledResultServerCaller = await compile({
218 code,
219 env: 'server',
220 isProviderFile: false,
221 mode: 'build',
222 })
223​
224 // Server provider (extracted file - has split param)
225 // Should HAVE the second argument since this is the implementation file
226 const compiledResultServerProvider = await compile({
227 code,
228 env: 'server',
229 isProviderFile: true,
230 mode: 'build',
231 })
232​
233 expect(compiledResultClient!.code).toMatchInlineSnapshot(`
234 "import { createClientRpc } from '@tanstack/react-start/client-rpc';
235 import { createServerFn } from '@tanstack/react-start';
236 const myServerFn = createServerFn().handler(createClientRpc("2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b"));"
237 `)
238​
239 // Server caller: no second argument (implementation from extracted chunk)
240 expect(compiledResultServerCaller!.code).toMatchInlineSnapshot(`
241 "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc';
242 import { createServerFn } from '@tanstack/react-start';
243 const myServerFn = createServerFn().handler(createSsrRpc("2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b"));"
244 `)
245​
246 // Server provider: has second argument (this is the implementation file)
247 expect(compiledResultServerProvider!.code).toMatchInlineSnapshot(`
248 "import { createServerRpc } from '@tanstack/react-start/server-rpc';
249 import { createServerFn } from '@tanstack/react-start';
250 const myFunc = () => {
251 return 'hello from the server';
252 };
253 const myServerFn_createServerFn_handler = createServerRpc({ "id": "2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b", "name": "myServerFn", "filename": "src/test.ts" }, (opts) => myServerFn.__executeServer(opts));
254 const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc);
255 export { myServerFn_createServerFn_handler };"
256 `)
257 })
258​
259 test('should remove imports used only as caller handler identifiers', async () => {
260 const code = `
261 import { createServerFn } from '@tanstack/react-start'
262 import { getUsers } from './server'
263​
264 export const getUsersFn = createServerFn().handler(getUsers)
265 `
266​
267 const compiledResult = await compile({
268 code,
269 env: 'client',
270 isProviderFile: false,
271 mode: 'build',
272 })
273​
274 expect(compiledResult!.code).toMatchInlineSnapshot(`
275 "import { createClientRpc } from '@tanstack/react-start/client-rpc';
276 import { createServerFn } from '@tanstack/react-start';
277 export const getUsersFn = createServerFn().handler(createClientRpc(\"a78c63d4bb3c0b10a8b70902c73611fbf0b9229e0807b065c03c939f9c0ce100\"));"
278 `)
279 })
280​
281 test('should not remove handler identifier bindings that are still referenced', async () => {
282 const code = `
283 import { createServerFn } from '@tanstack/react-start'
284 import { getUsers } from './server'
285​
286 export const getUsersFn = createServerFn().handler(getUsers)
287 console.log(getUsers)
288 `
289​
290 const compiledResult = await compile({
291 code,
292 env: 'client',
293 isProviderFile: false,
294 mode: 'build',
295 })
296​
297 expect(compiledResult!.code).toMatchInlineSnapshot(`
298 "import { createClientRpc } from '@tanstack/react-start/client-rpc';
299 import { createServerFn } from '@tanstack/react-start';
300 import { getUsers } from './server';
301 export const getUsersFn = createServerFn().handler(createClientRpc(\"a78c63d4bb3c0b10a8b70902c73611fbf0b9229e0807b065c03c939f9c0ce100\"));
302 console.log(getUsers);"
303 `)
304 })
305​
306 test('should compile server functions wrapped in TypeScript as expressions', async () => {
307 const code = `
308 import { createServerFn } from '@tanstack/react-start'
309​
310 export const getUsersFn = createServerFn().handler(() => 'server') as any
311 `
312​
313 const compiledResult = await compile({
314 code,
315 env: 'client',
316 isProviderFile: false,
317 mode: 'build',
318 })
319​
320 expect(compiledResult).not.toBeNull()
321 expect(compiledResult!.code).toContain('createClientRpc')
322 expect(compiledResult!.code).not.toContain('server')
323 })
324​
325 test('should compile server functions wrapped in TypeScript satisfies expressions', async () => {
326 const code = `
327 import { createServerFn } from '@tanstack/react-start'
328​
329 export const getUsersFn = createServerFn().handler(() => 'server') satisfies unknown
330 `
331​
332 const compiledResult = await compile({
333 code,
334 env: 'client',
335 isProviderFile: false,
336 mode: 'build',
337 })
338​
339 expect(compiledResult).not.toBeNull()
340 expect(compiledResult!.code).toContain('createClientRpc')
341 expect(compiledResult!.code).not.toContain('server')
342 })
343​
344 test('should use dce by default', async () => {
345 const code = `
346 import { createServerFn } from '@tanstack/react-start'
347 const exportedVar = 'exported'
348 export const exportedFn = createServerFn().handler(async () => {
349 return exportedVar
350 })
351 const nonExportedVar = 'non-exported'
352 const nonExportedFn = createServerFn().handler(async () => {
353 return nonExportedVar
354 })`
355​
356 // Client
357 const compiledResult = await compile({
358 code,
359 env: 'client',
360 isProviderFile: false,
361 mode: 'build',
362 })
363​
364 expect(compiledResult!.code).toMatchInlineSnapshot(`
365 "import { createClientRpc } from '@tanstack/react-start/client-rpc';
366 import { createServerFn } from '@tanstack/react-start';
367 export const exportedFn = createServerFn().handler(createClientRpc("c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864"));
368 const nonExportedFn = createServerFn().handler(createClientRpc("f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2"));"
369 `)
370​
371 // Server caller (route file) - no second argument
372 const compiledResultServerCaller = await compile({
373 code,
374 env: 'server',
375 isProviderFile: false,
376 mode: 'build',
377 })
378​
379 expect(compiledResultServerCaller!.code).toMatchInlineSnapshot(`
380 "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc';
381 import { createServerFn } from '@tanstack/react-start';
382 export const exportedFn = createServerFn().handler(createSsrRpc("c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864"));
383 const nonExportedFn = createServerFn().handler(createSsrRpc("f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2"));"
384 `)
385​
386 // Server provider (extracted file) - has second argument
387 const compiledResultServerProvider = await compile({
388 code,
389 env: 'server',
390 isProviderFile: true,
391 mode: 'build',
392 })
393​
394 expect(compiledResultServerProvider!.code).toMatchInlineSnapshot(`
395 "import { createServerRpc } from '@tanstack/react-start/server-rpc';
396 import { createServerFn } from '@tanstack/react-start';
397 const exportedVar = 'exported';
398 const exportedFn_createServerFn_handler = createServerRpc({ "id": "c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864", "name": "exportedFn", "filename": "src/test.ts" }, (opts) => exportedFn.__executeServer(opts));
399 const exportedFn = createServerFn().handler(exportedFn_createServerFn_handler, async () => {
400 return exportedVar;
401 });
402 const nonExportedVar = 'non-exported';
403 const nonExportedFn_createServerFn_handler = createServerRpc({ "id": "f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2", "name": "nonExportedFn", "filename": "src/test.ts" }, (opts) => nonExportedFn.__executeServer(opts));
404 const nonExportedFn = createServerFn().handler(nonExportedFn_createServerFn_handler, async () => {
405 return nonExportedVar;
406 });
407 export { exportedFn_createServerFn_handler, nonExportedFn_createServerFn_handler };"
408 `)
409 })
410​
411 test('should use fast path for direct imports from known library (no extra resolveId calls)', async () => {
412 const code = `
413 import { createServerFn } from '@tanstack/react-start'
414 const myServerFn = createServerFn().handler(async () => {
415 return 'hello'
416 })`
417​
418 const resolveIdMock = vi.fn(async (id: string) => id)
419​
420 const compiler = new StartCompiler({
421 env: 'client',
422 ...getDefaultTestOptions('client'),
423 loadModule: async () => {},
424 lookupKinds: new Set(['ServerFn']),
425 lookupConfigurations: [
426 {
427 libName: '@tanstack/react-start',
428 rootExport: 'createServerFn',
429 kind: 'Root',
430 },
431 ],
432 getKnownServerFns: () => ({}),
433 resolveId: resolveIdMock,
434 mode: 'build',
435 })
436​
437 await compiler.compile({
438 code,
439 id: '/test/src/test.ts',
440 })
441​
442 // Direct known-library imports use the knownRootImports fast path, so they
443 // do not need resolveId.
444 expect(resolveIdMock).not.toHaveBeenCalled()
445 })
446​
447 test('should use slow path for factory pattern (resolveId called for import resolution)', async () => {
448 // This simulates a factory pattern where createServerFn is re-exported from a local file
449 const factoryCode = `
450 import { createFooServerFn } from './factory'
451 const myServerFn = createFooServerFn().handler(async () => {
452 return 'hello'
453 })`
454​
455 const resolveIdMock = vi.fn(async (id: string) => id)
456​
457 const compiler = new StartCompiler({
458 env: 'client',
459 ...getDefaultTestOptions('client'),
460 loadModule: async (id) => {
461 // Simulate the factory module being loaded
462 if (id === './factory') {
463 compiler.ingestModule({
464 code: `
465 import { createServerFn } from '@tanstack/react-start'
466 export const createFooServerFn = createServerFn
467 `,
468 id: './factory',
469 })
470 }
471 },
472 lookupKinds: new Set(['ServerFn']),
473 lookupConfigurations: [
474 {
475 libName: '@tanstack/react-start',
476 rootExport: 'createServerFn',
477 kind: 'Root',
478 },
479 ],
480 getKnownServerFns: () => ({}),
481 resolveId: resolveIdMock,
482 mode: 'build',
483 })
484​
485 await compiler.compile({
486 code: factoryCode,
487 id: '/test/src/test.ts',
488 })
489​
490 // resolveId should only be called for './factory'. Direct known-library
491 // imports use the knownRootImports fast path.
492 //
493 // Note: The factory module's import from '@tanstack/react-start' ALSO uses
494 // the fast path (knownRootImports), so no additional resolveId call is needed there.
495 expect(resolveIdMock).toHaveBeenCalledTimes(1)
496 expect(resolveIdMock).toHaveBeenNthCalledWith(
497 1,
498 './factory',
499 '/test/src/test.ts',
500 )
501 })
502​
503 test('keeps query-bearing virtual module identities distinct', async () => {
504 const publicFactoryId = '\0virtual:server-fn-factory?variant=public'
505 const implementationFactoryId =
506 '\0virtual:server-fn-factory?variant=implementation'
507 const virtualModules: Record<string, string> = {
508 [publicFactoryId]: `
509 import { createIssueServerFn } from 'virtual:server-fn-factory?variant=implementation'
510 export { createIssueServerFn }
511 `,
512 [implementationFactoryId]: `
513 import { createServerFn } from '@tanstack/react-start'
514 export const createIssueServerFn = createServerFn
515 `,
516 }
517 const loadedIds: Array<string> = []
518​
519 const compiler = new StartCompiler({
520 env: 'client',
521 ...getDefaultTestOptions('client'),
522 mode: 'build',
523 loadModule: async (id) => {
524 loadedIds.push(id)
525 const code = virtualModules[id]
526 if (code) {
527 compiler.ingestModule({ code, id })
528 }
529 },
530 lookupKinds: new Set(['ServerFn']),
531 lookupConfigurations: [
532 {
533 libName: '@tanstack/react-start',
534 rootExport: 'createServerFn',
535 kind: 'Root',
536 },
537 ],
538 getKnownServerFns: () => ({}),
539 resolveId: async (source) => {
540 if (source.startsWith('virtual:server-fn-factory?')) {
541 return `\0${source}`
542 }
543​
544 return null
545 },
546 })
547​
548 const result = await compiler.compile({
549 id: '/test/src/test.ts',
550 code: `
551 import { createIssueServerFn } from 'virtual:server-fn-factory?variant=public'
552 const issueServerFn = createIssueServerFn().handler(async () => 'ok')
553 `,
554 })
555​
556 expect(result).not.toBeNull()
557 expect(result!.code).toContain('createClientRpc')
558 expect(loadedIds).toEqual([publicFactoryId, implementationFactoryId])
559 })
560​
561 test('should resolve local named re-exports of createServerFn', async () => {
562 const code = `
563 import { createFooServerFn } from './factory'
564 const myServerFn = createFooServerFn().handler(async () => {
565 return 'hello'
566 })`
567​
568 const resolveIdMock = vi.fn(async (id: string) => id)
569​
570 const compiler = new StartCompiler({
571 env: 'client',
572 ...getDefaultTestOptions('client'),
573 loadModule: async (id) => {
574 if (id === './factory') {
575 compiler.ingestModule({
576 code: `
577 export { createServerFn as createFooServerFn } from '@tanstack/react-start'
578 `,
579 id: './factory',
580 })
581 }
582 },
583 lookupKinds: new Set(['ServerFn']),
584 lookupConfigurations: [
585 {
586 libName: '@tanstack/react-start',
587 rootExport: 'createServerFn',
588 kind: 'Root',
589 },
590 ],
591 getKnownServerFns: () => ({}),
592 resolveId: resolveIdMock,
593 mode: 'build',
594 })
595​
596 const result = await compiler.compile({
597 code,
598 id: '/test/src/test.ts',
599 })
600​
601 expect(result).not.toBeNull()
602 expect(result!.code).toContain('createClientRpc')
603 expect(resolveIdMock).toHaveBeenCalledTimes(1)
604 expect(resolveIdMock).toHaveBeenNthCalledWith(
605 1,
606 './factory',
607 '/test/src/test.ts',
608 )
609 })
610​
611 test('should resolve export-star re-export chains of createServerFn', async () => {
612 const code = `
613 import { createFooServerFn } from './factory'
614 const myServerFn = createFooServerFn().handler(async () => {
615 return 'hello'
616 })`
617​
618 const resolveIdMock = vi.fn(async (id: string) => id)
619​
620 const compiler = new StartCompiler({
621 env: 'client',
622 ...getDefaultTestOptions('client'),
623 loadModule: async (id) => {
624 if (id === './factory') {
625 compiler.ingestModule({
626 code: `
627 export * from './factory-inner'
628 `,
629 id: './factory',
630 })
631 }
632​
633 if (id === './factory-inner') {
634 compiler.ingestModule({
635 code: `
636 export { createServerFn as createFooServerFn } from '@tanstack/react-start'
637 `,
638 id: './factory-inner',
639 })
640 }
641 },
642 lookupKinds: new Set(['ServerFn']),
643 lookupConfigurations: [
644 {
645 libName: '@tanstack/react-start',
646 rootExport: 'createServerFn',
647 kind: 'Root',
648 },
649 ],
650 getKnownServerFns: () => ({}),
651 resolveId: resolveIdMock,
652 mode: 'build',
653 })
654​
655 const result = await compiler.compile({
656 code,
657 id: '/test/src/test.ts',
658 })
659​
660 expect(result).not.toBeNull()
661 expect(result!.code).toContain('createClientRpc')
662 expect(resolveIdMock).toHaveBeenCalledTimes(2)
663 expect(resolveIdMock).toHaveBeenNthCalledWith(
664 1,
665 './factory',
666 '/test/src/test.ts',
667 )
668 expect(resolveIdMock).toHaveBeenNthCalledWith(
669 2,
670 './factory-inner',
671 './factory',
672 )
673 })
674​
675 test('reuses deduped custom IDs across compiler instances', async () => {
676 const serverFnsById: Record<
677 string,
678 {
679 functionName: string
680 functionId: string
681 extractedFilename: string
682 filename: string
683 isClientReferenced?: boolean
684 }
685 > = {}
686​
687 function createCompiler() {
688 return new StartCompiler({
689 env: 'server',
690 ...getDefaultTestOptions('server'),
691 mode: 'build',
692 loadModule: async () => {},
693 lookupKinds: new Set(['ServerFn']),
694 lookupConfigurations: [
695 {
696 libName: '@tanstack/react-start',
697 rootExport: 'createServerFn',
698 kind: 'Root',
699 },
700 ],
701 resolveId: async (id) => id,
702 generateFunctionId: ({ functionName }) =>
703 functionName === 'greetUser_createServerFn_handler'
704 ? 'constant_id'
705 : undefined,
706 getKnownServerFns: () => serverFnsById,
707 onServerFnsById: (discovered) => {
708 Object.assign(serverFnsById, discovered)
709 },
710 })
711 }
712​
713 const firstCompiler = createCompiler()
714 await firstCompiler.compile({
715 code: `
716 import { createServerFn } from '@tanstack/react-start'
717 export const greetUser = createServerFn().handler(async () => 'first')
718 `,
719 id: '/test/src/submit-post-formdata.tsx',
720 })
721​
722 await firstCompiler.compile({
723 code: `
724 import { createServerFn } from '@tanstack/react-start'
725 export const greetUser = createServerFn().handler(async () => 'second')
726 `,
727 id: '/test/src/formdata-redirect/index.tsx',
728 })
729​
730 expect(
731 Object.values(serverFnsById)
732 .map((serverFn) => serverFn.functionId)
733 .sort(),
734 ).toEqual(['constant_id', 'constant_id_1'])
735​
736 const secondCompiler = createCompiler()
737 const firstResult = await secondCompiler.compile({
738 code: `
739 import { createServerFn } from '@tanstack/react-start'
740 export const greetUser = createServerFn().handler(async () => 'first')
741 `,
742 id: '/test/src/submit-post-formdata.tsx',
743 })
744​
745 const secondResult = await secondCompiler.compile({
746 code: `
747 import { createServerFn } from '@tanstack/react-start'
748 export const greetUser = createServerFn().handler(async () => 'second')
749 `,
750 id: '/test/src/formdata-redirect/index.tsx',
751 })
752​
753 expect(firstResult!.code).toContain('createSsrRpc("constant_id"')
754 expect(secondResult!.code).toContain('createSsrRpc("constant_id_1"')
755 })
756​
757 test('should resolve createServerFn from the same binding as a known root export', async () => {
758 const virtualModules: Record<string, string> = {
759 '@tanstack/start-client-core': `
760 export { createServerFn } from './createServerFn'
761 `,
762 '/virtual/compiler-known/server-fn-factory.ts': `
763 export const createServerFn = () => ({
764 handler: () => createServerFn(),
765 })
766 `,
767 }
768​
769 const compiler = new StartCompiler({
770 env: 'client',
771 ...getDefaultTestOptions('client'),
772 root: '/test',
773 mode: 'build',
774 loadModule: async (id) => {
775 const code = virtualModules[id]
776 if (code) {
777 compiler.ingestModule({ code, id })
778 }
779 },
780 lookupKinds: new Set(['ServerFn']),
781 lookupConfigurations: [],
782 getKnownServerFns: () => ({}),
783 resolveId: async (source) => {
784 if (source === '@tanstack/start-client-core') {
785 return '@tanstack/start-client-core'
786 }
787​
788 if (source === './createServerFn') {
789 return '/virtual/compiler-known/server-fn-factory.ts'
790 }
791​
792 return null
793 },
794 })
795​
796 const result = await compiler.compile({
797 id: '/test/src/internal-server-fn.ts',
798 code: `
799 import { createServerFn } from './createServerFn'
800​
801 export const getMessage = createServerFn().handler(() => {
802 return 'server-only-value'
803 })
804 `,
805 })
806​
807 expect(result).not.toBeNull()
808 expect(result!.code).toContain('createClientRpc')
809 expect(result!.code).not.toContain('server-only-value')
810 })
811})