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

hydrate-when-transform.test.ts

746 lines21.5 KB

1import { mkdtempSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { walk } from 'yuku-ast'
5import {
6 analyzeModule,
7 cloneModuleAst,
8 generateModule,
9 parseExpression,
10 removeUnusedBindings,
11} from '@tanstack/router-utils'
12import { describe, expect, test } from 'vitest'
13import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform'
14import type { CompileStartFrameworkOptions } from '../src/types'
15​
16const root = '/repo'
17const id = '/repo/src/routes/about.tsx'
18​
19type HydrateBoundary = {
20 id: string
21 exportName: string
22 index: number
24​
25function getHydrateBoundariesFromCode(code: string): Array<HydrateBoundary> {
26 const boundaries: Array<HydrateBoundary> = []
27 const hydrateImportPattern =
28 /import\("([^"]*[?&]tss-hydrate=[^"]*)"\),\s*"([^"]+)"/g
29 let match: RegExpExecArray | null
30​
31 while ((match = hydrateImportPattern.exec(code))) {
32 const importId = match[1]!
33 const queryIndex = importId.indexOf('?')
34 const params = new URLSearchParams(importId.slice(queryIndex + 1))
35 const boundaryId = params.get('tss-hydrate')
36 const separatorIndex = boundaryId?.indexOf('_') ?? -1
37 const index =
38 boundaryId && separatorIndex > 0
39 ? Number.parseInt(boundaryId.slice(0, separatorIndex), 36)
40 : Number.NaN
41​
42 if (boundaryId && Number.isInteger(index)) {
43 boundaries.push({
44 id: boundaryId,
45 exportName: match[2]!,
46 index,
47 })
48 }
49 }
50​
51 return boundaries.sort((a, b) => a.index - b.index)
53​
54function virtualHydrateId(
55 file: string,
56 boundary: Pick<HydrateBoundary, 'id' | 'index'>,
57) {
58 const params = new URLSearchParams()
59 params.set('tss-hydrate', boundary.id)
60 return `${file}?${params.toString()}`
62​
63function withSourceHash(id: string, sourceHash: string) {
64 const separatorIndex = id.indexOf('_')
65 return `${id.slice(0, separatorIndex + 1)}${sourceHash}`
67​
68/**
69 * Runs only the Hydrate plugin's `transformAst` on a fresh AST, with a minimal
70 * editor and its own unused-binding cleanup, bypassing `StartCompiler` (no
71 * Start factories, generated-import insertion or file pragmas). It unit-tests
72 * the transform's output; tests of what compiled modules do belong in
73 * hydrate-split-modules.test.ts and hydrate-captures.test.ts, which compile
74 * through the real pipeline (`compileHydrate` in regression-helpers.ts).
75 */
76function compileHydrate(options: {
77 code: string
78 id: string
79 root: string
80 env: 'client' | 'server'
81 envName?: string
82 framework?: CompileStartFrameworkOptions
83 plugin?: ReturnType<typeof createHydrateCompilerPlugin>
84}) {
85 const plugin = options.plugin ?? createHydrateCompilerPlugin()
86 const envName = options.envName ?? options.env
87 const module = analyzeModule({ code: options.code, filename: options.id })
88 const { program: ast, originalNodes } = cloneModuleAst(module)
89 const result = plugin.transformAst?.({
90 ast,
91 module,
92 originalNodes,
93 code: options.code,
94 id: options.id,
95 root: options.root,
96 env: options.env,
97 envName,
98 mode: 'dev',
99 framework: options.framework ?? 'react',
100 providerEnvName: 'ssr',
101 parseExpression,
102 replaceNode(node, replacement) {
103 walk(ast, {
104 enter(current, context) {
105 if (current === node) {
106 context.replace(replacement)
107 context.stop()
108 }
109 },
110 })
111 },
112 parentOf(node) {
113 let parent: import('@yuku-toolchain/types').Node | null = null
114 walk(ast, {
115 enter(current, context) {
116 if (current === node) {
117 parent = context.parent
118 context.stop()
119 }
120 },
121 })
122 return parent
123 },
124 })
125 if (!result) {
126 return null
127 }
128​
129 removeUnusedBindings(module, ast, originalNodes)
130 const generated = generateModule(ast, {
131 source: options.code,
132 filename: options.id,
133 })
134​
135 return {
136 code: generated.code,
137 map: generated.map,
138 boundaries: getHydrateBoundariesFromCode(generated.code),
139 plugin,
140 }
142​
143function loadVirtualHydrateModule(options: {
144 code: string
145 id: string
146 root: string
147 envName?: string
148}) {
149 const plugin = createHydrateCompilerPlugin()
150 return plugin.loadVirtualModule?.({
151 code: options.code,
152 id: options.id,
153 root: options.root,
154 env: 'client',
155 envName: options.envName ?? 'client',
156 })
158​
159describe('Hydrate compiler transform', () => {
160 test.each(['client', 'server'] as const)(
161 'resolves spread props declared after their containing function in %s output',
162 (env) => {
163 const result = compileHydrate({
164 code: `import { Hydrate } from '@tanstack/react-start'
165export function Page() { return <Hydrate {...props}><p>child</p></Hydrate> }
166const props = { when: true, fallback: <p>server-fallback</p> }`,
167 id,
168 root,
169 env,
170 })
171 expect(result).not.toBeNull()
172 expect(result?.code).toContain('when: true')
173 if (env === 'client') {
174 expect(result?.code).not.toContain('.preload')
175 expect(result?.code).toContain('server-fallback')
176 } else {
177 expect(result?.code).not.toContain('server-fallback')
178 }
179 },
180 )
181​
182 test.each(['client', 'server'] as const)(
183 'respects parenthesized split={false} in %s output',
184 (env) => {
185 const result = compileHydrate({
186 code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return <Hydrate split={(false)}>{() => <p>child</p>}</Hydrate> }`,
187 id,
188 root,
189 env,
190 })
191 expect(result).toBeNull()
192 },
193 )
194​
195 test.each(['{...({ fallback: <p>server-fallback</p> })}', '{...(props)}'])(
196 'strips fallback from a parenthesized spread %s',
197 (spread) => {
198 const result = compileHydrate({
199 code: `import { Hydrate } from '@tanstack/react-start'; ${spread.includes('props') ? 'const props = ({ fallback: <p>server-fallback</p> });' : ''} export function Page() { return <Hydrate ${spread}><p>child</p></Hydrate> }`,
200 id,
201 root,
202 env: 'server',
203 })
204 expect(result).not.toBeNull()
205 expect(result?.code).not.toContain('server-fallback')
206 },
207 )
208​
209 test('strips a statically computed fallback property from server output', () => {
210 const result = compileHydrate({
211 code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return <Hydrate {...{ ['fallback']: <p>server-fallback</p> }}><p>child</p></Hydrate> }`,
212 id,
213 root,
214 env: 'server',
215 })
216 expect(result).not.toBeNull()
217 expect(result?.code).not.toContain('server-fallback')
218 })
219​
220 test.each(['{...({ when: true })}', '{...(props)}'])(
221 'avoids generating a preload callback for known props %s',
222 (spread) => {
223 const result = compileHydrate({
224 code: `import { Hydrate } from '@tanstack/react-start'; const props = ({ when: true }); export function Page() { return <Hydrate ${spread}><p>child</p></Hydrate> }`,
225 id,
226 root,
227 env: 'client',
228 })
229 expect(result).not.toBeNull()
230 expect(result?.code).not.toContain('.preload')
231 },
232 )
233​
234 test.each([
235 ['{(() => <p>child</p>)}', /function-as-children/],
236 ['{(useThing)()}', /hooks/],
237 ])('rejects parenthesized unsafe extraction %s', (child, message) => {
238 expect(() =>
239 compileHydrate({
240 code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return <Hydrate>${child}</Hydrate> }`,
241 id,
242 root,
243 env: 'client',
244 }),
245 ).toThrow(message)
246 })
247​
248 test('splits Hydrate children behind a lazy import', () => {
249 const result = compileHydrate({
250 code: `
251 import { Hydrate } from '@tanstack/react-start'
252 import { visible } from '@tanstack/react-start/hydration'
253​
254 export function Page() {
255 return (
256 <Hydrate when={visible()}>
257 <Widget title="Hello" />
258 </Hydrate>
259 )
260 }
261​
262 function Widget(props: { title: string }) {
263 return <p>{props.title}</p>
264 }
265 `,
266 id,
267 root,
268 env: 'client',
269 })
270​
271 expect(result?.code).toContain('lazyRouteComponent')
272 expect(result?.code).toContain('tss-hydrate=')
273 expect(result?.code).not.toContain('tss-hydrate-index')
274 expect(result?.code).not.toContain('createElement')
275 expect(result?.code).toContain('h=')
276 expect(result?.code).not.toContain('p=')
277 })
278​
279 test('uses the Solid Router import source for Solid Hydrate boundaries', () => {
280 const result = compileHydrate({
281 code: `
282 import { Hydrate } from '@tanstack/solid-start'
283 import { visible } from '@tanstack/solid-start/hydration'
284​
285 export function Page() {
286 return (
287 <Hydrate when={visible()}>
288 <Widget title="Hello" />
289 </Hydrate>
290 )
291 }
292​
293 function Widget(props: { title: string }) {
294 return <p>{props.title}</p>
295 }
296 `,
297 id,
298 root,
299 env: 'client',
300 framework: 'solid',
301 })
302​
303 expect(result?.code).toContain(
304 'lazyRouteComponent } from "@tanstack/solid-router"',
305 )
306 expect(result?.code).toContain('tss-hydrate=')
307 expect(result?.code).toContain('h=')
308 expect(result?.code).not.toContain('p=')
309 })
310​
311 test('rejects function-as-children unless the boundary opts out of splitting', () => {
312 expect(() =>
313 compileHydrate({
314 code: `
315 import { Hydrate } from '@tanstack/react-start'
316 import { idle } from '@tanstack/react-start/hydration'
317​
318 export function Page() {
319 return (
320 <Hydrate when={idle()}>
321 {() => <p>child</p>}
322 </Hydrate>
323 )
324 }
325 `,
326 id,
327 root,
328 env: 'client',
329 }),
330 ).toThrow(/function-as-children/)
331 })
332​
333 test('rejects hook calls that would be moved into an extracted component', () => {
334 expect(() =>
335 compileHydrate({
336 code: `
337 import { Hydrate } from '@tanstack/react-start'
338 import { idle } from '@tanstack/react-start/hydration'
339​
340 function useThing() {
341 return 'thing'
342 }
343​
344 export function Page() {
345 return (
346 <Hydrate when={idle()}>
347 <p>{useThing()}</p>
348 </Hydrate>
349 )
350 }
351 `,
352 id,
353 root,
354 env: 'client',
355 }),
356 ).toThrow(/hooks/)
357 })
358​
359 test('strips Hydrate fallback from the server transform', () => {
360 const result = compileHydrate({
361 code: `
362 import { Hydrate } from '@tanstack/react-start'
363 import { idle, visible } from '@tanstack/react-start/hydration'
364​
365 const spreadProps = {
366 when: visible(),
367 fallback: <div data-testid="server-bound-spread">bound</div>,
368 }
369​
370 export function Page() {
371 return (
372 <>
373 <Hydrate
374 when={visible()}
375 fallback={<div data-testid="server-fallback">fallback</div>}
376 >
377 <Widget title="split" />
378 </Hydrate>
379 <Hydrate
380 when={idle()}
381 split={false}
382 fallback={<div data-testid="server-inline">inline</div>}
383 >
384 <Widget title="inline" />
385 </Hydrate>
386 <Hydrate
387 {...{
388 when: visible(),
389 fallback: <div data-testid="server-spread">spread</div>,
390 }}
391 >
392 <Widget title="spread" />
393 </Hydrate>
394 <Hydrate {...spreadProps}>
395 <Widget title="bound-spread" />
396 </Hydrate>
397 </>
398 )
399 }
400​
401 function Widget(props: { title: string }) {
402 return <p>{props.title}</p>
403 }
404 `,
405 id,
406 root,
407 env: 'server',
408 })
409​
410 expect(result?.code).not.toContain('fallback=')
411 expect(result?.code).not.toContain('fallback:')
412 expect(result?.code).not.toContain('server-fallback')
413 expect(result?.code).not.toContain('server-inline')
414 expect(result?.code).not.toContain('server-spread')
415 expect(result?.code).not.toContain('server-bound-spread')
416 expect(result?.code).toContain('h=')
417 expect(result?.code).toContain('<Widget title="split" />')
418 expect(result?.code).toContain('<Widget title="inline" />')
419 expect(result?.code).toContain('<Widget title="spread" />')
420 expect(result?.code).toContain('<Widget title="bound-spread" />')
421 })
422​
423 test('supports nested Hydrate boundaries in extracted virtual modules', () => {
424 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
425 const file = join(dir, 'route.tsx')
426 const code = `
427 import { Hydrate } from '@tanstack/react-start'
428 import { interaction, visible } from '@tanstack/react-start/hydration'
429​
430 const unused = 'remove me'
431​
432 export function Page() {
433 return (
434 <Hydrate when={visible()}>
435 <section>
436 <Hydrate when={interaction()}>
437 <button>Nested</button>
438 </Hydrate>
439 </section>
440 </Hydrate>
441 )
442 }
443 `
444 const firstPass = compileHydrate({
445 code,
446 id: file,
447 root: dir,
448 env: 'client',
449 })
450 expect(firstPass?.boundaries).toHaveLength(1)
451​
452 const virtualId = virtualHydrateId(file, firstPass!.boundaries[0]!)
453 const virtualModule = loadVirtualHydrateModule({
454 code,
455 id: virtualId,
456 root: dir,
457 })
458 expect(virtualModule?.code).not.toContain('remove me')
459​
460 const boundaryIndex = firstPass!.boundaries[0]!.index
461 const nestedPass = compileHydrate({
462 code: virtualModule!.code,
463 id: virtualId,
464 root: dir,
465 env: 'client',
466 })
467​
468 expect(boundaryIndex).toBe(0)
469 expect(nestedPass?.code).toContain('H1')
470 expect(nestedPass?.code).toContain('tss-hydrate=')
471 })
472​
473 test('keeps sibling boundary ids stable after nested boundaries', () => {
474 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
475 const file = join(dir, 'route.tsx')
476 const code = `
477 import { Hydrate } from '@tanstack/react-start'
478 import { idle, interaction, visible } from '@tanstack/react-start/hydration'
479​
480 export function Page() {
481 return (
482 <>
483 <Hydrate when={visible()}>
484 <section>
485 <Hydrate when={interaction()}>
486 <button>Nested</button>
487 </Hydrate>
488 </section>
489 </Hydrate>
490 <Hydrate when={idle()}>
491 <p>Sibling</p>
492 </Hydrate>
493 </>
494 )
495 }
496 `
497 const firstPass = compileHydrate({
498 code,
499 id: file,
500 root: dir,
501 env: 'client',
502 })
503 expect(
504 firstPass?.boundaries.map((boundary) => boundary.exportName),
505 ).toEqual(['H0', 'H2'])
506​
507 const siblingBoundary = firstPass!.boundaries[1]!
508 const virtualId = virtualHydrateId(file, siblingBoundary)
509 const boundaryIndex = siblingBoundary.index
510 const virtualModule = loadVirtualHydrateModule({
511 code,
512 id: virtualId,
513 root: dir,
514 })
515 const parentVirtualId = virtualHydrateId(file, firstPass!.boundaries[0]!)
516 const parentVirtualModule = loadVirtualHydrateModule({
517 code,
518 id: parentVirtualId,
519 root: dir,
520 })
521 const nestedPass = compileHydrate({
522 code: parentVirtualModule!.code,
523 id: parentVirtualId,
524 root: dir,
525 env: 'client',
526 })
527 const serverPass = compileHydrate({
528 code,
529 id: file,
530 root: dir,
531 env: 'server',
532 })
533​
534 expect(boundaryIndex).toBe(2)
535 expect(virtualModule?.code).toContain('Sibling')
536 expect(virtualModule?.code).not.toContain('Nested')
537 expect(nestedPass?.boundaries[0]?.exportName).toBe('H1')
538 expect(serverPass?.code).toContain(firstPass!.boundaries[0]!.id)
539 expect(serverPass?.code).toContain(nestedPass!.boundaries[0]!.id)
540 expect(serverPass?.code).toContain(siblingBoundary.id)
541 })
542​
543 test('loads virtual modules from supplied bundler code instead of the filesystem', () => {
544 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
545 const file = join(dir, 'route.tsx')
546 const oldCode = `
547 import { Hydrate } from '@tanstack/react-start'
548 import { visible } from '@tanstack/react-start/hydration'
549​
550 export function Page() {
551 return <Hydrate when={visible()}><p>Old</p></Hydrate>
552 }
553 `
554 const nextCode = oldCode.replace('Old', 'New')
555 const firstPass = compileHydrate({
556 code: oldCode,
557 id: file,
558 root: dir,
559 env: 'client',
560 })
561 const virtualModule = loadVirtualHydrateModule({
562 code: nextCode,
563 id: virtualHydrateId(file, firstPass!.boundaries[0]!),
564 root: dir,
565 })
566​
567 expect(virtualModule?.code).toContain('New')
568 expect(virtualModule?.code).not.toContain('Old')
569 })
570​
571 test('captures identifiers used by shorthand objects and computed members', () => {
572 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
573 const file = join(dir, 'route.tsx')
574 const code = `
575 import { Hydrate } from '@tanstack/react-start'
576 import { visible } from '@tanstack/react-start/hydration'
577​
578 export function Page() {
579 const key = 'name'
580 const items = { name: 'Ada' }
581 return (
582 <Hydrate when={visible()}>
583 <Widget data={{ key, value: items[key] }} />
584 </Hydrate>
585 )
586 }
587​
588 function Widget(props: { data: { key: string; value: string } }) {
589 return <p>{props.data.value}</p>
590 }
591 `
592 const firstPass = compileHydrate({
593 code,
594 id: file,
595 root: dir,
596 env: 'client',
597 })
598 const virtualModule = loadVirtualHydrateModule({
599 code,
600 id: virtualHydrateId(file, firstPass!.boundaries[0]!),
601 root: dir,
602 })
603​
604 expect(virtualModule?.code).toContain('export function H0({')
605 expect(virtualModule?.code).toContain('items')
606 expect(virtualModule?.code).toContain('key')
607 expect(virtualModule?.code).toContain('items[key]')
608 })
609​
610 test('unwraps exported declarations needed by extracted virtual modules', () => {
611 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
612 const file = join(dir, 'route.tsx')
613 const code = `
614 import { createFileRoute } from '@tanstack/react-router'
615 import { Hydrate } from '@tanstack/react-start'
616 import { visible } from '@tanstack/react-start/hydration'
617​
618 export const Route = createFileRoute('/test')({
619 component: Page,
620 })
621​
622 export const label = 'Ada'
623​
624 export const Widget = () => {
625 return <p>{label}</p>
626 }
627​
628 function Page() {
629 return <Hydrate when={visible()}><Widget /></Hydrate>
630 }
631 `
632 const firstPass = compileHydrate({
633 code,
634 id: file,
635 root: dir,
636 env: 'client',
637 })
638 const virtualModule = loadVirtualHydrateModule({
639 code,
640 id: virtualHydrateId(file, firstPass!.boundaries[0]!),
641 root: dir,
642 })
643​
644 expect(virtualModule?.code).toContain('const Widget')
645 expect(virtualModule?.code).toContain('const label')
646 expect(virtualModule?.code).toContain('<Widget />')
647 expect(virtualModule?.code).not.toContain('export const Widget')
648 expect(virtualModule?.code).not.toContain('createFileRoute')
649 expect(virtualModule?.code).not.toContain('const Route')
650 })
651​
652 test('invalidates cached Hydrate source for virtual module loads', () => {
653 const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-'))
654 const file = join(dir, 'route.tsx')
655 const oldCode = `
656 import { Hydrate } from '@tanstack/react-start'
657 import { visible } from '@tanstack/react-start/hydration'
658​
659 export function Page() {
660 return <Hydrate when={visible()}><p>Old</p></Hydrate>
661 }
662 `
663 const nextCode = oldCode.replace('Old', 'New')
664 const envName = 'client'
665 const plugin = createHydrateCompilerPlugin()
666 const transformed = compileHydrate({
667 code: oldCode,
668 id: file,
669 root: dir,
670 env: 'client',
671 envName,
672 plugin,
673 })
674 const virtualId = virtualHydrateId(file, transformed!.boundaries[0]!)
675​
676 expect(
677 transformed!.plugin.loadVirtualModule?.({
678 id: virtualId,
679 root: dir,
680 env: 'client',
681 envName,
682 })?.code,
683 ).toContain('Old')
684​
685 transformed!.plugin.invalidateModule?.({ id: file, envName })
686 expect(() =>
687 transformed!.plugin.loadVirtualModule?.({
688 id: virtualId,
689 root: dir,
690 env: 'client',
691 envName,
692 }),
693 ).toThrow(/Missing Hydrate source/)
694​
695 const updated = compileHydrate({
696 code: nextCode,
697 id: file,
698 root: dir,
699 env: 'client',
700 envName,
701 plugin,
702 })
703​
704 expect(
705 updated!.plugin.loadVirtualModule?.({
706 id: virtualId,
707 root: dir,
708 env: 'client',
709 envName,
710 })?.code,
711 ).toContain('New')
712 })
713​
714 test('rejects virtual module ids whose source hash does not match', () => {
715 const code = `
716 import { Hydrate } from '@tanstack/react-start'
717 import { idle, visible } from '@tanstack/react-start/hydration'
718​
719 export function Page() {
720 return (
721 <>
722 <Hydrate when={visible()}><p>First</p></Hydrate>
723 <Hydrate when={idle()}><p>Second</p></Hydrate>
724 </>
725 )
726 }
727 `
728 const firstPass = compileHydrate({
729 code,
730 id,
731 root,
732 env: 'client',
733 })
734 const mismatchedId = virtualHydrateId(id, {
735 id: withSourceHash(firstPass!.boundaries[0]!.id, 'mismatch'),
736 index: firstPass!.boundaries[0]!.index,
737 })
738​
739 expect(
740 new URLSearchParams(mismatchedId.split('?')[1]).get('tss-hydrate'),
741 ).toMatch(/_mismatch$/)
742 expect(
743 loadVirtualHydrateModule({ code, id: mismatchedId, root }),
744 ).toBeNull()
745 })
746})