Open History to see the last commit
1import { relative } from 'node:path'
2import crypto from 'node:crypto'
3import { b, is, nameOf, walk } from 'yuku-ast'
4import {
5 analyzeModule,
6 cloneModuleAst,
7 collectModuleReferences,
8 expandTransitively,
9 generateModule,
10 keepFilePragmas,
11 moduleDeclarationGraph,
12 parseExpression,
13 parseStatements,
14 removeUnusedBindings,
15 unwrapExport,
16 unwrapExpression,
17} from '@tanstack/router-utils'
18import { BindingFlags } from 'yuku-analyzer'
19import { tssHydrate } from './hydration-constants'
20import { cleanId, codeFrameError, sourcePosition } from './start-compiler/utils'
21import type { Binding, Module } from 'yuku-analyzer'
22import type * as t from '@yuku-toolchain/types'
23import type {
24 CompileStartFrameworkOptions,
25 StartCompilerPlugin,
26 StartCompilerTransformResult,
27} from './types'
28β
29export class MissingHydrateSourceError extends Error {
30 constructor(id: string) {
31 super(
32 `Missing Hydrate source for virtual module ${id}. The parent module must be transformed before its Hydrate child chunk is loaded.`,
33 )
34 }
35}
36β
37/**
38 * Detection pattern used by the transform code filter to pre-scan files for
39 * `<Hydrate>` JSX before any AST parsing happens.
40 */
41const HYDRATE_DETECTION_PATTERN = /\bHydrate\b/
42β
43function createBoundaryId(root: string, sourceId: string) {
44 const normalized = relative(root, sourceId).replaceAll('\\', '/')
45 const sourceHash = crypto
46 .createHash('sha1')
47 .update(normalized)
48 .digest('hex')
49 .slice(0, 10)
50β
51 return (index: number) => {
52 return `${index.toString(36)}_${sourceHash}`
53 }
54}
55β
56function parseHydrateVirtualId(id: string) {
57 const queryIndex = id.indexOf('?')
58 const sourceId = cleanId(queryIndex === -1 ? id : id.slice(0, queryIndex))
59 if (queryIndex === -1) {
60 return { sourceId, splitId: null, boundaryIndex: -1 }
61 }
62β
63 const rawQuery = id.slice(queryIndex + 1)
64 const params = new URLSearchParams(rawQuery)
65 const splitId = params.get(tssHydrate)
66 let boundaryIndex = -1
67 if (splitId) {
68 const separatorIndex = splitId.indexOf('_')
69 if (separatorIndex > 0) {
70 const parsedIndex = Number.parseInt(splitId.slice(0, separatorIndex), 36)
71 if (Number.isInteger(parsedIndex)) {
72 boundaryIndex = parsedIndex
73 }
74 }
75 }
76β
77 return {
78 sourceId,
79 splitId,
80 boundaryIndex,
81 }
82}
83β
84interface HydrateAst {
85 ast: t.Program
86 module: Module
87 originalNodes: WeakMap<t.Node, t.Node>
88}
89β
90function getJSXElementName(node: t.JSXElement) {
91 return is.JSXIdentifier(node.openingElement.name)
92 ? node.openingElement.name.name
93 : undefined
94}
95β
96function getJSXAttribute(node: t.JSXOpeningElement, name: string) {
97 return node.attributes.find(
98 (attribute): attribute is t.JSXAttribute =>
99 is.JSXAttribute(attribute) &&
100 is.JSXIdentifier(attribute.name) &&
101 attribute.name.name === name,
102 )
103}
104β
105function getBooleanProp(node: t.JSXOpeningElement, name: string) {
106 const attribute = getJSXAttribute(node, name)
107 if (!attribute) {
108 return undefined
109 }
110 if (!attribute.value) {
111 return true
112 }
113 if (is.StringLiteral(attribute.value)) {
114 return attribute.value.value !== 'false'
115 }
116 if (is.JSXExpressionContainer(attribute.value)) {
117 const expression = is.Expression(attribute.value.expression)
118 ? unwrapExpression(attribute.value.expression)
119 : attribute.value.expression
120 if (is.BooleanLiteral(expression)) {
121 return expression.value
122 }
123 }
124 return undefined
125}
126β
127function propertyIs(property: t.Property, name: string) {
128 return (
129 (!property.computed || is.StringLiteral(property.key)) &&
130 nameOf(property.key) === name
131 )
132}
133β
134function objectExpressionMayHaveProperty(
135 node: t.ObjectExpression,
136 name: string,
137) {
138 return node.properties.some(
139 (property) =>
140 is.SpreadElement(property) ||
141 property.computed ||
142 propertyIs(property, name),
143 )
144}
145β
146function stripObjectExpressionProperty(node: t.ObjectExpression, name: string) {
147 const before = node.properties.length
148 node.properties = node.properties.filter(
149 (property) => !is.Property(property) || !propertyIs(property, name),
150 )
151 return before !== node.properties.length
152}
153β
154function sourceNode(context: HydrateAst, node: t.Node) {
155 return context.originalNodes.get(node) ?? node
156}
157β
158function getSingleUseObjectExpressionBinding(
159 context: HydrateAst,
160 identifier: t.Identifier,
161 objectExpressions: WeakMap<t.Node, t.ObjectExpression>,
162) {
163 const original = sourceNode(context, identifier)
164 const binding = context.module.bindingOf(original)
165 if (
166 !binding ||
167 binding.references.length !== 1 ||
168 binding.references[0]?.node !== original ||
169 binding.references.some((reference) => reference.isWrite)
170 ) {
171 return undefined
172 }
173 const declarationIdentifier = binding.declarations[0]
174 const declaration =
175 declarationIdentifier && context.module.parentOf(declarationIdentifier)
176 if (!is.VariableDeclarator(declaration) || !declaration.init) {
177 return undefined
178 }
179 const init = unwrapExpression(declaration.init)
180 if (!is.ObjectExpression(init)) {
181 return undefined
182 }
183 return objectExpressions.get(init)
184}
185β
186function isWithin(module: Module, node: t.Node, parent: t.Node) {
187 let current: t.Node | null = node
188 while (current) {
189 if (current === parent) {
190 return true
191 }
192 current = module.parentOf(current)
193 }
194 return false
195}
196β
197/** Packages whose `use*` exports are hooks, by framework */
198const hookSources: Record<CompileStartFrameworkOptions, Set<string>> = {
199 react: new Set(['react']),
200 solid: new Set(['solid-js']),
201 vue: new Set(['vue']),
202}
203β
204/** The import a reference reads, if it reads a module-scope import. */
205function importOf(context: HydrateAst, identifier: t.Node) {
206 const binding = context.module.bindingOf(sourceNode(context, identifier))
207 return binding
208 ? context.module.imports.find((entry) => entry.local === binding)
209 : undefined
210}
211β
212/**
213 * Whether a call is a hook call: a callee named like a custom hook
214 * (`useThing`), or a hook of the framework, renamed (`useState as state`),
215 * read from a namespace (`React.useState`) or named `use`.
216 */
217function isHookCall(
218 context: HydrateAst,
219 call: t.CallExpression,
220 framework: CompileStartFrameworkOptions,
221) {
222 const callee = unwrapExpression(call.callee)
223 const hookName = /^use(?:[A-Z0-9]|$)/
224 if (is.Identifier(callee)) {
225 if (/^use[A-Z0-9]/.test(callee.name)) {
226 return true
227 }
228 const entry = importOf(context, callee)
229 return (
230 entry?.kind === 'named' &&
231 hookSources[framework].has(entry.specifier) &&
232 hookName.test(entry.name ?? '')
233 )
234 }
235 if (
236 is.MemberExpression(callee) &&
237 !callee.computed &&
238 is.Identifier(callee.property) &&
239 hookName.test(callee.property.name)
240 ) {
241 const object = unwrapExpression(callee.object)
242 const entry = is.Identifier(object) ? importOf(context, object) : undefined
243 return !!entry && hookSources[framework].has(entry.specifier)
244 }
245 return false
246}
247β
248function inspectSplitBoundary(
249 context: HydrateAst,
250 node: t.JSXElement,
251 options: {
252 code: string
253 validate?: boolean
254 collectCaptured?: boolean
255 nestedHydrate?: { localName: string }
256 framework?: CompileStartFrameworkOptions
257 },
258) {
259 const captured = new Set<string>()
260 let nestedBoundaryCount = 0
261 const fail = (message: string): never => {
262 throw codeFrameError(options.code, sourceNode(context, node), message)
263 }
264 /**
265 * Whether the component that renders the boundary owns `current`: no
266 * function (or, with `arrows: false`, no non-arrow function) lies between
267 * them, so moving `current` into the chunk component changes its meaning.
268 */
269 const ownedByComponent = (current: t.Node, arrows: boolean) => {
270 for (
271 let ancestor = context.module.parentOf(sourceNode(context, current));
272 ancestor && ancestor !== originalBoundary;
273 ancestor = context.module.parentOf(ancestor)
274 ) {
275 if (
276 is.FunctionDeclaration(ancestor) ||
277 is.FunctionExpression(ancestor) ||
278 (arrows && is.ArrowFunctionExpression(ancestor))
279 ) {
280 return false
281 }
282 }
283 return true
284 }
285 if (options.validate) {
286 for (const child of node.children) {
287 const expression =
288 is.JSXExpressionContainer(child) && is.Expression(child.expression)
289 ? unwrapExpression(child.expression)
290 : undefined
291 if (
292 is.FunctionExpression(expression) ||
293 is.ArrowFunctionExpression(expression)
294 ) {
295 fail(
296 'Hydrate cannot code-split function-as-children. Use split={false} for this boundary.',
297 )
298 }
299 }
300 }
301 const originalBoundary = sourceNode(context, node)
302 walk(node, {
303 enter(current) {
304 if (!options.collectCaptured) {
305 return
306 }
307 const reference = context.module.referenceOf(sourceNode(context, current))
308 const binding = reference?.binding
309 if (
310 !reference ||
311 reference.inTypePosition ||
312 !binding ||
313 binding.scope === context.module.rootScope
314 ) {
315 return
316 }
317 if (
318 binding.declarations.some((declaration) =>
319 isWithin(context.module, declaration, originalBoundary),
320 )
321 ) {
322 return
323 }
324 captured.add(binding.name)
325 },
326 JSXOpeningElement(current, visitor) {
327 if (current === node.openingElement) {
328 visitor.skip()
329 }
330 },
331 JSXClosingElement(_current, visitor) {
332 visitor.skip()
333 },
334 JSXElement(current) {
335 if (
336 current !== node &&
337 options.nestedHydrate &&
338 getJSXElementName(current) === options.nestedHydrate.localName &&
339 getBooleanProp(current.openingElement, 'split') !== false
340 ) {
341 nestedBoundaryCount++
342 }
343 },
344 CallExpression(current) {
345 if (
346 options.validate &&
347 isHookCall(context, current, options.framework ?? 'react')
348 ) {
349 fail(
350 'Hydrate cannot code-split JSX that calls hooks during render. Move the hook call into a child component or use split={false}.',
351 )
352 }
353 },
354 AwaitExpression(current) {
355 if (options.validate && ownedByComponent(current, true)) {
356 fail(
357 'Hydrate cannot code-split JSX that uses await during render. Await the value before the boundary, or use split={false}.',
358 )
359 }
360 },
361 ForOfStatement(current) {
362 if (
363 options.validate &&
364 current.await &&
365 ownedByComponent(current, true)
366 ) {
367 fail(
368 'Hydrate cannot code-split JSX that uses await during render. Await the value before the boundary, or use split={false}.',
369 )
370 }
371 },
372 YieldExpression(current) {
373 if (options.validate && ownedByComponent(current, true)) {
374 fail(
375 'Hydrate cannot code-split JSX that uses yield during render. Yield before the boundary, or use split={false}.',
376 )
377 }
378 },
379 Identifier(current) {
380 if (
381 !options.validate ||
382 current.name !== 'arguments' ||
383 !ownedByComponent(current, false)
384 ) {
385 return
386 }
387 const reference = context.module.referenceOf(sourceNode(context, current))
388 // The implicit `arguments` of the component, not a binding of that name
389 if (reference && !reference.binding?.declarations.length) {
390 fail(
391 'Hydrate cannot code-split JSX that reads the arguments of its component. Read them before the boundary, or use split={false}.',
392 )
393 }
394 },
395 ThisExpression() {
396 if (options.validate) {
397 fail('Hydrate cannot code-split JSX that captures this.')
398 }
399 },
400 Super() {
401 if (options.validate) {
402 fail('Hydrate cannot code-split JSX that captures super.')
403 }
404 },
405 })
406 return { captured: [...captured].sort(), nestedBoundaryCount }
407}
408β
409function getHydrateImport(
410 ast: t.Program,
411 framework: CompileStartFrameworkOptions,
412) {
413 for (const statement of ast.body) {
414 if (
415 !is.ImportDeclaration(statement) ||
416 statement.source.value !== `@tanstack/${framework}-start`
417 ) {
418 continue
419 }
420 for (const specifier of statement.specifiers) {
421 if (
422 is.ImportSpecifier(specifier) &&
423 nameOf(specifier.imported) === 'Hydrate'
424 ) {
425 return { hydrateLocalName: specifier.local.name }
426 }
427 }
428 }
429 return undefined
430}
431β
432function getMeaningfulChildren(children: t.JSXElement['children']) {
433 return children.filter(
434 (child) => !is.JSXText(child) || child.value.trim() !== '',
435 )
436}
437β
438function setChildren(node: t.JSXElement, children: t.JSXElement['children']) {
439 node.children = children
440 if (node.openingElement.selfClosing) {
441 node.openingElement.selfClosing = false
442 node.closingElement = b.JSXClosingElement({
443 name: { ...node.openingElement.name },
444 })
445 }
446}
447β
448/**
449 * Moves a boundary's `children` prop into its JSX children, so
450 * `<Hydrate children={content} />` splits like `<Hydrate>{content}</Hydrate>`.
451 *
452 * @returns false when props may still provide the children (e.g. a spread
453 * after the `children` prop), which cannot be split.
454 */
455function moveChildrenPropIntoChildren(node: t.JSXElement) {
456 if (getMeaningfulChildren(node.children).length) {
457 // JSX children take precedence over a children prop.
458 return true
459 }
460 // The last spread or children prop determines the children.
461 const attributes = node.openingElement.attributes
462 let index = attributes.length - 1
463 for (; index >= 0; index--) {
464 const attribute = attributes[index]!
465 if (
466 is.JSXSpreadAttribute(attribute) ||
467 (is.JSXIdentifier(attribute.name) && attribute.name.name === 'children')
468 ) {
469 break
470 }
471 }
472 const attribute = attributes[index]
473 if (!attribute) {
474 return true
475 }
476 if (
477 is.JSXSpreadAttribute(attribute) ||
478 !attribute.value ||
479 is.StringLiteral(attribute.value)
480 ) {
481 return false
482 }
483 attributes.splice(index, 1)
484 setChildren(node, [attribute.value])
485 return true
486}
487β
488/**
489 * Whether a boundary without JSX children may receive them from a spread,
490 * which cannot be split. A spread object literal without children does not.
491 */
492function childrenComeFromSpread(node: t.JSXElement) {
493 if (getMeaningfulChildren(node.children).length) {
494 return false
495 }
496 const attributes = node.openingElement.attributes
497 for (let index = attributes.length - 1; index >= 0; index--) {
498 const attribute = attributes[index]!
499 if (!is.JSXSpreadAttribute(attribute)) {
500 if (
501 is.JSXIdentifier(attribute.name) &&
502 attribute.name.name === 'children'
503 ) {
504 return false
505 }
506 continue
507 }
508 const argument = unwrapExpression(attribute.argument)
509 if (
510 !is.ObjectExpression(argument) ||
511 objectExpressionMayHaveProperty(argument, 'children')
512 ) {
513 return true
514 }
515 }
516 return false
517}
518β
519function transformHydrateAst(
520 options: HydrateAst & {
521 code: string
522 id: string
523 root: string
524 env: 'client' | 'server'
525 framework: CompileStartFrameworkOptions
526 indexOffset?: number
527 /** Reports a boundary that is left unsplit */
528 warn?: (message: string) => void
529 },
530) {
531 if (!options.code.includes('Hydrate')) {
532 return null
533 }
534 const hydrateImport = getHydrateImport(options.ast, options.framework)
535 if (!hydrateImport) {
536 return null
537 }
538 const localName = hydrateImport.hydrateLocalName
539 const sourceId = cleanId(options.id)
540 const getBoundaryId = createBoundaryId(options.root, sourceId)
541 let nextBoundaryIndex = options.indexOffset ?? 0
542 const transformation = { modified: false }
543 let lazyName: string | undefined
544 const names = new Set([
545 ...options.module.bindings.map((binding) => binding.name),
546 ...options.module.unresolvedReferences.map((reference) => reference.name),
547 ])
548 const fresh = (base: string) => {
549 let name = `_${base}`
550 let count = 2
551 while (names.has(name)) {
552 name = `_${base}${count++}`
553 }
554 names.add(name)
555 return name
556 }
557 const prepend: t.Program['body'] = []
558 // Index before mutation so spreads can resolve declarations later in the file.
559 const objectExpressions = new WeakMap<t.Node, t.ObjectExpression>()
560 walk(options.ast, {
561 ObjectExpression(node) {
562 objectExpressions.set(sourceNode(options, node), node)
563 },
564 })
565 walk(options.ast, {
566 JSXElement(node, visitor) {
567 if (getJSXElementName(node) !== localName) {
568 return
569 }
570 if (options.env === 'server') {
571 node.openingElement.attributes = node.openingElement.attributes.filter(
572 (attribute) => {
573 if (
574 is.JSXAttribute(attribute) &&
575 is.JSXIdentifier(attribute.name) &&
576 attribute.name.name === 'fallback'
577 ) {
578 transformation.modified = true
579 return false
580 }
581 if (is.JSXSpreadAttribute(attribute)) {
582 const argument = unwrapExpression(attribute.argument)
583 const object = is.ObjectExpression(argument)
584 ? argument
585 : is.Identifier(argument)
586 ? getSingleUseObjectExpressionBinding(
587 options,
588 argument,
589 objectExpressions,
590 )
591 : undefined
592 if (object && stripObjectExpressionProperty(object, 'fallback')) {
593 transformation.modified = true
594 }
595 if (is.ObjectExpression(argument)) {
596 return argument.properties.length > 0
597 }
598 }
599 return true
600 },
601 )
602 }
603 if (getBooleanProp(node.openingElement, 'split') === false) {
604 return
605 }
606 if (options.env === 'client' && childrenComeFromSpread(node)) {
607 const position = sourcePosition(
608 options.code,
609 sourceNode(options, node).start,
610 )
611 options.warn?.(
612 `[tanstack-start] The <${localName}> at ${sourceId}:${position.line}:${position.column + 1} 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}.`,
613 )
614 }
615 const splittable = moveChildrenPropIntoChildren(node)
616 const inspection = inspectSplitBoundary(options, node, {
617 code: options.code,
618 framework: options.framework,
619 validate: true,
620 collectCaptured: options.env === 'client',
621 ...(options.env === 'client' ? { nestedHydrate: { localName } } : {}),
622 })
623 const index = nextBoundaryIndex
624 nextBoundaryIndex += 1 + inspection.nestedBoundaryCount
625 const id = getBoundaryId(index)
626 const exportName = `H${index}`
627 const existingId = getJSXAttribute(node.openingElement, 'h')
628 const idValue: t.StringLiteral = {
629 type: 'Literal',
630 value: id,
631 raw: JSON.stringify(id),
632 start: 0,
633 end: 0,
634 }
635 if (existingId) {
636 existingId.value = idValue
637 } else {
638 node.openingElement.attributes.push(
639 b.JSXAttribute({
640 name: b.JSXIdentifier({ name: 'h' }),
641 value: idValue,
642 }),
643 )
644 }
645 transformation.modified = true
646 if (options.env === 'server' || !splittable) {
647 return
648 }
649 const needsPreload = node.openingElement.attributes.some((attribute) => {
650 if (is.JSXAttribute(attribute)) {
651 return (
652 is.JSXIdentifier(attribute.name) &&
653 attribute.name.name === 'prefetch'
654 )
655 }
656 const argument = unwrapExpression(attribute.argument)
657 const object = is.ObjectExpression(argument)
658 ? argument
659 : is.Identifier(argument)
660 ? getSingleUseObjectExpressionBinding(
661 options,
662 argument,
663 objectExpressions,
664 )
665 : undefined
666 return !object || objectExpressionMayHaveProperty(object, 'prefetch')
667 })
668 if (!lazyName) {
669 lazyName = fresh('lazyRouteComponent')
670 prepend.push(
671 ...parseStatements(
672 `import { lazyRouteComponent as ${lazyName} } from ${JSON.stringify(`@tanstack/${options.framework}-router`)}`,
673 ),
674 )
675 }
676 const query = new URLSearchParams({ [tssHydrate]: id })
677 const componentName = fresh(exportName)
678 prepend.push(
679 ...parseStatements(
680 `const ${componentName} = ${lazyName}(() => import(${JSON.stringify(`${sourceId}?${query}`)}), ${JSON.stringify(exportName)})`,
681 ),
682 )
683 if (needsPreload) {
684 const preloadName = fresh(`${exportName}_preload`)
685 prepend.push(
686 ...parseStatements(`const ${preloadName} = ${componentName}.preload`),
687 )
688 node.openingElement.attributes.push(
689 b.JSXAttribute({
690 name: b.JSXIdentifier({ name: 'p' }),
691 value: b.JSXExpressionContainer({
692 expression: parseExpression(preloadName),
693 }),
694 }),
695 )
696 }
697 const props = inspection.captured
698 .map((name) => `${name}={${name}}`)
699 .join(' ')
700 const child = parseExpression(`<${componentName} ${props} />`)
701 setChildren(node, [b.JSXExpressionContainer({ expression: child })])
702 visitor.skip()
703 },
704 })
705 if (!transformation.modified) {
706 return null
707 }
708 let prologueEnd = 0
709 while (is.Directive(options.ast.body[prologueEnd])) {
710 prologueEnd++
711 }
712 options.ast.body.splice(prologueEnd, 0, ...prepend)
713 return true
714}
715β
716function loadHydrateVirtualModule(options: {
717 module: Module
718 id: string
719 root: string
720 code: string
721 framework: CompileStartFrameworkOptions
722}) {
723 const { sourceId, splitId, boundaryIndex } = parseHydrateVirtualId(options.id)
724 if (!splitId || boundaryIndex < 0) {
725 return null
726 }
727 const module = options.module
728 const { program: ast, originalNodes } = cloneModuleAst(module)
729 const context = { ast, module, originalNodes }
730 const hydrateImport = getHydrateImport(ast, options.framework)
731 if (!hydrateImport) {
732 return null
733 }
734 const getBoundaryId = createBoundaryId(options.root, sourceId)
735 let target: t.JSXElement | undefined
736 let captures: Array<string> = []
737 let index = 0
738 walk(ast, {
739 JSXElement(node, visitor) {
740 if (
741 getJSXElementName(node) !== hydrateImport.hydrateLocalName ||
742 getBooleanProp(node.openingElement, 'split') === false
743 ) {
744 return
745 }
746 if (index === boundaryIndex) {
747 if (
748 getBoundaryId(index) === splitId &&
749 moveChildrenPropIntoChildren(node)
750 ) {
751 target = node
752 captures = inspectSplitBoundary(context, node, {
753 code: options.code,
754 collectCaptured: true,
755 }).captured
756 }
757 visitor.stop()
758 }
759 index++
760 },
761 })
762 if (!target) {
763 return null
764 }
765 const children = getMeaningfulChildren(target.children)
766 const child = children.length === 1 ? children[0] : undefined
767 let expression: t.Expression = b.Literal({ value: null, raw: 'null' })
768 if (is.JSXExpressionContainer(child)) {
769 if (!is.JSXEmptyExpression(child.expression)) {
770 expression = child.expression
771 }
772 } else if (is.JSXElement(child) || is.JSXFragment(child)) {
773 expression = child
774 } else if (children.length) {
775 // Keep text as JSX so the JSX compiler applies entity and whitespace rules.
776 expression = b.JSXFragment({
777 openingFragment: b.JSXOpeningFragment({}),
778 closingFragment: b.JSXClosingFragment({}),
779 children: target.children,
780 })
781 }
782 const graph = moduleDeclarationGraph(module)
783 const keep = new Set<Binding>()
784 for (const child of children) {
785 for (const binding of collectModuleReferences(
786 module,
787 sourceNode(context, child),
788 )) {
789 keep.add(binding)
790 }
791 }
792 // The route is a singleton: code reading the module's `Route` imports the
793 // parent module's instead of creating the route again with its options.
794 const route = module.rootScope.bindings.find(
795 (binding) => binding.name === 'Route' && !binding.has(BindingFlags.Import),
796 )
797 const retained = expandTransitively(
798 keep,
799 new Map([...graph.dependencies].filter(([binding]) => binding !== route)),
800 )
801 if (route && retained.delete(route)) {
802 const { exports: moduleExports } = module
803 const exportedNames = moduleExports
804 .filter((entry) => entry.local === route && !entry.typeOnly)
805 .map((entry) => entry.name)
806 const exported = exportedNames.includes('Route')
807 ? 'Route'
808 : exportedNames.find((name) => name !== null)
809 if (!exported) {
810 throw codeFrameError(
811 options.code,
812 sourceNode(context, target),
813 'Hydrate cannot code-split children that read Route when the module does not export it. Export Route, or use split={false} for this boundary.',
814 )
815 }
816 let prologueEnd = 0
817 while (is.Directive(ast.body[prologueEnd])) {
818 prologueEnd++
819 }
820 ast.body.splice(
821 prologueEnd,
822 0,
823 ...parseStatements(
824 `import { ${/^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(exported) ? exported : JSON.stringify(exported)} as Route } from ${JSON.stringify(sourceId)}`,
825 ),
826 )
827 }
828 const selected = new Set(
829 [...graph.declarationSymbols]
830 .filter(([, owners]) =>
831 [...owners].some((binding) => retained.has(binding)),
832 )
833 .map(([declaration]) => declaration),
834 )
835 ast.body = ast.body.flatMap((statement): t.Program['body'] => {
836 if (is.ImportDeclaration(statement) || is.Directive(statement)) {
837 return [statement]
838 }
839 const declaration =
840 is.ExportNamedDeclaration(statement) ||
841 is.ExportDefaultDeclaration(statement)
842 ? statement.declaration
843 : statement
844 if (is.VariableDeclaration(declaration)) {
845 declaration.declarations = declaration.declarations.filter((item) =>
846 selected.has(sourceNode(context, item)),
847 )
848 return declaration.declarations.length
849 ? [unwrapExport(statement, declaration)]
850 : []
851 }
852 if (
853 (is.FunctionDeclaration(declaration) ||
854 is.ClassDeclaration(declaration) ||
855 is.TSDeclareFunction(declaration) ||
856 is.TSModuleDeclaration(declaration) ||
857 is.TSEnumDeclaration(declaration)) &&
858 selected.has(sourceNode(context, declaration))
859 ) {
860 return [unwrapExport(statement, declaration)]
861 }
862 return []
863 })
864 const params = captures.length ? `{ ${captures.join(', ')} }` : ''
865 const output = parseStatements(
866 `export function H${boundaryIndex}(${params}) {}`,
867 )[0] as t.ExportNamedDeclaration
868 const component = output.declaration as t.FunctionDeclaration
869 component.body!.body.push(b.ReturnStatement({ argument: expression }))
870 ast.body.push(output)
871 removeUnusedBindings(module, ast, originalNodes)
872 keepFilePragmas(module.ast, ast)
873 return generateModule(ast, { source: options.code, filename: options.id })
874}
875export function createHydrateCompilerPlugin(): StartCompilerPlugin {
876 type SourceEntry = {
877 module: Module
878 code: string
879 framework: CompileStartFrameworkOptions
880 virtualModules: Map<string, StartCompilerTransformResult | null>
881 }
882β
883 const sourcesByEnvironment = new Map<string, Map<string, SourceEntry>>()
884 const reportedWarnings = new Set<string>()
885β
886 const getEnvironmentSources = (envName: string) => {
887 let sources = sourcesByEnvironment.get(envName)
888 if (!sources) {
889 sources = new Map()
890 sourcesByEnvironment.set(envName, sources)
891 }
892 return sources
893 }
894β
895 const setSource = (
896 envName: string,
897 id: string,
898 code: string,
899 framework: CompileStartFrameworkOptions,
900 sourceModule?: Module,
901 ) => {
902 const sourceId = cleanId(id)
903 const sources = getEnvironmentSources(envName)
904 const existing = sources.get(sourceId)
905 if (existing?.code === code && existing.framework === framework) {
906 return existing
907 }
908β
909 const entry = {
910 module: sourceModule ?? analyzeModule({ code, filename: sourceId }),
911 code,
912 framework,
913 virtualModules: new Map<string, StartCompilerTransformResult | null>(),
914 }
915 sources.set(sourceId, entry)
916 return entry
917 }
918β
919 const getSourceEntry = (envName: string, id: string) =>
920 sourcesByEnvironment.get(envName)?.get(cleanId(id))
921β
922 const deleteSource = (envName: string, id: string) => {
923 sourcesByEnvironment.get(envName)?.delete(cleanId(id))
924 }
925β
926 return {
927 name: 'tanstack-start-core:hydrate',
928 detect: HYDRATE_DETECTION_PATTERN,
929 virtualModuleIdPattern: new RegExp(`[?&]${tssHydrate}=`),
930 transformAst(context) {
931 const virtualModule = parseHydrateVirtualId(context.id)
932 const indexOffset =
933 virtualModule.boundaryIndex < 0
934 ? undefined
935 : virtualModule.boundaryIndex + 1
936 const result = transformHydrateAst({
937 ast: context.ast,
938 module: context.module,
939 originalNodes: context.originalNodes,
940 code: context.code,
941 id: context.id,
942 root: context.root,
943 env: context.env,
944 framework: context.framework,
945 indexOffset,
946 // A dev warning about the source module, once per message
947 warn:
948 context.mode === 'dev' && virtualModule.boundaryIndex < 0
949 ? (message) => {
950 if (!reportedWarnings.has(message)) {
951 reportedWarnings.add(message)
952 context.warn?.(message)
953 }
954 }
955 : undefined,
956 })
957β
958 if (result && virtualModule.boundaryIndex < 0) {
959 setSource(
960 context.envName,
961 context.id,
962 context.code,
963 context.framework,
964 context.module,
965 )
966 }
967β
968 return !!result
969 },
970 loadVirtualModule(context) {
971 const virtualModule = parseHydrateVirtualId(context.id)
972 if (!virtualModule.splitId || virtualModule.boundaryIndex < 0) {
973 return null
974 }
975β
976 const existingSourceEntry = getSourceEntry(
977 context.envName,
978 virtualModule.sourceId,
979 )
980 const sourceEntry =
981 context.code === undefined
982 ? existingSourceEntry
983 : setSource(
984 context.envName,
985 virtualModule.sourceId,
986 context.code,
987 existingSourceEntry?.framework ??
988 (context.code.includes('@tanstack/solid-start')
989 ? 'solid'
990 : 'react'),
991 )
992β
993 if (!sourceEntry) {
994 throw new MissingHydrateSourceError(context.id)
995 }
996β
997 if (sourceEntry.virtualModules.has(context.id)) {
998 return sourceEntry.virtualModules.get(context.id)!
999 }
1000β
1001 const result = loadHydrateVirtualModule({
1002 module: sourceEntry.module,
1003 code: sourceEntry.code,
1004 id: context.id,
1005 root: context.root,
1006 framework: sourceEntry.framework,
1007 })
1008 sourceEntry.virtualModules.set(context.id, result)
1009 return result
1010 },
1011 invalidateModule(context) {
1012 deleteSource(context.envName, context.id)
1013 },
1014 }
1015}