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

hydrate-split-modules.test.ts

1,089 lines36.9 KB

1import { afterEach, describe, expect, test } from 'vitest'
2import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform'
3import {
4 compileCode,
5 compileErrorMessage,
6 compileFirstChunk,
7 compileHydrate,
8 directivePrologue,
9 evaluateHydrateParent,
10 evaluateModule,
11 getBoundaryIds,
12 getChunkComponent,
13 getChunkIds,
14 hydrateParentStubs,
15 importSources,
16 loadChunk,
17 parentImportSources,
18 renderChunk,
19} from './regression-helpers'
20import { declarationOf, getModuleErrors } from './validate-module'
21import type { ModuleStub } from './regression-helpers'
22​
23// On the client `<Hydrate>` children move into a lazily loaded chunk module
24// and the parent renders the chunk component in their place; on the server
25// the children render inline and the client-only `fallback` is stripped.
26// Both modules must stay valid and behave like the original source.
27​
28const head = `import { Hydrate } from '@tanstack/react-start'\n`
29​
30/**
31 * JSX runtime of the evaluated modules: intrinsic elements render as tags and,
32 * like React, components never receive `key` (nor `ref` before React 19).
33 */
34const reactRuntime = `const __Fragment = Symbol('Fragment')
35const __jsx = (type, props, ...children) => {
36 const text = children.flat(Infinity).filter((c) => c != null && c !== false && c !== true).join('')
37 if (type === __Fragment) return text
38 if (typeof type === 'function') {
39 const { key, ref, ...rest } = props ?? {}
40 return type(children.length ? { ...rest, children: text } : rest)
41 }
42 if (typeof type !== 'string') throw new Error('cannot render ' + String(type))
43 return '<' + type + '>' + text + '</' + type + '>'
46​
47/**
48 * Evaluates `code` compiled for the client once its `<Hydrate>` chunks have
49 * loaded: each lazy chunk component renders the chunk export it loads, and
50 * the modules are linked like a bundler would (`evaluateHydrateParent`).
51 * `beforeChunksLoad` runs app code between the two.
52 */
53async function loadClientModule(
54 code: string,
55 options: {
56 stubs?: Record<string, ModuleStub>
57 beforeChunksLoad?: (module: Record<string, any>) => void
58 } = {},
59) {
60 const { parent, chunks, plugin } = await compileHydrate('client', code)
61 const lazyChunks: Array<{ name: string; rendered: boolean }> = []
62 const chunkExports: Record<string, (props: unknown) => unknown> = {}
63 const userStubs = options.stubs ?? {}
64 const stubs: Record<string, ModuleStub> = {
65 ...hydrateParentStubs,
66 ...userStubs,
67 '@tanstack/react-router': {
68 ...(userStubs['@tanstack/react-router'] as Record<string, unknown>),
69 lazyRouteComponent: (_load: unknown, name = 'default') => {
70 const lazyChunk = { name, rendered: false }
71 lazyChunks.push(lazyChunk)
72 return (props: unknown) => {
73 lazyChunk.rendered = true
74 return chunkExports[name]!(props)
75 }
76 },
77 },
78 }
79 expect(await getModuleErrors(parent)).toEqual([])
80 const { module, parentModuleStubs } = await evaluateHydrateParent(
81 plugin,
82 parent,
83 stubs,
84 reactRuntime,
85 )
86 options.beforeChunksLoad?.(module)
87 for (const chunk of chunks) {
88 expect(await getModuleErrors(chunk)).toEqual([])
89 Object.assign(
90 chunkExports,
91 await evaluateModule(
92 chunk,
93 { ...stubs, ...(await parentModuleStubs(chunk)) },
94 reactRuntime,
95 ),
96 )
97 }
98 return { module, lazyChunks }
100​
101describe('harness controls', () => {
102 test('client: loadClientModule renders every boundary through its lazy chunk', async () => {
103 const { module, lazyChunks } =
104 await loadClientModule(`${head}const helper = () => '!'
105export function Page() {
106 const label = 'hi'
107 return <><Hydrate><p>{label}{helper()}</p></Hydrate><Hydrate><b>two</b></Hydrate></>
108}`)
109 expect(module.Page()).toBe('[<p>hi!</p>][<b>two</b>]')
110 expect(lazyChunks.map((chunk) => chunk.rendered)).toEqual([true, true])
111 })
112​
113 test('client: loadClientModule links stubs and runs app code before the chunks load', async () => {
114 const events: Array<string> = []
115 const { module } = await loadClientModule(
116 `${head}import { Link } from '@tanstack/react-router'
117import { label } from './label'
118export function Page() {
119 return <Hydrate><p><Link />{label()}</p></Hydrate>
120}`,
121 {
122 stubs: {
123 // Merged with the lazy chunk loader the harness provides.
124 '@tanstack/react-router': { Link: () => 'link ' },
125 './label': {
126 get label() {
127 events.push('label linked')
128 return () => 'stubbed'
129 },
130 },
131 },
132 beforeChunksLoad: (parent) =>
133 events.push(`app code with ${Object.keys(parent).join()}`),
134 },
135 )
136 expect(module.Page()).toBe('[<p>link stubbed</p>]')
137 expect(events).toEqual(['app code with Page', 'label linked'])
138 })
139})
140​
141describe('the parent module', () => {
142 const widgetPage = `${head}import { visible } from '@tanstack/react-start/hydration'
143import { Chart, FallbackPane } from './widgets'
144import { formatValue } from './format'
145const chartTitle = formatValue('Revenue')
146export function Page() {
147 return <Hydrate when={visible()} fallback={<FallbackPane />}><Chart title={chartTitle} /></Hydrate>
148}`
149​
150 test('client: bindings only the split children use leave the parent', async () => {
151 const { parent, chunks } = await compileHydrate('client', widgetPage)
152 expect(chunks[0]).toMatch(declarationOf('chartTitle'))
153 expect(parent).not.toMatch(declarationOf('chartTitle'))
154 expect(parent).not.toMatch(/\bChart\b/)
155 expect(importSources(parent)).toEqual(['./widgets'])
156 })
157​
158 test('server: bindings only the stripped fallback uses are removed', async () => {
159 const { parent } = await compileHydrate('server', widgetPage)
160 expect(parent).not.toContain('FallbackPane')
161 })
162​
163 test("client: the directive prologue stays first in the parent module and 'use client' in the split chunk", async () => {
164 const { parent, chunks } = await compileHydrate(
165 'client',
166 `'use client'
167'use strict'
168${head}import { Chart } from './chart'
169export function Page() {
170 return <Hydrate><Chart /></Hydrate>
171}`,
172 )
173 expect(directivePrologue(parent)).toEqual(['use client', 'use strict'])
174 expect(directivePrologue(chunks[0]!)[0]).toBe('use client')
175 })
176​
177 // Children passed as props split like JSX children, or stay in place when
178 // props only provide them at runtime; either way they render once, without
179 // a chunk that never renders.
180 test.each([
181 {
182 name: 'a spread on an element without children',
183 code: `export function Page(props) {
184 return <Hydrate {...props}></Hydrate>
185}`,
186 props: { children: 'spread' },
187 html: '[spread]',
188 },
189 {
190 name: 'a children prop of a self-closing element',
191 code: `import { idle } from '@tanstack/react-start/hydration'
192import { Chart } from './chart'
193export function Page() {
194 return <Hydrate when={idle()} children={<Chart />} />
195}`,
196 props: {},
197 html: '[chart]',
198 },
199 {
200 // A string children prop is left in place, while the same text as JSX
201 // children (`<Hydrate>text</Hydrate>`) is split like any JSX children
202 // (see the text-only child tests): the compiler only moves a children
203 // prop holding an expression into the JSX children. Plain text has
204 // nothing to hydrate, so both render the same.
205 name: 'a string children prop',
206 code: `export function Page() {
207 return <Hydrate children="text" />
208}`,
209 props: {},
210 html: '[text]',
211 },
212 ])(
213 'client: children passed through $name render without unused chunks',
214 async ({ code, props, html }) => {
215 const { module, lazyChunks } = await loadClientModule(`${head}${code}`, {
216 stubs: { './chart': { Chart: () => 'chart' } },
217 })
218 expect({
219 html: module.Page(props),
220 unusedChunks: lazyChunks.filter((chunk) => !chunk.rendered).length,
221 }).toEqual({ html, unusedChunks: 0 })
222 },
223 )
224​
225 test('client: a stale h attribute is replaced by the generated boundary id', async () => {
226 const { parent } = await compileHydrate(
227 'client',
228 `${head}export function Page() {
229 return <Hydrate h="stale"><p>child</p></Hydrate>
230}`,
231 )
232 expect(parent).not.toContain('stale')
233 expect(getBoundaryIds(parent)).toHaveLength(1)
234 })
235​
236 // String values of `split` are accepted too, for untyped or JS callers.
237 test('client: split="false" keeps function-as-children in place', async () => {
238 const parent = await compileCode(
239 'client',
240 `${head}export function Page() {
241 return <Hydrate split="false">{() => <p>child</p>}</Hydrate>
242}`,
243 { compilerPlugins: [createHydrateCompilerPlugin()] },
244 )
245 expect(parent).toBeNull()
246 })
247​
248 test.each(['split', 'split="true"'])(
249 'client: %s splits the children',
250 async (split) => {
251 const { chunks } = await compileHydrate(
252 'client',
253 `${head}export function Page() {
254 return <Hydrate ${split}><p>child</p></Hydrate>
255}`,
256 )
257 expect(chunks).toHaveLength(1)
258 expect(await renderChunk(chunks[0]!)).toBe('<p>child</p>')
259 },
260 )
261​
262 // An object spread into one boundary only is stripped of its fallback; a
263 // shared or computed object may be observed elsewhere and is kept.
264 test.each([
265 {
266 name: 'used once',
267 code: `const opts = { fallback: <p>server-fallback</p>, when: true }
268export function Page() { return <Hydrate {...opts}><p>child</p></Hydrate> }`,
269 kept: false,
270 },
271 {
272 name: 'shared by two boundaries',
273 code: `const opts = { fallback: <p>server-fallback</p> }
274export function Page() { return <><Hydrate {...opts}><p>a</p></Hydrate><Hydrate {...opts}><p>b</p></Hydrate></> }`,
275 kept: true,
276 },
277 {
278 name: 'returned by a call',
279 code: `const makeOpts = () => ({ fallback: <p>server-fallback</p> })
280const opts = makeOpts()
281export function Page() { return <Hydrate {...opts}><p>child</p></Hydrate> }`,
282 kept: true,
283 },
284 ])(
285 'server: a fallback in a spread object $name is kept: $kept',
286 async ({ code, kept }) => {
287 const { parent } = await compileHydrate('server', `${head}${code}`)
288 expect(await getModuleErrors(parent)).toEqual([])
289 expect(parent.includes('server-fallback')).toBe(kept)
290 },
291 )
292​
293 // Source: Qwik optimizer example_functional_component_capture_props
294 test('server: params used only by the fallback keep later params in place', async () => {
295 const { parent } = await compileHydrate(
296 'server',
297 `${head}export function List({ items }) {
298 return <ul>{items.map((item, i) => <Hydrate key={i} fallback={<p>{item}</p>}><li>{i}</li></Hydrate>)}</ul>
300export function Card(label, body) {
301 return <Hydrate fallback={<p>{label}</p>}><p>{body}</p></Hydrate>
302}`,
303 )
304 const module = await evaluateModule(parent, hydrateParentStubs)
305 expect(module.List({ items: ['a', 'b'] })).toBe(
306 '<ul>[<li>0</li>][<li>1</li>]</ul>',
307 )
308 expect(module.Card('L', 'B')).toBe('[<p>B</p>]')
309 })
310​
311 // Source: Qwik optimizer should_transform_handler_in_for_of_loop
312 test('server: a loop variable used only by the fallback keeps the module valid', async () => {
313 const { parent } = await compileHydrate(
314 'server',
315 `${head}export function List({ xs }) {
316 const out = []
317 for (const x of xs) out.push(<Hydrate fallback={<p>{x}</p>}><p>child</p></Hydrate>)
318 return out
319}`,
320 )
321 expect(await getModuleErrors(parent)).toEqual([])
322 })
323​
324 // Source: Qwik optimizer should_keep_non_migrated_binding_from_shared_destructuring_declarator
325 test('server: a destructuring shared by the fallback and the children keeps the children binding', async () => {
326 const { parent } = await compileHydrate(
327 'server',
328 `${head}export function Page(props) {
329 const { a, b } = props
330 return <Hydrate fallback={<p>{a}</p>}><p>{b}</p></Hydrate>
331}`,
332 )
333 const module = await evaluateModule(parent, hydrateParentStubs)
334 expect(module.Page({ a: 'A', b: 'B' })).toBe('[<p>B</p>]')
335 })
336​
337 // Source: Qwik optimizer example_mutable_children, issue_5008
338 test('client: boundaries in conditionals and callbacks load the chunk the server id names', async () => {
339 const code = `${head}export function Page({ flag, items }) {
340 return <div>
341 {flag ? <Hydrate><p>yes</p></Hydrate> : <Hydrate><p>no</p></Hydrate>}
342 {flag && <Hydrate><p>and</p></Hydrate>}
343 {items.map(function (item, idx) { return <Hydrate key={idx}><p>{'fn' + item}</p></Hydrate> })}
344 {items.map((item) => <Hydrate key={item}><p>{'arrow' + item}</p></Hydrate>)}
345 </div>
347export function Other({ early }) {
348 if (early) { return <Hydrate><p>early</p></Hydrate> }
349 return <Hydrate><p>late</p></Hydrate>
350}`
351 const server = await compileHydrate('server', code)
352 const { parent, plugin } = await compileHydrate('client', code)
353 const serverIds = getBoundaryIds(server.parent)
354 expect(getBoundaryIds(parent)).toEqual(serverIds)
355 const rendered: Array<unknown> = []
356 for (const id of serverIds) {
357 const chunkId = getChunkIds(parent).find((chunk) =>
358 chunk.endsWith(`=${id}`),
359 )
360 rendered.push(
361 await renderChunk(loadChunk(plugin, 'client', chunkId!)!, {
362 item: 'x',
363 }),
364 )
365 }
366 expect(rendered).toEqual([
367 '<p>yes</p>',
368 '<p>no</p>',
369 '<p>and</p>',
370 '<p>fnx</p>',
371 '<p>arrowx</p>',
372 '<p>early</p>',
373 '<p>late</p>',
374 ])
375 })
376​
377 // Source: Qwik optimizer example_strip_exports_used
378 test.each([
379 {
380 name: 'an exported server fn also called by the parent',
381 code: `import { Hydrate, createServerFn } from '@tanstack/react-start'
382export const greet = createServerFn().handler(async () => 'greet-handler-marker')
383export function Page() {
384 return <><button onClick={() => greet()}>a</button><Hydrate><button onClick={() => greet()}>b</button></Hydrate></>
385}`,
386 },
387 {
388 name: 'a private server fn only called by the children',
389 code: `import { Hydrate, createServerFn } from '@tanstack/react-start'
390const greet = createServerFn().handler(async () => 'greet-handler-marker')
391export function Page() {
392 return <Hydrate><button onClick={() => greet()}>b</button></Hydrate>
393}`,
394 },
395 ])(
396 'client: $name calls the provider id from the split chunk',
397 async ({ code }) => {
398 const { parent, plugin } = await compileHydrate('client', code)
399 const compiled = await compileFirstChunk(plugin, parent)
400 const chunk =
401 compiled.code ?? loadChunk(plugin, 'client', getChunkIds(parent)[0]!)!
402 expect(await getModuleErrors(chunk)).toEqual([])
403 expect(chunk).not.toContain('greet-handler-marker')
404 const provider = await evaluateModule(
405 (await compileCode('provider', code))!,
406 )
407 // The chunk compiles its own caller of the provider, or imports the
408 // parent's caller.
409 const ids = Object.keys(compiled.serverFns)
410 if (ids.length > 0) {
411 expect(ids).toEqual([provider.greet_createServerFn_handler.meta.id])
412 } else {
413 expect(parentImportSources(chunk)).not.toEqual([])
414 }
415 },
416 )
417})
418​
419describe('the split chunk', () => {
420 // The server renders the children as JSX text.
421 test.each([
422 { name: 'entities', text: '&amp; &#38; &#x26;', rendered: '& & &' },
423 {
424 name: 'numeric entities',
425 text: '&copy; &#169; &#xA9;',
426 rendered: '© © ©',
427 },
428 {
429 name: 'multi-line text with entities',
430 text: '\n Fish &amp;\n Chips &copy;\n ',
431 rendered: 'Fish & Chips ©',
432 },
433 {
434 name: 'lines with trailing whitespace',
435 text: '\n first line \n second line\n ',
436 rendered: 'first line second line',
437 },
438 ])(
439 'client: a text-only child renders like JSX text: $name',
440 async ({ text, rendered }) => {
441 const jsx = await evaluateModule(`export const text = <>${text}</>`)
442 expect(jsx.text).toBe(rendered)
443 const { chunks } = await compileHydrate(
444 'client',
445 `${head}export function Page() {
446 return <Hydrate>${text}</Hydrate>
447}`,
448 )
449 expect(await renderChunk(chunks[0]!)).toBe(rendered)
450 },
451 )
452​
453 describe('the route of the parent module', () => {
454 /** Router stub recording the routes it creates. */
455 const routerStub = (created: Array<string>) => ({
456 '@tanstack/react-router': {
457 createFileRoute:
458 (id: string) => (options: { loader?: () => unknown }) => {
459 created.push(id)
460 return { id, useLoaderData: () => options.loader?.() }
461 },
462 },
463 })
464​
465 test.each([
466 {
467 name: 'directly',
468 code: `export const Route = createFileRoute('/posts')({ component: Page })
469export function Page() {
470 return <Hydrate><p>{Route.id}</p></Hydrate>
471}`,
472 rendered: '[<p>/posts</p>]',
473 },
474 {
475 name: 'through a module helper',
476 code: `export const Route = createFileRoute('/posts')({
477 loader: () => 'data',
478 component: Page,
479})
480function Comments() {
481 return <p>{Route.useLoaderData()}</p>
483export function Page() {
484 return <Hydrate><Comments /></Hydrate>
485}`,
486 rendered: '[<p>data</p>]',
487 },
488 {
489 name: 'exported under a specifier',
490 code: `const Route = createFileRoute('/posts')({ component: Page })
491export { Route }
492export function Page() {
493 return <Hydrate><p>{Route.id}</p></Hydrate>
494}`,
495 rendered: '[<p>/posts</p>]',
496 },
497 {
498 name: 'exported as default',
499 code: `const Route = createFileRoute('/posts')({ component: Page })
500export default Route
501export function Page() {
502 return <Hydrate><p>{Route.id}</p></Hydrate>
503}`,
504 rendered: '[<p>/posts</p>]',
505 },
506 ])(
507 'client: children reading Route $name use the one route',
508 async ({ code, rendered }) => {
509 const created: Array<string> = []
510 const { module } = await loadClientModule(
511 `${head}import { createFileRoute } from '@tanstack/react-router'
512${code}`,
513 { stubs: routerStub(created) },
514 )
515 expect(module.Page()).toBe(rendered)
516 expect(created).toEqual(['/posts'])
517 },
518 )
519​
520 test('client: children reading a Route the module does not export are rejected', async () => {
521 const error = await compileHydrate(
522 'client',
523 `${head}import { createFileRoute } from '@tanstack/react-router'
524const Route = createFileRoute('/posts')({ component: Page })
525export function Page() {
526 return <Hydrate><p>{Route.id}</p></Hydrate>
527}`,
528 )
529 .then(({ parent, plugin }) =>
530 loadChunk(plugin, 'client', getChunkIds(parent)[0]!),
531 )
532 .catch((error: unknown) => error)
533 expect(compileErrorMessage(error)).toMatch(/\bHydrate\b[^]*\bRoute\b/)
534 })
535 })
536​
537 test('client: children may contain return statements', async () => {
538 const { chunks } = await compileHydrate(
539 'client',
540 `${head}const letters = ['a', 'b']
541export function Page() {
542 return <Hydrate><ul onClick={() => { return 'click' }}>{letters.map((letter) => { const upper = letter.toUpperCase(); return <li>{upper}</li> })}{(function () { return 'iife' })()}</ul></Hydrate>
543}`,
544 )
545 expect(await getModuleErrors(chunks[0]!)).toEqual([])
546 // Render the click handler's result next to the element.
547 const runtime = `const __Fragment = Symbol('Fragment')
548const __jsx = (type, props, ...children) => {
549 const text = children.flat(Infinity).filter((c) => c != null && c !== false && c !== true).join('')
550 const click = props?.onClick ? '(' + props.onClick() + ')' : ''
551 return '<' + type + '>' + click + text + '</' + type + '>'
554 const module = await evaluateModule(chunks[0]!, {}, runtime)
555 expect(getChunkComponent(module)({})).toBe(
556 '<ul>(click)<li>A</li><li>B</li>iife</ul>',
557 )
558 })
559​
560 // Leaving such a boundary unsplit is valid too.
561 test('client: empty, self-closing and comment-only boundaries load chunks that render nothing', async () => {
562 const { parent, chunks } = await compileHydrate(
563 'client',
564 `${head}export function Page() {
565 return <div><Hydrate></Hydrate><Hydrate /><Hydrate>{/* nothing */}</Hydrate></div>
566}`,
567 )
568 expect(await getModuleErrors(parent)).toEqual([])
569 expect(chunks.length).toBeLessThanOrEqual(3)
570 for (const chunk of chunks) {
571 expect(await getModuleErrors(chunk)).toEqual([])
572 expect(await renderChunk(chunk)).toBeNull()
573 }
574 })
575​
576 test('client: chunk ids stay loadable when the same source is compiled again', async () => {
577 const source = `${head}export function Page() {
578 return <Hydrate><p>chunk-marker</p></Hydrate>
579}`
580 const { parent, plugin } = await compileHydrate('client', source)
581 const [id] = getChunkIds(parent)
582 expect(loadChunk(plugin, 'client', id!)).toContain('chunk-marker')
583 await compileCode('client', source, { compilerPlugins: [plugin] })
584 expect(loadChunk(plugin, 'client', id!)).toContain('chunk-marker')
585 // Unknown boundaries and ids without a split id are not Hydrate chunks.
586 expect(loadChunk(plugin, 'client', id!.replace(/=0_/, '=5_'))).toBeNull()
587 expect(
588 loadChunk(plugin, 'client', '/test/src/module.tsx?other=1'),
589 ).toBeNull()
590 })
591​
592 // Source: Qwik optimizer example_capture_imports,
593 // jsx_member_tag_object_is_captured, example_jsx
594 test('client: default, namespace and aliased imports and namespaced names in the children', async () => {
595 const { chunks } = await compileHydrate(
596 'client',
597 `${head}import Chart from './chart'
598import * as UI from './ui'
599import { format as fmt, default as theme } from './format'
600export function Page() {
601 return <Hydrate><Chart /><UI.Button label={fmt(theme)} /><svg><use xlink:href="#icon" /></svg></Hydrate>
602}`,
603 )
604 expect(await getModuleErrors(chunks[0]!)).toEqual([])
605 expect(
606 await renderChunk(
607 chunks[0]!,
608 {},
609 {
610 './chart': { default: () => '<chart></chart>' },
611 './ui': {
612 Button: ({ label }: { label: string }) =>
613 `<button>${label}</button>`,
614 },
615 './format': {
616 format: (value: string) => `[${value}]`,
617 default: 'dark',
618 },
619 },
620 ),
621 ).toBe('<chart></chart><button>[dark]</button><svg><use></use></svg>')
622 })
623​
624 // Source: Qwik optimizer should_handle_dangerously_set_inner_html
625 test('client: string attributes keep their value', async () => {
626 const element = `<span title="Fish &amp; Chips &copy;" data-q='say "hi"' data-n="a
627b" dangerouslySetInnerHTML={{ __html: "<h1>I'm an h1!</h1>" }} />`
628 const { chunks } = await compileHydrate(
629 'client',
630 `${head}export function Page() {
631 return <Hydrate>${element}</Hydrate>
632}`,
633 )
634 // Render the props instead of the element.
635 const propsRuntime = `const __Fragment = null
636const __jsx = (type, props) => JSON.stringify(props)
638 const expected = await evaluateModule(
639 `export const H0 = () => ${element}`,
640 {},
641 propsRuntime,
642 )
643 const module = await evaluateModule(chunks[0]!, {}, propsRuntime)
644 expect(getChunkComponent(module)({})).toBe(expected.H0())
645 })
646​
647 // Source: Qwik optimizer example_exports, example_ts_enums
648 test.each([
649 {
650 name: 'exported declarations of every form',
651 code: `export const [a, { b }] = ['a', { b: 'b' }]
652const exp1 = 'e1'
653const internal = 'i'
654export { exp1, internal as expr2 }
655export function foo() { return 'foo' }
656export class Bar { static id = 'bar' }
657export default function DefaultFn() { return 'default' }
658export function Page() {
659 return <Hydrate><p>{[a, b, exp1, internal, foo(), Bar.id, DefaultFn()].join('|')}</p></Hydrate>
660}`,
661 rendered: '<p>a|b|e1|i|foo|bar|default</p>',
662 },
663 {
664 name: 'TypeScript enums and namespaces',
665 code: `export enum Tone { Loud = 'LOUD' }
666namespace Labels { export const quiet = 'quiet' }
667export function Page() {
668 return <Hydrate><p>{Tone.Loud + ':' + Labels.quiet}</p></Hydrate>
669}`,
670 rendered: '<p>LOUD:quiet</p>',
671 },
672 ])(
673 'client: $name used by the children reach the chunk',
674 async ({ code, rendered }) => {
675 // Known limitation: the chunk declares its own copy of these module
676 // declarations, so the parent and the chunk do not share class
677 // identity or module state, and initializers run twice. Only the
678 // rendered output is asserted here.
679 const { chunks } = await compileHydrate('client', `${head}${code}`)
680 expect(await getModuleErrors(chunks[0]!)).toEqual([])
681 expect(await renderChunk(chunks[0]!)).toBe(rendered)
682 },
683 )
684​
685 // Source: Qwik optimizer example_use_optimization (use* calls inside the
686 // extracted scope)
687 test('client: an optional hook call in the children is rejected', async () => {
688 const error = await compileHydrate(
689 'client',
690 `import { useId } from 'react'
691${head}export function Page() {
692 return <Hydrate><p id={useId?.()}>x</p></Hydrate>
693}`,
694 ).catch((caught: unknown) => caught)
695 expect(compileErrorMessage(error)).toMatch(/hook/i)
696 })
697​
698 // A hook is recognized by its import, whatever its local name
699 test.each([
700 {
701 name: 'a renamed React hook',
702 imports: `import { useState as state } from 'react'`,
703 expression: 'state(0)[0]',
704 },
705 {
706 name: 'React 19 use()',
707 imports: `import { use } from 'react'`,
708 expression: 'use(globalThis.promise)',
709 },
710 {
711 name: 'a hook of a React namespace import',
712 imports: `import * as React from 'react'`,
713 expression: 'React.useId()',
714 },
715 {
716 name: 'a hook of a React default import',
717 imports: `import React from 'react'`,
718 expression: 'React.useId()',
719 },
720 ])(
721 'client: $name in the children is rejected',
722 async ({ imports, expression }) => {
723 const error = await compileHydrate(
724 'client',
725 `${imports}
726${head}export function Page() {
727 return <Hydrate><p>{${expression}}</p></Hydrate>
728}`,
729 ).catch((caught: unknown) => caught)
730 expect(compileErrorMessage(error)).toMatch(/calls hooks during render/)
731 },
732 )
733​
734 test('client: a use-prefixed function that is not a hook splits', async () => {
735 const { chunks } = await compileHydrate(
736 'client',
737 `import { use } from './helpers'
738import { useless } from './helpers'
739${head}export function Page() {
740 return <Hydrate><p>{use(useless)}</p></Hydrate>
741}`,
742 )
743 expect(chunks).toHaveLength(1)
744 })
745​
746 // Code that reads the state of the component's own call cannot move into
747 // the chunk component
748 test.each([
749 {
750 name: 'await',
751 component: `export async function Page() {
752 return <Hydrate><p>{await globalThis.load()}</p></Hydrate>
753}`,
754 error: /uses await during render/,
755 },
756 {
757 name: 'yield',
758 component: `export function* Page() {
759 return <Hydrate><p>{yield 'x'}</p></Hydrate>
760}`,
761 error: /uses yield during render/,
762 },
763 {
764 name: 'arguments',
765 component: `export function Page() {
766 return <Hydrate><p>{arguments.length}</p></Hydrate>
767}`,
768 error: /reads the arguments of its component/,
769 },
770 {
771 name: 'arguments in an arrow function',
772 component: `export function Page() {
773 return <Hydrate><p>{[1].map(() => arguments.length)}</p></Hydrate>
774}`,
775 error: /reads the arguments of its component/,
776 },
777 ])(
778 'client: $name in the children is rejected',
779 async ({ component, error }) => {
780 const caught = await compileHydrate(
781 'client',
782 `${head}${component}`,
783 ).catch((caught: unknown) => caught)
784 expect(compileErrorMessage(caught)).toMatch(error)
785 },
786 )
787​
788 test.each([
789 {
790 name: 'await in a nested async function',
791 expression: '[1].map(async () => await globalThis.load()).length',
792 },
793 {
794 name: 'arguments of a nested function',
795 expression: '[1].map(function () { return arguments.length })',
796 },
797 ])('client: $name in the children splits', async ({ expression }) => {
798 const { chunks } = await compileHydrate(
799 'client',
800 `${head}export function Page() {
801 return <Hydrate><p>{${expression}}</p></Hydrate>
802}`,
803 )
804 expect(chunks).toHaveLength(1)
805 expect(await getModuleErrors(chunks[0]!)).toEqual([])
806 })
807​
808 test('client dev: a boundary whose children come from a spread is reported', async () => {
809 const code = `${head}export function Page(props: any) {
810 return (
811 <>
812 <Hydrate {...props} />
813 <Hydrate {...{ when: 'idle' }}><p>split</p></Hydrate>
814 <Hydrate {...{ when: 'idle' }} />
815 </>
816 )
817}`
818 const warnings: Array<string> = []
819 await compileHydrate('client', code, {
820 mode: 'dev',
821 warn: (message) => warnings.push(message),
822 })
823 expect(warnings).toEqual([
824 "[tanstack-start] The <Hydrate> at /test/src/module.tsx:5:7 receives its children from a spread, so they won't be code-split. Pass them as JSX children or a children prop, or use split={false}.",
825 ])
826 const buildWarnings: Array<string> = []
827 await compileHydrate('client', code, {
828 warn: (message) => buildWarnings.push(message),
829 })
830 expect(buildWarnings).toEqual([])
831 })
832​
833 // Source: Qwik optimizer example_default_export
834 test('client: an anonymous default-exported component splits its boundary', async () => {
835 const { parent, chunks } = await compileHydrate(
836 'client',
837 `${head}const label = 'default'
838export default () => <Hydrate><p>{label}</p></Hydrate>`,
839 )
840 expect(await getModuleErrors(parent)).toEqual([])
841 expect(await renderChunk(chunks[0]!)).toBe('<p>default</p>')
842 })
843​
844 // Source: Qwik optimizer example_invalid_references,
845 // should_migrate_destructured_binding_with_imported_dependency
846 test('client: a module-level destructuring of an import moves into the chunk with the import', async () => {
847 const { chunks } = await compileHydrate(
848 'client',
849 `${head}import { source } from './lib'
850const fallback = 'd'
851const [a, { b = fallback, ...rest }] = source
852export function Page() {
853 return <Hydrate><p>{[a, b, JSON.stringify(rest)].join('|')}</p></Hydrate>
854}`,
855 )
856 expect(await getModuleErrors(chunks[0]!)).toEqual([])
857 expect(
858 await renderChunk(
859 chunks[0]!,
860 {},
861 { './lib': { source: ['A', { extra: 'x' }] } },
862 ),
863 ).toBe('<p>A|d|{"extra":"x"}</p>')
864 })
865​
866 // Source: Qwik optimizer should_preserve_let_when_migrated_into_segment;
867 // React Compiler fixture should-bailout-without-compilation-annotation-mode.js
868 test.each([
869 { name: 'read and written', update: '{++renders}', rendered: ['1', '2'] },
870 {
871 name: 'only written',
872 update: `{(() => { renders = 'set' })()}`,
873 rendered: ['', ''],
874 },
875 ])(
876 'client: a module-level let only the children use stays mutable when $name',
877 async ({ update, rendered }) => {
878 const { chunks } = await compileHydrate(
879 'client',
880 `${head}let renders = 0
881export function Page() {
882 return <Hydrate><p>${update}</p></Hydrate>
883}`,
884 )
885 expect(await getModuleErrors(chunks[0]!)).toEqual([])
886 const component = getChunkComponent(await evaluateModule(chunks[0]!))
887 expect([component({}), component({})]).toEqual(
888 rendered.map((text) => `<p>${text}</p>`),
889 )
890 },
891 )
892​
893 // Source: Qwik optimizer should_keep_non_migrated_binding_from_shared_destructuring_declarator
894 // (+ _array_destructuring_declarator, _with_rest)
895 test.each([
896 { name: 'object', declaration: `const { a, b } = { a: 'A', b: 'B' }` },
897 { name: 'array', declaration: `const [a, b] = ['A', 'B']` },
898 { name: 'rest', declaration: `const { a, ...b } = { a: 'A', c: 'B' }` },
899 ])(
900 'client: an $name destructuring shared by the parent and the children keeps both bindings',
901 async ({ declaration }) => {
902 const { parent, chunks, plugin } = await compileHydrate(
903 'client',
904 `${head}${declaration}
905export const fromRoot = () => JSON.stringify(b)
906export function Page() {
907 return <Hydrate><p>{a}</p></Hydrate>
908}`,
909 )
910 const { module, parentModuleStubs } = await evaluateHydrateParent(
911 plugin,
912 parent,
913 )
914 expect(module.fromRoot()).toContain('B')
915 expect(
916 await renderChunk(chunks[0]!, {}, await parentModuleStubs(chunks[0]!)),
917 ).toBe('<p>A</p>')
918 },
919 )
920​
921 // Source: Qwik optimizer should_keep_root_var_used_by_export_decl_and_qrl,
922 // example_segment_variable_migration,
923 // variable_migration_transitive_dep_used_by_other_segment
924 test('client: helpers shared by two boundaries and an export stay available to each', async () => {
925 const { parent, chunks, plugin } = await compileHydrate(
926 'client',
927 `${head}const scrollState = (el) => ({ x: el.x, y: el.y })
928const saveScroll = (s) => s.x + s.y
929const bigHelper = (el) => saveScroll(scrollState(el))
930export const direct = saveScroll(scrollState({ x: 1, y: 1 }))
931export function App() {
932 return <><Hydrate><p>{bigHelper({ x: 1, y: 2 })}</p></Hydrate><Hydrate><p>{scrollState({ x: 3, y: 4 }).y}</p></Hydrate></>
933}`,
934 )
935 expect(chunks).toHaveLength(2)
936 const { module, parentModuleStubs } = await evaluateHydrateParent(
937 plugin,
938 parent,
939 )
940 expect(module.direct).toBe(2)
941 const render = async (chunk: string) =>
942 renderChunk(chunk, {}, await parentModuleStubs(chunk))
943 expect(await render(chunks[0]!)).toBe('<p>3</p>')
944 expect(await render(chunks[1]!)).toBe('<p>4</p>')
945 })
946​
947 // Source: Qwik optimizer example_ts_enums (TypeScript-only declaration forms)
948 test('client: an overloaded function used by the children keeps its implementation', async () => {
949 const { chunks } = await compileHydrate(
950 'client',
951 `${head}function label(value: string): string
952function label(value: number): string
953function label(value: unknown) { return 'label:' + String(value) }
954export function Page() {
955 return <Hydrate><p>{label(1)}</p></Hydrate>
956}`,
957 )
958 expect(await getModuleErrors(chunks[0]!)).toEqual([])
959 expect(await renderChunk(chunks[0]!)).toBe('<p>label:1</p>')
960 })
961​
962 /** A page whose split child renders `Widget`, declared by `body`. */
963 const widgetPage = (body: string) => `${head}${body}
964export function Page(props) {
965 return <Hydrate><Widget {...props} /></Hydrate>
966}`
967​
968 // A component the children render moves into the chunk with the module
969 // bindings it reads.
970 // Source: React Compiler fixtures (per row)
971 test.each([
972 {
973 // try-catch-* fixtures
974 name: 'a catch parameter shadowing a module binding',
975 body: `const error = 'module'
976function Widget() {
977 let caught
978 try {
979 throw 'thrown'
980 } catch (error) {
981 caught = error
982 }
983 return <p>{caught}-{error}</p>
984}`,
985 expected: '<p>thrown-module</p>',
986 },
987 {
988 // fn-name-no-leak-to-nested-arrow.js
989 name: 'a named function expression shadowing a module binding',
990 body: `const helper = () => 'module'
991function Widget() {
992 const local = function helper(n) {
993 return n > 0 ? helper(n - 1) : 'local'
994 }
995 return <p>{local(2)}/{helper()}</p>
996}`,
997 expected: '<p>local/module</p>',
998 },
999 {
1000 // destructure-*-default fixtures
1001 name: 'parameter defaults reading module bindings',
1002 body: `const fallback = 'fb'
1003function Widget({ title = fallback, items: [first = fallback.toUpperCase()] = [] }) {
1004 return <p>{title}{first}</p>
1005}`,
1006 expected: '<p>fbFB</p>',
1007 },
1009 // hoisting-simple-function-declaration.js
1010 name: 'a hoisted local function reading a module binding declared later',
1011 body: `function Widget() {
1012 const x = format()
1013 function format() {
1014 return prefix + 'x'
1016 return <p>{x}</p>
1018const prefix = 'p-'`,
1019 expected: '<p>p-x</p>',
1020 },
1022 // class fixtures (static blocks, private fields)
1023 name: 'a local class with a static block and a private field',
1024 body: `const base = 2
1025function Widget() {
1026 class Counter {
1027 static start
1028 static {
1029 Counter.start = base * 2
1031 #n = Counter.start
1032 get n() {
1033 return this.#n
1036 return <p>{new Counter().n}</p>
1037}`,
1038 expected: '<p>4</p>',
1039 },
1040 ])(
1041 'client: the chunk renders like the original with $name',
1042 async ({ body, expected }) => {
1043 const { chunks } = await compileHydrate('client', widgetPage(body))
1044 expect(await getModuleErrors(chunks[0]!)).toEqual([])
1045 expect(await renderChunk(chunks[0]!, { props: {} })).toBe(expected)
1046 },
1048​
1049 describe('side effects of the component bodies it moves', () => {
1050 afterEach(() => {
1051 delete (globalThis as { __hydrateCalls?: unknown }).__hydrateCalls
1052 })
1053​
1054 // An unused local initialized by a hook call or another side effect must
1055 // still run when the chunk renders.
1056 // Source: React Compiler fixtures react-namespace.js,
1057 // unused-optional-method-assigned-to-variable.js, error.todo-reassign-const.js
1058 test.each([
1059 { name: 'a call', initializer: `useTracked('call')` },
1060 { name: 'an optional call', initializer: `useTracked?.('optional')` },
1062 name: 'a member read of a call',
1063 initializer: `useTracked('member').length`,
1064 },
1065 ])(
1066 'client: an unused local initialized by $name still runs',
1067 async ({ initializer }) => {
1068 const { chunks } = await compileHydrate(
1069 'client',
1070 widgetPage(`function useTracked(label) {
1071 globalThis.__hydrateCalls.push(label)
1072 return label
1074function Widget() {
1075 const unused = ${initializer}
1076 return <p>widget</p>
1077}`),
1079 const calls: Array<string> = []
1080 ;(globalThis as { __hydrateCalls?: Array<string> }).__hydrateCalls =
1081 calls
1082 expect(await renderChunk(chunks[0]!, { props: {} })).toBe(
1083 '<p>widget</p>',
1085 expect(calls).toHaveLength(1)
1086 },
1088 })