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

code-splitter.test.ts

954 lines29.1 KB

1import { readFile, readdir } from 'node:fs/promises'
2import path from 'node:path'
3import { describe, expect, it } from 'vitest'
4import { analyzeModule, createIdentifier } from '@tanstack/router-utils'
5import { BindingFlags } from 'yuku-analyzer'
6​
7import {
8 analyzeRouteModule,
9 compileCodeSplitReferenceRoute,
10 compileCodeSplitSharedRoute,
11 compileCodeSplitVirtualRoute,
12 computeSharedBindings,
13} from '../src/core/code-splitter/compilers'
14import { defaultCodeSplitGroupings } from '../src/core/constants'
15import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins'
16import { frameworks } from './constants'
17import type { CodeSplitGroupings } from '../src/core/constants'
18​
19function getFrameworkDir(framework: string) {
20 const files = path.resolve(
21 __dirname,
22 `./code-splitter/test-files/${framework}`,
23 )
24 const snapshots = path.resolve(
25 __dirname,
26 `./code-splitter/snapshots/${framework}`,
27 )
28 return { files, snapshots }
30​
31const testGroups: Array<{ name: string; groupings: CodeSplitGroupings }> = [
32 {
33 name: '1-default',
34 groupings: defaultCodeSplitGroupings,
35 },
36 {
37 name: '2-components-combined-loader-separate',
38 groupings: [
39 ['loader'],
40 ['component', 'pendingComponent', 'errorComponent', 'notFoundComponent'],
41 ],
42 },
43 {
44 name: '3-all-combined-errorComponent-separate',
45 groupings: [
46 ['loader', 'component', 'pendingComponent', 'notFoundComponent'],
47 ['errorComponent'],
48 ],
49 },
51​
52describe('one route analysis shared by every output', () => {
53 const code = `'use client';
54import { createFileRoute } from '@tanstack/react-router'
55const state = {count: 0}
56export const Route = createFileRoute('/')({loader: () => state, component: () => state.count})`
57​
58 function compileOutputs() {
59 const analysis = analyzeRouteModule({ code, filename: 'route.tsx' })
60 const sharedBindings = computeSharedBindings({
61 code,
62 analysis,
63 codeSplitGroupings: defaultCodeSplitGroupings,
64 })
65 return {
66 reference: () =>
67 compileCodeSplitReferenceRoute({
68 code,
69 analysis,
70 sharedBindings,
71 filename: 'route.tsx',
72 id: 'route.tsx',
73 targetFramework: 'react',
74 addHmr: false,
75 codeSplitGroupings: defaultCodeSplitGroupings,
76 })!.code,
77 component: () =>
78 compileCodeSplitVirtualRoute({
79 code,
80 analysis,
81 sharedBindings,
82 filename: 'route.tsx?tsr-split=component',
83 splitTargets: ['component'],
84 }).code,
85 shared: () =>
86 compileCodeSplitSharedRoute({
87 code,
88 analysis,
89 sharedBindings,
90 filename: 'route.tsx?tsr-shared=1',
91 }).code,
92 }
93 }
94​
95 it('compiles the same outputs whatever order they are generated in', () => {
96 const first = compileOutputs()
97 const componentFirst = first.component()
98 const referenceSecond = first.reference()
99 const sharedThird = first.shared()
100 const second = compileOutputs()
101 expect([second.shared(), second.reference(), second.component()]).toEqual([
102 sharedThird,
103 referenceSecond,
104 componentFirst,
105 ])
106 expect([first.reference(), first.component(), first.shared()]).toEqual([
107 referenceSecond,
108 componentFirst,
109 sharedThird,
110 ])
111 })
112​
113 it('keeps "use client" first in the reference, split and shared outputs', () => {
114 const outputs = compileOutputs()
115 for (const output of [
116 outputs.reference(),
117 outputs.component(),
118 outputs.shared(),
119 ]) {
120 expect(output).toMatch(/^['"]use client['"]/)
121 }
122 })
123})
124​
125describe('code-splitter works', () => {
126 describe.each(frameworks)('FRAMEWORK=%s', (framework) => {
127 describe.each(testGroups)(
128 'SPLIT_GROUP=$name',
129 async ({ groupings: grouping, name: groupName }) => {
130 const dirs = getFrameworkDir(framework)
131 const filenames = await readdir(dirs.files)
132​
133 it.each(filenames)(
134 `should compile "reference" for "%s"`,
135 async (filename) => {
136 const file = await readFile(path.join(dirs.files, filename))
137 const code = file.toString()
138​
139 const sharedBindings = computeSharedBindings({
140 code,
141 codeSplitGroupings: grouping,
142 })
143​
144 const compileResult = compileCodeSplitReferenceRoute({
145 code,
146 filename,
147 id: filename,
148 addHmr: false,
149 codeSplitGroupings: grouping,
150 targetFramework: framework,
151 sharedBindings:
152 sharedBindings.size > 0 ? sharedBindings : undefined,
153 })
154 if (compileResult) {
155 analyzeModule({ code: compileResult.code, filename })
156 }
157​
158 await expect(compileResult?.code || code).toMatchFileSnapshot(
159 path.join(dirs.snapshots, groupName, filename),
160 )
161 },
162 )
163​
164 it.each(filenames)(
165 `should compile "virtual" for "%s"`,
166 async (filename) => {
167 const file = await readFile(path.join(dirs.files, filename))
168 const code = file.toString()
169​
170 const sharedBindings = computeSharedBindings({
171 code,
172 codeSplitGroupings: grouping,
173 })
174​
175 for (const targets of grouping) {
176 const ident = createIdentifier(targets)
177​
178 const splitResult = compileCodeSplitVirtualRoute({
179 code,
180 filename: `${filename}?${ident}`,
181 splitTargets: targets,
182 sharedBindings:
183 sharedBindings.size > 0 ? sharedBindings : undefined,
184 })
185 analyzeModule({ code: splitResult.code, filename })
186​
187 const snapshotFilename = path.join(
188 dirs.snapshots,
189 groupName,
190 `${filename.replace('.tsx', '')}@${ident}.tsx`,
191 )
192 await expect(splitResult.code).toMatchFileSnapshot(
193 snapshotFilename,
194 )
195 }
196 },
197 )
198​
199 it.each(filenames)(
200 `should compile "shared" for "%s"`,
201 async (filename) => {
202 const file = await readFile(path.join(dirs.files, filename))
203 const code = file.toString()
204​
205 const sharedBindings = computeSharedBindings({
206 code,
207 codeSplitGroupings: grouping,
208 })
209​
210 const snapshotFilename = path.join(
211 dirs.snapshots,
212 groupName,
213 `${filename.replace('.tsx', '')}@shared.tsx`,
214 )
215​
216 if (sharedBindings.size === 0) {
217 // No shared module β€” snapshot should be empty string
218 await expect('').toMatchFileSnapshot(snapshotFilename)
219 return
220 }
221​
222 const sharedResult = compileCodeSplitSharedRoute({
223 code,
224 sharedBindings,
225 filename: `${filename}?tsr-shared=1`,
226 })
227 analyzeModule({ code: sharedResult.code, filename })
228​
229 await expect(sharedResult.code).toMatchFileSnapshot(
230 snapshotFilename,
231 )
232 },
233 )
234 },
235 )
236 })
237})
238​
239describe('React Refresh virtual route compiler plugin', () => {
240 const splitComponentCases = [
241 { splitType: 'component', splitIdentifier: 'SplitComponent' },
242 {
243 splitType: 'pendingComponent',
244 splitIdentifier: 'SplitPendingComponent',
245 },
246 { splitType: 'errorComponent', splitIdentifier: 'SplitErrorComponent' },
247 ] as const
248​
249 function createRouteCode(splitType: string) {
250 return `
251import { createFileRoute } from '@tanstack/react-router'
252​
253export const Route = createFileRoute('/')({ ${splitType} })
254​
255function ${splitType}() {
256 return <div>lowercase function declaration</div>
259 }
260​
261 it.each(splitComponentCases)(
262 'renames a lowercase $splitType binding when HMR is enabled',
263 ({ splitType, splitIdentifier }) => {
264 const result = compileCodeSplitVirtualRoute({
265 code: createRouteCode(splitType),
266 filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`,
267 splitTargets: [splitType],
268 compilerPlugins: getFrameworkHmrCompilerPlugins({
269 targetFramework: 'react',
270 }),
271 })
272​
273 expect(result.code).toContain(`function ${splitIdentifier}()`)
274 expect(result.code).toContain(
275 `export { ${splitIdentifier} as ${splitType} }`,
276 )
277 },
278 )
279​
280 it.each(splitComponentCases)(
281 'keeps a lowercase $splitType binding when HMR is disabled',
282 ({ splitType }) => {
283 const result = compileCodeSplitVirtualRoute({
284 code: createRouteCode(splitType),
285 filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`,
286 splitTargets: [splitType],
287 })
288​
289 expect(result.code).toContain(`function ${splitType}()`)
290 expect(result.code).toContain(`export { ${splitType} }`)
291 },
292 )
293})
294​
295describe('computeSharedBindings fast paths', () => {
296 it('returns empty when only one split group is present (default groupings)', () => {
297 const code = `
298import { createFileRoute } from '@tanstack/react-router'
299const shared = 42
300export const Route = createFileRoute('/')({
301 component: () => shared,
302})
304 const result = computeSharedBindings({
305 code,
306 codeSplitGroupings: defaultCodeSplitGroupings,
307 })
308 expect(result.size).toBe(0)
309 })
310​
311 it('returns empty when all split props are in the same group', () => {
312 const code = `
313import { createFileRoute } from '@tanstack/react-router'
314const shared = 42
315export const Route = createFileRoute('/')({
316 component: () => shared,
317 loader: () => shared,
318})
320 const result = computeSharedBindings({
321 code,
322 codeSplitGroupings: [['component', 'loader']],
323 })
324 expect(result.size).toBe(0)
325 })
326​
327 it('returns empty when all route option values are undefined', () => {
328 const code = `
329import { createFileRoute } from '@tanstack/react-router'
330export const Route = createFileRoute('/')({
331 component: undefined,
332 errorComponent: undefined,
333 notFoundComponent: undefined,
334})
336 const result = computeSharedBindings({
337 code,
338 codeSplitGroupings: defaultCodeSplitGroupings,
339 })
340 expect(result.size).toBe(0)
341 })
342​
343 it('returns empty when no local bindings exist (only imports + Route)', () => {
344 const code = `
345import { createFileRoute } from '@tanstack/react-router'
346export const Route = createFileRoute('/')({
347 component: () => <div>hello</div>,
348 errorComponent: () => <div>error</div>,
349})
351 const result = computeSharedBindings({
352 code,
353 codeSplitGroupings: defaultCodeSplitGroupings,
354 })
355 expect(result.size).toBe(0)
356 })
357​
358 it('does not fast-path when there is a non-split and a split group', () => {
359 const code = `
360import { createFileRoute } from '@tanstack/react-router'
361const shared = 42
362export const Route = createFileRoute('/')({
363 component: () => shared,
364 beforeLoad: () => shared,
365})
367 const result = computeSharedBindings({
368 code,
369 codeSplitGroupings: defaultCodeSplitGroupings,
370 })
371 expect(result).toContain('shared')
372 })
373})
374​
375// ============================================================================
376// Invariant Tests on computeSharedBindings
377//
378// These verify the core "contracts" of the shared bindings computation:
379// - Route is never extracted
380// - Results are always real local bindings
381// - Destructured cohesion holds
382// - Transitive dependencies are included
383// - Route-dependent bindings are excluded
384// ============================================================================
385​
386describe('computeSharedBindings invariants', () => {
387 const defaultGroupings = defaultCodeSplitGroupings
388​
389 function getLocalBindings(code: string): Set<string> {
390 return new Set(
391 analyzeModule({ code })
392 .rootScope.bindings.filter(
393 (binding) =>
394 !binding.has(BindingFlags.Import) && binding.name !== 'Route',
395 )
396 .map((binding) => binding.name),
397 )
398 }
399​
400 it('INVARIANT: Route is never in the shared set', () => {
401 const code = `
402import { createFileRoute } from '@tanstack/react-router'
403const shared = 42
404export const Route = createFileRoute('/')({
405 component: () => shared,
406 beforeLoad: () => shared,
407})
409 const result = computeSharedBindings({
410 code,
411 codeSplitGroupings: defaultGroupings,
412 })
413 expect(result.has('Route')).toBe(false)
414 })
415​
416 it('INVARIANT: all results are actual local bindings from the source', () => {
417 const code = `
418import { createFileRoute } from '@tanstack/react-router'
419import { external } from 'somewhere'
420const config = { url: external, timeout: 5000 }
421const fetcher = (path) => fetch(config.url + path)
422export const Route = createFileRoute('/')({
423 loader: () => fetcher('/data'),
424 component: () => <div>{config.timeout}</div>,
425})
427 const result = computeSharedBindings({
428 code,
429 codeSplitGroupings: defaultGroupings,
430 })
431 const localBindings = getLocalBindings(code)
432​
433 for (const name of result) {
434 expect(localBindings.has(name)).toBe(true)
435 }
436 })
437​
438 it('INVARIANT: imports are never in the shared set', () => {
439 const code = `
440import { createFileRoute } from '@tanstack/react-router'
441import { helper } from './utils'
442export const Route = createFileRoute('/')({
443 loader: () => helper(),
444 component: () => <div>{helper()}</div>,
445})
447 const result = computeSharedBindings({
448 code,
449 codeSplitGroupings: defaultGroupings,
450 })
451 expect(result.has('helper')).toBe(false)
452 })
453​
454 it('INVARIANT: vars declared inside nested statements are never shared', () => {
455 const code = `
456import { createFileRoute } from '@tanstack/react-router'
457if (typeof window !== 'undefined') { var inBlock = 1 }
458if (typeof window !== 'undefined') var inStatement = 2
459export const Route = createFileRoute('/')({
460 loader: () => [inBlock, inStatement],
461 component: () => <div>{inBlock}{inStatement}</div>,
462})
464 const result = computeSharedBindings({
465 code,
466 codeSplitGroupings: defaultGroupings,
467 })
468 expect([...result]).toEqual([])
469 })
470​
471 it('INVARIANT: destructured siblings are either all shared or none shared', () => {
472 const code = `
473import { createFileRoute } from '@tanstack/react-router'
474const { a, b, c } = createHelpers()
475export const Route = createFileRoute('/')({
476 loader: () => a,
477 component: () => <div>{b}</div>,
478})
480 const result = computeSharedBindings({
481 code,
482 codeSplitGroupings: defaultGroupings,
483 })
484​
485 // If any destructured sibling is shared, all must be
486 const siblings = ['a', 'b', 'c']
487 const sharedSiblings = siblings.filter((s) => result.has(s))
488 if (sharedSiblings.length > 0) {
489 expect(sharedSiblings.length).toBe(siblings.length)
490 }
491 })
492​
493 it('INVARIANT: transitive dependencies of shared bindings are also shared', () => {
494 const code = `
495import { createFileRoute } from '@tanstack/react-router'
496const BASE = 'https://api.example.com'
497const config = { url: BASE }
498const fetcher = () => fetch(config.url)
499export const Route = createFileRoute('/')({
500 loader: () => fetcher(),
501 component: () => <div>{config.url}</div>,
502})
504 const result = computeSharedBindings({
505 code,
506 codeSplitGroupings: defaultGroupings,
507 })
508​
509 // If config is shared (referenced by both loader via fetcher and component directly),
510 // then BASE (which config depends on) should also be shared
511 if (result.has('config')) {
512 expect(result.has('BASE')).toBe(true)
513 }
514 })
515​
516 it('INVARIANT: bindings depending on Route are excluded from shared', () => {
517 const code = `
518import { createFileRoute } from '@tanstack/react-router'
519const HEADER = 'Page'
520function usePageTitle() {
521 return HEADER + ' - ' + Route.fullPath
523export const Route = createFileRoute('/about')({
524 loader: () => usePageTitle(),
525 component: () => <div>{usePageTitle()}</div>,
526})
528 const result = computeSharedBindings({
529 code,
530 codeSplitGroupings: defaultGroupings,
531 })
532​
533 // usePageTitle references Route, so it must NOT be shared
534 expect(result.has('usePageTitle')).toBe(false)
535 // HEADER is only referenced by usePageTitle which depends on Route,
536 // so HEADER should also not be shared (unless it has other references)
537 })
538​
539 it('INVARIANT: single-group-only bindings are never shared', () => {
540 const code = `
541import { createFileRoute } from '@tanstack/react-router'
542const loaderOnly = () => fetch('/api')
543const componentOnly = () => <span>hi</span>
544const shared = 42
545export const Route = createFileRoute('/')({
546 loader: () => { loaderOnly(); return shared },
547 component: () => <div>{componentOnly()} {shared}</div>,
548})
550 const result = computeSharedBindings({
551 code,
552 codeSplitGroupings: defaultGroupings,
553 })
554​
555 // loaderOnly is only used by loader (non-split), should NOT be shared
556 expect(result.has('loaderOnly')).toBe(false)
557 // componentOnly is only used by component (split), should NOT be shared
558 expect(result.has('componentOnly')).toBe(false)
559 // shared IS used by both groups
560 expect(result.has('shared')).toBe(true)
561 })
562​
563 it('INVARIANT: empty result for unsplittable routes (createRootRoute)', () => {
564 const code = `
565import { createRootRoute } from '@tanstack/react-router'
566const shared = 42
567export const Route = createRootRoute({
568 component: () => <div>{shared}</div>,
569 beforeLoad: () => shared,
570})
572 const result = computeSharedBindings({
573 code,
574 codeSplitGroupings: defaultGroupings,
575 })
576 expect(result.size).toBe(0)
577 })
578​
579 it('INVARIANT: result is stable across multiple calls with same input', () => {
580 const code = `
581import { createFileRoute } from '@tanstack/react-router'
582const shared = { name: 'test' }
583export const Route = createFileRoute('/')({
584 loader: () => shared.name,
585 component: () => <div>{shared.name}</div>,
586})
588 const opts = { code, codeSplitGroupings: defaultGroupings }
589 const result1 = computeSharedBindings(opts)
590 const result2 = computeSharedBindings(opts)
591 const result3 = computeSharedBindings(opts)
592​
593 expect(result1).toEqual(result2)
594 expect(result2).toEqual(result3)
595 })
596})
597​
598// ============================================================================
599// Small-Scope Exhaustive Tests
600//
601// Inspired by Alloy's "small scope hypothesis" β€” most bugs show up in small
602// counterexamples. We exhaustively test all combinations of:
603// - binding declaration types (const, function, class)
604// - route property configurations (loader+component, loader+errorComponent, etc.)
605// - split grouping configurations
606// ============================================================================
607​
608describe('small-scope exhaustive: computeSharedBindings', () => {
609 // Helper to generate a route file with specific binding configurations
610 function makeRouteCode(opts: {
611 bindings: Array<{ name: string; kind: 'const' | 'function' | 'class' }>
612 loaderRefs: Array<string>
613 componentRefs: Array<string>
614 errorComponentRefs?: Array<string>
615 beforeLoadRefs?: Array<string>
616 }): string {
617 const bindingDecls = opts.bindings
618 .map((b) => {
619 switch (b.kind) {
620 case 'const':
621 return `const ${b.name} = 42`
622 case 'function':
623 return `function ${b.name}() { return 42 }`
624 case 'class':
625 return `class ${b.name} { value = 42 }`
626 }
627 })
628 .join('\n')
629​
630 const loaderBody =
631 opts.loaderRefs.length > 0
632 ? opts.loaderRefs.map((r) => `${r}`).join('; ')
633 : '42'
634​
635 const componentBody =
636 opts.componentRefs.length > 0
637 ? opts.componentRefs.map((r) => `{${r}}`).join('')
638 : 'hello'
639​
640 const props: Array<string> = [
641 ` loader: () => { return ${loaderBody} }`,
642 ` component: () => <div>${componentBody}</div>`,
643 ]
644​
645 if (opts.errorComponentRefs) {
646 const body =
647 opts.errorComponentRefs.length > 0
648 ? opts.errorComponentRefs.map((r) => `{${r}}`).join('')
649 : 'error'
650 props.push(` errorComponent: () => <div>${body}</div>`)
651 }
652​
653 if (opts.beforeLoadRefs) {
654 const body =
655 opts.beforeLoadRefs.length > 0
656 ? opts.beforeLoadRefs.map((r) => `${r}`).join('; ')
657 : '42'
658 props.push(` beforeLoad: () => { return ${body} }`)
659 }
660​
661 return `
662import { createFileRoute } from '@tanstack/react-router'
663${bindingDecls}
664export const Route = createFileRoute('/')({
665${props.join(',\n')}
666})
668 }
669​
670 // Exhaustively test 1-binding scenarios with all grouping configs
671 const groupingConfigs: Array<{
672 name: string
673 groupings: CodeSplitGroupings
674 }> = [
675 { name: 'default', groupings: defaultCodeSplitGroupings },
676 {
677 name: 'loader+components-combined',
678 groupings: [
679 ['loader'],
680 [
681 'component',
682 'pendingComponent',
683 'errorComponent',
684 'notFoundComponent',
685 ],
686 ],
687 },
688 ]
689​
690 const bindingKinds = ['const', 'function', 'class'] as const
691​
692 describe('single binding Γ— all property combinations', () => {
693 // For each binding kind Γ— each grouping Γ— each reference pattern,
694 // verify invariants hold
695 for (const kind of bindingKinds) {
696 for (const { name: groupName, groupings } of groupingConfigs) {
697 // Pattern: binding used only by loader (non-split) β†’ never shared
698 it(`${kind} used only by loader [${groupName}] β†’ not shared`, () => {
699 const code = makeRouteCode({
700 bindings: [{ name: 'x', kind }],
701 loaderRefs: ['x'],
702 componentRefs: [],
703 })
704 const result = computeSharedBindings({
705 code,
706 codeSplitGroupings: groupings,
707 })
708 expect(result.has('x')).toBe(false)
709 })
710​
711 // Pattern: binding used only by component (split) β†’ never shared
712 it(`${kind} used only by component [${groupName}] β†’ not shared`, () => {
713 const code = makeRouteCode({
714 bindings: [{ name: 'x', kind }],
715 loaderRefs: [],
716 componentRefs: ['x'],
717 })
718 const result = computeSharedBindings({
719 code,
720 codeSplitGroupings: groupings,
721 })
722 expect(result.has('x')).toBe(false)
723 })
724​
725 // Pattern: binding used by both loader AND component β†’ shared
726 it(`${kind} used by loader+component [${groupName}] β†’ shared`, () => {
727 const code = makeRouteCode({
728 bindings: [{ name: 'x', kind }],
729 loaderRefs: ['x'],
730 componentRefs: ['x'],
731 })
732 const result = computeSharedBindings({
733 code,
734 codeSplitGroupings: groupings,
735 })
736 expect(result.has('x')).toBe(true)
737 })
738​
739 // Pattern: binding used by component AND beforeLoad (non-split) β†’ shared
740 it(`${kind} used by component+beforeLoad [${groupName}] β†’ shared`, () => {
741 const code = makeRouteCode({
742 bindings: [{ name: 'x', kind }],
743 loaderRefs: [],
744 componentRefs: ['x'],
745 beforeLoadRefs: ['x'],
746 })
747 const result = computeSharedBindings({
748 code,
749 codeSplitGroupings: groupings,
750 })
751 expect(result.has('x')).toBe(true)
752 })
753 }
754 }
755 })
756​
757 describe('two bindings Γ— cross-group references', () => {
758 for (const { name: groupName, groupings } of groupingConfigs) {
759 // Both bindings in same group β†’ neither shared
760 it(`both in loader only [${groupName}] β†’ neither shared`, () => {
761 const code = makeRouteCode({
762 bindings: [
763 { name: 'a', kind: 'const' },
764 { name: 'b', kind: 'const' },
765 ],
766 loaderRefs: ['a', 'b'],
767 componentRefs: [],
768 })
769 const result = computeSharedBindings({
770 code,
771 codeSplitGroupings: groupings,
772 })
773 expect(result.has('a')).toBe(false)
774 expect(result.has('b')).toBe(false)
775 })
776​
777 // One binding per group β†’ neither shared
778 it(`one per group, no overlap [${groupName}] β†’ neither shared`, () => {
779 const code = makeRouteCode({
780 bindings: [
781 { name: 'a', kind: 'const' },
782 { name: 'b', kind: 'const' },
783 ],
784 loaderRefs: ['a'],
785 componentRefs: ['b'],
786 })
787 const result = computeSharedBindings({
788 code,
789 codeSplitGroupings: groupings,
790 })
791 expect(result.has('a')).toBe(false)
792 expect(result.has('b')).toBe(false)
793 })
794​
795 // Both in both groups β†’ both shared
796 it(`both in both groups [${groupName}] β†’ both shared`, () => {
797 const code = makeRouteCode({
798 bindings: [
799 { name: 'a', kind: 'const' },
800 { name: 'b', kind: 'const' },
801 ],
802 loaderRefs: ['a', 'b'],
803 componentRefs: ['a', 'b'],
804 })
805 const result = computeSharedBindings({
806 code,
807 codeSplitGroupings: groupings,
808 })
809 expect(result.has('a')).toBe(true)
810 expect(result.has('b')).toBe(true)
811 })
812​
813 // One shared, one not β†’ exactly one shared
814 it(`one in both groups, one in one [${groupName}] β†’ only cross-group is shared`, () => {
815 const code = makeRouteCode({
816 bindings: [
817 { name: 'a', kind: 'const' },
818 { name: 'b', kind: 'const' },
819 ],
820 loaderRefs: ['a'],
821 componentRefs: ['a', 'b'],
822 })
823 const result = computeSharedBindings({
824 code,
825 codeSplitGroupings: groupings,
826 })
827 expect(result.has('a')).toBe(true)
828 expect(result.has('b')).toBe(false)
829 })
830 }
831 })
832​
833 describe('transitive dependency chains', () => {
834 it('A depends on B, both used by different groups β†’ both shared', () => {
835 const code = `
836import { createFileRoute } from '@tanstack/react-router'
837const BASE = 'https://api.example.com'
838const config = { url: BASE }
839export const Route = createFileRoute('/')({
840 loader: () => config.url,
841 component: () => <div>{config.url}</div>,
842})
844 const result = computeSharedBindings({
845 code,
846 codeSplitGroupings: defaultCodeSplitGroupings,
847 })
848 // config is directly used by both groups β†’ shared
849 expect(result.has('config')).toBe(true)
850 // BASE is a dep of config β†’ also shared
851 expect(result.has('BASE')).toBe(true)
852 })
853​
854 it('A depends on B depends on C, A used cross-group β†’ all three shared', () => {
855 const code = `
856import { createFileRoute } from '@tanstack/react-router'
857const c = 'deep'
858const b = c + '-value'
859const a = b + '-final'
860export const Route = createFileRoute('/')({
861 loader: () => a,
862 component: () => <div>{a}</div>,
863})
865 const result = computeSharedBindings({
866 code,
867 codeSplitGroupings: defaultCodeSplitGroupings,
868 })
869 expect(result.has('a')).toBe(true)
870 expect(result.has('b')).toBe(true)
871 expect(result.has('c')).toBe(true)
872 })
873​
874 it('diamond dependency: A→B, A→C, B→D, C→D → all shared when A is cross-group', () => {
875 const code = `
876import { createFileRoute } from '@tanstack/react-router'
877const D = 42
878const B = D + 1
879const C = D + 2
880const A = B + C
881export const Route = createFileRoute('/')({
882 loader: () => A,
883 component: () => <div>{A}</div>,
884})
886 const result = computeSharedBindings({
887 code,
888 codeSplitGroupings: defaultCodeSplitGroupings,
889 })
890 expect(result.has('A')).toBe(true)
891 expect(result.has('B')).toBe(true)
892 expect(result.has('C')).toBe(true)
893 expect(result.has('D')).toBe(true)
894 })
895 })
896​
897 describe('meta-invariant: all fixture files satisfy core contracts', () => {
898 const sharedFixtures = [
899 'shared-variable.tsx',
900 'shared-class.tsx',
901 'shared-function.tsx',
902 'shared-exported.tsx',
903 'shared-indirect-ref.tsx',
904 'shared-none.tsx',
905 'shared-destructured.tsx',
906 'shared-destructured-export.tsx',
907 'shared-imported-binding.tsx',
908 'shared-jsx-component-ref.tsx',
909 'shared-referencing-route.tsx',
910 'shared-transitive.tsx',
911 'shared-with-side-effect.tsx',
912 ]
913​
914 // Run invariants across ALL existing test fixtures β€” like a conformance suite
915 it.each(sharedFixtures)(
916 'fixture "%s" satisfies: Route excluded, results βŠ† localBindings',
917 async (filename) => {
918 const file = await readFile(
919 path.join(__dirname, `./code-splitter/test-files/react/${filename}`),
920 )
921 const code = file.toString()
922​
923 const result = computeSharedBindings({
924 code,
925 codeSplitGroupings: defaultCodeSplitGroupings,
926 })
927​
928 // Contract 1: Route is never shared
929 expect(result.has('Route')).toBe(false)
930​
931 // Contract 2: all results are real local bindings
932 const localBindings = new Set(
933 analyzeModule({ code })
934 .rootScope.bindings.filter(
935 (binding) =>
936 !binding.has(BindingFlags.Import) && binding.name !== 'Route',
937 )
938 .map((binding) => binding.name),
939 )
940​
941 for (const name of result) {
942 expect(localBindings.has(name)).toBe(true)
943 }
944​
945 // Contract 3: result is deterministic
946 const result2 = computeSharedBindings({
947 code,
948 codeSplitGroupings: defaultCodeSplitGroupings,
949 })
950 expect(result).toEqual(result2)
951 },
952 )
953 })
954})