@pithyjs/vite-plugin 0.2.0-beta.26 → 0.2.0-beta.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,11 @@ export interface AotCodegenOptions {
27
27
  wrappable?: boolean;
28
28
  anchorSlots?: ReadonlyMap<string, string>;
29
29
  sub?: boolean;
30
+ /**
31
+ * In DEV, the template's root factory lists its `<slot>` names and a
32
+ * template component's child factory marks its fragment (BUG-130).
33
+ */
34
+ declareSlots?: boolean;
30
35
  }
31
36
  /**
32
37
  * Generate AOT code from a PithyNode tree.
@@ -1 +1 @@
1
- {"version":3,"file":"generateDomFactory.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EASL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAwB3B,MAAM,WAAW,gBAAgB;IAC/B,6FAA6F;IAC7F,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,kBAAkB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAAE,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE,iBAAsB,GAC9B,gBAAgB,CAoGlB"}
1
+ {"version":3,"file":"generateDomFactory.d.ts","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EAUL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAwB3B,MAAM,WAAW,gBAAgB;IAC/B,6FAA6F;IAC7F,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,iBAAiB;IAChC,kBAAkB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,WAAW,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,GAAG,CAAC,EAAE,OAAO,CAAC;IACd;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAAE,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,OAAO,GAAE,iBAAsB,GAC9B,gBAAgB,CAkHlB"}
@@ -13,7 +13,7 @@
13
13
  }
14
14
  }
15
15
  */
16
- import { boundSlotMessage, componentChildDirectiveMessage, componentChildDirectives, loopConflictMessage, sharedSlotMessage, sharedSlots, isSvgNode, svgBindMessage, } from '@pithyjs/compiler';
16
+ import { boundSlotMessage, collectSlotNames, componentChildDirectiveMessage, componentChildDirectives, loopConflictMessage, sharedSlotMessage, sharedSlots, isSvgNode, svgBindMessage, } from '@pithyjs/compiler';
17
17
  import { createSerializeContext, serializeNode, appendChildren, enterTemplate, } from './serializeNode.js';
18
18
  import { generateBindings, serializeBindings, } from './generateBindings.js';
19
19
  import { collectIfChain, stripStructuralDirective, isDefaultCase, } from './structuralCodegen.js';
@@ -70,6 +70,7 @@ export function generateDomFactory(nodes, hash, scopeId, options = {}) {
70
70
  const subOptions = {
71
71
  templateComponents: options.templateComponents,
72
72
  anchorSlots: options.anchorSlots,
73
+ declareSlots: options.declareSlots,
73
74
  };
74
75
  // Generate DOM factory body
75
76
  const ctx = createSerializeContext(scopeId);
@@ -92,9 +93,18 @@ export function generateDomFactory(nodes, hash, scopeId, options = {}) {
92
93
  else if (topLevelVarNames.length > 1) {
93
94
  bodyLines.push(`f.append(${topLevelVarNames.join(',')});`);
94
95
  }
95
- const fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';
96
+ let fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';
96
97
  const bindingsArg = allDescriptors.length > 0 ? bindingsName : '[]';
97
98
  const drainArg = options.sub ? ',false' : '';
99
+ if (options.declareSlots && options.wrappable) {
100
+ // The runtime reads a root fragment without a slot list as an older build.
101
+ bodyLines.push(`const __w=${fragment};`, `if(import.meta.env.DEV)__w.__pithyChildFactory=true;`);
102
+ fragment = '__w';
103
+ }
104
+ else if (options.declareSlots && !options.sub) {
105
+ const names = collectSlotNames(nodes).map(n => `'${escapeJS(n)}'`);
106
+ bodyLines.push(`if(import.meta.env.DEV)f.__pithySlots=[${names.join(',')}];`);
107
+ }
98
108
  bodyLines.push(`return __applyBindings(${fragment},${bindingsArg},__ctx${drainArg});`);
99
109
  // Assemble final code: sub-factories first, then this factory
100
110
  const codeLines = [];
@@ -1 +1 @@
1
- {"version":3,"file":"generateDomFactory.js","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,gBAAgB,EAChB,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,EACX,SAAS,EACT,cAAc,GAEf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,aAAa,GAEd,MAAM,iBAAi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AAC,EAAE,CAAC,CAAC;QACrE,OAAO;IACT,CAAC;IACD,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,KAAK,SAAS;QAC9B,OAAO,CAAC,IAAI,CAAC,eAAe,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACvD,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;QACjD,OAAO,CAAC,IAAI,CAAC,eAAe,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;AAChE,CAAC;AAED,2EAA2E;AAC3E,SAAS,gBAAgB,CAAC,IAAe;IACvC,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,EAAE,KAAK,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACtE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;IAC/C,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.aot.generate-dom-factory\",\n \"title\": \"AOT DOM Factory Generator\",\n \"category\": \"compiler\",\n \"description\": \"Generates a DOM factory function from parsed template nodes, producing static HTML with binding placeholders.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n boundSlotMessage,\n componentChildDirectiveMessage,\n componentChildDirectives,\n loopConflictMessage,\n sharedSlotMessage,\n sharedSlots,\n isSvgNode,\n svgBindMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport {\n createSerializeContext,\n serializeNode,\n appendChildren,\n enterTemplate,\n type SerializeContext,\n} from './serializeNode';\nimport {\n generateBindings,\n serializeBindings,\n type BindingDescriptor,\n type IfDescriptor,\n type ForDescriptor,\n type SwitchDescriptor,\n type ProjectionDescriptor,\n} from './generateBindings';\nimport {\n collectIfChain,\n stripStructuralDirective,\n isDefaultCase,\n} from './structuralCodegen';\nimport { escapeJS } from './utils';\n\nexport interface AotCodegenResult {\n /** Complete JS code for the factory function + bindings const (includes sub-factory code) */\n code: string;\n /** The factory function name (e.g. \"__f_a7f3\") */\n factoryName: string;\n /** The bindings variable name (e.g. \"__b_a7f3\") */\n bindingsName: string;\n}\n\nexport interface AotCodegenOptions {\n templateComponents?: ReadonlySet<string>;\n wrappable?: boolean;\n anchorSlots?: ReadonlyMap<string, string>;\n sub?: boolean;\n}\n\n/**\n * Generate AOT code from a PithyNode tree.\n *\n * Produces:\n * 1. Sub-factory code for structural directives (@if branches, @for bodies, @switch cases)\n * 2. A bindings descriptor array (const __b_{hash} = [...])\n * 3. A DOM factory function (function __f_{hash}(__ctx) { ... })\n *\n * The factory creates DOM nodes via createElement/createTextNode,\n * sets static attributes, and calls __applyBindings with the\n * pre-extracted descriptors.\n *\n * Structural directives generate sub-factory functions (via recursive calls)\n * and comment placeholders in the parent factory. Sub-factory code is prepended\n * to the output so function references resolve correctly.\n *\n * **Phase 5 gap:** AOT factories do not set runtime-only DOM properties that\n * `pithyTreeToDom` assigns (`__pithyCtx`, `__pithyNode`, `__nodeId`,\n * `__slotName`, `__fallbackFactory`). Phase 5's `applyBindings()` will need\n * to set these on the factory-created DOM before wiring reactive effects.\n *\n * @param nodes - Parsed PithyNode tree (from parse5ToPithyTree)\n * @param hash - Unique identifier for this template (used in names)\n * @param scopeId - CSS scope ID (e.g. \"pithy-abc123\")\n *\n * @example\n * ```typescript\n * const result = generateDomFactory(pithyNodes, 'a7f3', 'pithy-abc');\n * // result.code contains the full factory + bindings code\n * // result.factoryName is \"__f_a7f3\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.generate-dom-factory\",\"name\":\"generateDomFactory\",\"stability\":\"experimental\",\"signature\":\"(nodes: PithyNode[], hash: string, scopeId?: string, options?: AotCodegenOptions) => AotCodegenResult\"} */\nexport function generateDomFactory(\n nodes: PithyNode[],\n hash: string,\n scopeId?: string,\n options: AotCodegenOptions = {}\n): AotCodegenResult {\n // Validate scopeId — it's interpolated into an attribute name (data-scope-{id}),\n // so it must contain only characters valid in HTML attribute names.\n if (scopeId && !/^[a-zA-Z0-9_-]+$/.test(scopeId)) {\n throw new Error(\n `AOT: invalid scopeId \"${scopeId}\" — must contain only alphanumeric, hyphen, or underscore characters.`\n );\n }\n\n // Sanitize hash to ensure valid JS identifiers (replace non-alphanumeric with _)\n const safeHash = hash.replace(/[^a-zA-Z0-9_$]/g, '_');\n const factoryName = `__f_${safeHash}`;\n const bindingsName = `__b_${safeHash}`;\n\n // Accumulate sub-factory code blocks (emitted before this factory)\n const subFactoryCodeBlocks: string[] = [];\n\n // Accumulate structural descriptors (merged with Phase 1 descriptors)\n const structuralDescriptors: BindingDescriptor[] = [];\n\n const childFactories = new Map<string, string>();\n const slotFactories = new Map<string, Record<string, string>>();\n const subOptions: AotCodegenOptions = {\n templateComponents: options.templateComponents,\n anchorSlots: options.anchorSlots,\n };\n\n // Generate DOM factory body\n const ctx = createSerializeContext(scopeId);\n\n // Process all nodes recursively, handling structural directives at every level\n const topLevelVarNames = processNodes(\n nodes,\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n subOptions,\n childFactories,\n slotFactories\n );\n\n // Generate Phase 1 binding descriptors (non-structural)\n const phase1Descriptors = generateBindings(\n nodes,\n childFactories,\n slotFactories\n );\n\n // Merge all descriptors: structural first, then Phase 1\n const allDescriptors = [...structuralDescriptors, ...phase1Descriptors];\n const bindingsCode = serializeBindings(allDescriptors);\n\n // Build factory function body\n const bodyLines: string[] = [];\n bodyLines.push(`const f=document.createDocumentFragment();`);\n\n // Add all serialized node creation code\n bodyLines.push(...ctx.lines);\n\n // Append top-level nodes to fragment\n if (topLevelVarNames.length === 1) {\n bodyLines.push(`f.appendChild(${topLevelVarNames[0]});`);\n } else if (topLevelVarNames.length > 1) {\n bodyLines.push(`f.append(${topLevelVarNames.join(',')});`);\n }\n\n const fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';\n const bindingsArg = allDescriptors.length > 0 ? bindingsName : '[]';\n const drainArg = options.sub ? ',false' : '';\n bodyLines.push(\n `return __applyBindings(${fragment},${bindingsArg},__ctx${drainArg});`\n );\n\n // Assemble final code: sub-factories first, then this factory\n const codeLines: string[] = [];\n\n // Sub-factory code blocks (from structural directives)\n for (const block of subFactoryCodeBlocks) {\n codeLines.push(block);\n }\n\n // Bindings constant (only if non-empty)\n if (allDescriptors.length > 0) {\n codeLines.push(`const ${bindingsName}=${bindingsCode};`);\n }\n\n // Factory function\n codeLines.push(\n `function ${factoryName}(__ctx${options.wrappable ? ',__wrap' : ''}){`\n );\n codeLines.push(...bodyLines);\n codeLines.push(`}`);\n\n return {\n code: codeLines.join('\\n'),\n factoryName,\n bindingsName,\n };\n}\n\n// ─── Internal: recursive tree processing with structural awareness ───────────\n\n/**\n * Process an array of sibling nodes, handling structural directives at every level.\n * Returns the varNames of the processed top-level nodes (for parent.append()).\n *\n * This function replaces the simple for-of loop over serializeNode calls.\n * It detects structural directives (which span siblings for @if chains)\n * and delegates to sub-factory generation, creating comment placeholders\n * in the current factory for the structural nodes.\n *\n * For non-structural elements, it serializes the element shell (no children)\n * via serializeNode, then recursively processes children here.\n */\nfunction processNodes(\n nodes: PithyNode[],\n ctx: SerializeContext,\n safeHash: string,\n scopeId: string | undefined,\n subFactoryCodeBlocks: string[],\n structuralDescriptors: BindingDescriptor[],\n options: AotCodegenOptions,\n childFactories: Map<string, string>,\n slotFactories: Map<string, Record<string, string>>\n): string[] {\n const varNames: string[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n\n // ─── @if/@else-if/@else chain ────────────────────────────────────\n if (node.type === 'element' && node.directives?.if !== undefined) {\n const chain = collectIfChain(nodes, i);\n const pid = node.nodeId ?? `_${i}`;\n i += chain.length - 1; // Skip consumed siblings\n\n // Generate sub-factory for each branch\n const branches: IfDescriptor['branches'] = [];\n for (let b = 0; b < chain.length; b++) {\n const branchNode = chain[b];\n const branchHash = `${safeHash}_if_${pid}_${b}`;\n const stripped = stripStructuralDirective(branchNode);\n if (branchNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: branchNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], branchHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const branch: IfDescriptor['branches'][0] = {\n factory: sub.factoryName,\n };\n if (branchNode.directives?.if !== undefined)\n branch.expr = branchNode.directives.if;\n else if (branchNode.directives?.elseIf !== undefined)\n branch.expr = branchNode.directives.elseIf;\n branches.push(branch);\n }\n\n // Emit comment placeholder\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('if:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n structuralDescriptors.push({ t: 'if', pid, branches });\n continue;\n }\n\n // ─── Orphaned @else-if, @else, @case, @default ────────────────────\n if (\n node.type === 'element' &&\n (node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined ||\n node.directives?.case !== undefined ||\n isDefaultCase(node))\n ) {\n if (\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n )\n console.warn(\n `[pithy:aot] ${node.directives.elseIf !== undefined ? '@else-if' : '@else'} has no @if directly before it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n else\n console.warn(\n `[pithy:aot] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n continue;\n }\n\n // ─── @for loop ───────────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.for) {\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n const pid = node.nodeId ?? `_${i}`;\n const forHash = `${safeHash}_for_${pid}`;\n const stripped = withoutTrackProp(stripStructuralDirective(node));\n const sub = generateDomFactory([stripped], forHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('for:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n const forDir = node.directives.for;\n const desc: ForDescriptor = {\n t: 'for',\n pid,\n item: forDir.itemVar,\n expr: forDir.collectionExpr,\n factory: sub.factoryName,\n };\n if (forDir.indexVar) desc.index = forDir.indexVar;\n if (forDir.trackBy) desc.trackBy = forDir.trackBy;\n const forTag = node.originalTagName ?? node.tagName;\n if (forTag) desc.tag = forTag;\n structuralDescriptors.push(desc);\n continue;\n }\n\n // ─── @switch block ───────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.switch !== undefined) {\n const pid = node.nodeId ?? `_${i}`;\n // Ensure the original node has nodeId so generateBindings can find it too\n if (!node.nodeId) node.nodeId = pid;\n\n // Serialize the switch container (without children, without @switch directive).\n // nodeId is guaranteed set above, so data-pid is always emitted.\n const switchShell: PithyNode = {\n ...node,\n children: [],\n directives: stripSwitchDirective(node.directives),\n };\n const shellResult = serializeNode(switchShell, ctx);\n if (shellResult) varNames.push(shellResult.varName);\n warnElement(node, node.originalTagName ?? node.tagName ?? '');\n\n // Generate sub-factory for each @case/@default child\n const cases: SwitchDescriptor['cases'] = [];\n let dropped: string | undefined;\n for (let c = 0; c < (node.children ?? []).length; c++) {\n const caseNode = node.children![c];\n if (\n caseNode.type !== 'element' ||\n (caseNode.directives?.case === undefined && !isDefaultCase(caseNode))\n ) {\n for (const name of caseNode.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(caseNode.originalTagName ?? caseNode.tagName ?? '', name)}`\n );\n if (caseNode.type === 'element')\n dropped ??= `<${caseNode.originalTagName ?? caseNode.tagName}>`;\n else if (caseNode.type === 'slot') dropped ??= '<slot>';\n else if (caseNode.type === 'text' && caseNode.textContent?.trim())\n dropped ??= JSON.stringify(caseNode.textContent.trim());\n continue;\n }\n\n const caseHash = `${safeHash}_sw_${pid}_${c}`;\n const stripped = stripStructuralDirective(caseNode);\n if (caseNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: caseNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], caseHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const caseDesc: SwitchDescriptor['cases'][0] = {\n factory: sub.factoryName,\n };\n if (caseNode.directives?.case !== undefined)\n caseDesc.val = caseNode.directives.case;\n cases.push(caseDesc);\n }\n\n if (dropped)\n console.warn(\n `[pithy:aot] @switch renders only its @case/@default children; ${dropped} is dropped`\n );\n\n structuralDescriptors.push({\n t: 'switch',\n pid,\n expr: node.directives.switch,\n cases,\n });\n continue;\n }\n\n // ─── Text nodes ─────────────────────────────────────────────────\n if (node.type === 'text') {\n const result = serializeNode(node, ctx);\n if (result) varNames.push(result.varName);\n continue;\n }\n\n // ─── Slot nodes (content projection) ─────────────────────────────\n if (node.type === 'slot') {\n const slotName = node.slotName ?? '';\n const pid = node.nodeId ?? `_slot_${ctx.commentCount}`;\n // A factory is one render scope; only its first slot of a name gets content.\n const dup = structuralDescriptors.some(\n d => d.t === 'proj' && d.name === slotName\n );\n\n // Emit comment anchor for the slot\n const commentVar = `c${ctx.commentCount++}`;\n const anchor = dup ? `slot-dup:${pid}` : `slot:${slotName}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('${escapeJS(anchor)}');`\n );\n varNames.push(commentVar);\n\n // Build projection descriptor\n const projDesc: ProjectionDescriptor = {\n t: 'proj',\n pid,\n name: slotName,\n };\n if (dup) projDesc.dup = true;\n\n // Generate sub-factory for fallback content if present\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n const fbHash = `${safeHash}_slot_${pid}`;\n // Roots of the fallback factory, so bare text binds at its root.\n const roots = node.fallbackChildren.map(child =>\n child.parentId === node.nodeId\n ? { ...child, parentId: undefined }\n : child\n );\n const sub = generateDomFactory(roots, fbHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n projDesc.fallback = sub.factoryName;\n }\n\n structuralDescriptors.push(projDesc);\n continue;\n }\n\n // ─── Regular element (no structural directive on THIS node) ──────\n // Serialize element shell (without children) via serializeNode,\n // then process children recursively with structural awareness.\n if (node.type === 'element') {\n const shell: PithyNode = { ...node, children: [] };\n const result = serializeNode(shell, ctx);\n if (!result) continue;\n\n const tag = node.originalTagName ?? node.tagName ?? '';\n for (const name of componentChildDirectives(node))\n console.warn(\n `[pithy:aot] ${componentChildDirectiveMessage(tag, name)}`\n );\n warnElement(node, tag);\n if (\n node.isComponent &&\n node.nodeId &&\n node.children?.length &&\n options.templateComponents?.has(tag)\n ) {\n const { children, anchorSlots } = asTemplateRoots(\n node.children,\n node.nodeId,\n tag\n );\n const sub = generateDomFactory(\n children,\n `${safeHash}_tpl_${node.nodeId}`,\n scopeId,\n { ...options, wrappable: true, anchorSlots }\n );\n subFactoryCodeBlocks.push(sub.code);\n childFactories.set(node.nodeId, sub.factoryName);\n varNames.push(result.varName);\n continue;\n }\n\n // Each slot mount renders and binds its content afresh, as dev does.\n if (node.isComponent && node.nodeId && node.children?.length) {\n const slots: Record<string, string> = Object.create(null);\n let n = 0;\n for (const [name, group] of groupSlots(\n node.children,\n node.nodeId,\n tag\n )) {\n const sub = generateDomFactory(\n group,\n `${safeHash}_cs_${node.nodeId}_${n++}`,\n scopeId,\n { ...options, sub: true }\n );\n subFactoryCodeBlocks.push(sub.code);\n slots[name] = sub.factoryName;\n }\n slotFactories.set(node.nodeId, slots);\n varNames.push(result.varName);\n continue;\n }\n\n // Recursively process children (handles nested structural directives)\n const leave = enterTemplate(node, result.varName, ctx);\n const childVarNames = processNodes(\n node.children ?? [],\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n options,\n childFactories,\n slotFactories\n );\n\n leave();\n appendChildren(node, result.varName, childVarNames, ctx);\n\n varNames.push(result.varName);\n continue;\n }\n }\n\n return varNames;\n}\n\nfunction markAnchorSlot(\n ctx: SerializeContext,\n commentVar: string,\n slot: string | undefined\n): void {\n if (slot === undefined) return;\n ctx.lines.push(`${commentVar}.__pithyAnchorSlot='${escapeJS(slot)}';`);\n}\n\nconst BLANK = /^[ \\t\\n\\f\\r]*$/;\n\nfunction warnMixedChainSlots(\n nodes: PithyNode[],\n ownerTag: string,\n outcome: string\n): void {\n let chainSlot: string | undefined;\n let inChain = false;\n let chainWarned = false;\n for (const { directives: d } of nodes) {\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n if (d?.if !== undefined) {\n inChain = true;\n chainSlot = d.slot;\n chainWarned = false;\n } else if (!isBranch) {\n inChain = false;\n }\n if (isBranch && inChain && d.slot !== chainSlot && !chainWarned) {\n chainWarned = true;\n console.warn(\n `[pithy:aot] <${ownerTag}>: the branches of an @if chain carry different slots ` +\n `(${chainSlot ?? 'none'} and ${d.slot ?? 'none'}). ${outcome}`\n );\n }\n if (d?.else !== undefined) inChain = false;\n }\n}\n\n/** Groups a component's children by slot name, as `collectSlotMap` does. */\nfunction groupSlots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): Map<string, PithyNode[]> {\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'Each slot keeps only the branches that name it; a branch cut off from its @if is dropped.'\n );\n const groups = new Map<string, PithyNode[]>();\n for (const child of nodes) {\n const name = child.directives?.slot || '';\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const group = groups.get(name);\n if (group) group.push(root);\n else groups.set(name, [root]);\n }\n const blank = (n: PithyNode) =>\n n.type === 'text' && BLANK.test(n.textContent ?? '');\n const main = groups.get('');\n if (main) {\n let start = 0;\n let end = main.length;\n while (start < end && blank(main[start])) start++;\n while (end > start && blank(main[end - 1])) end--;\n if (start < end) groups.set('', main.slice(start, end));\n else groups.delete('');\n }\n return groups;\n}\n\nfunction asTemplateRoots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): { children: PithyNode[]; anchorSlots: Map<string, string> } {\n const anchorSlots = new Map<string, string>();\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'The whole chain is placed by its first branch.'\n );\n\n const children = nodes.map(child => {\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const d = root.directives;\n const isHead = d?.if !== undefined;\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n const isLoop = d?.for !== undefined;\n\n if (!d || d.slot === undefined || !(isHead || isBranch || isLoop))\n return root;\n\n if (root.nodeId && (isHead || isLoop)) anchorSlots.set(root.nodeId, d.slot);\n const { slot: _slot, ...directives } = d;\n return { ...root, directives };\n });\n\n return { children, anchorSlots };\n}\n\n/**\n * Remove the `switch` field from a ParsedDirectives object.\n * Used to serialize the switch container element without the @switch directive\n * (since the directive is captured in the SwitchDescriptor instead).\n */\nfunction stripSwitchDirective(\n d: NonNullable<PithyNode['directives']>\n): PithyNode['directives'] {\n const { switch: _switch, ...rest } = d;\n return Object.keys(rest).length > 0\n ? (rest as PithyNode['directives'])\n : undefined;\n}\n\n/** Build-time copies of dev's `[slot]`, shared-slot and SVG `@bind` warnings. */\nfunction warnElement(node: PithyNode, tag: string): void {\n const d = node.directives;\n // A component's name says nothing about the namespace of what it renders.\n if (!node.isComponent) {\n if (d?.bind !== undefined && isSvgNode(node))\n console.warn(`[pithy:aot] ${svgBindMessage(node.tagName ?? tag)}`);\n return;\n }\n if (d?.bound?.slot !== undefined)\n console.warn(`[pithy:aot] ${boundSlotMessage(tag)}`);\n for (const slot of sharedSlots(node.children ?? []))\n console.warn(`[pithy:aot] ${sharedSlotMessage(tag, slot)}`);\n}\n\n/** `track` belongs to the `@for`, not to a component's props (BUG-110). */\nfunction withoutTrackProp(node: PithyNode): PithyNode {\n if (!node.isComponent || node.attrs?.track === undefined) return node;\n const { track: _track, ...attrs } = node.attrs;\n return { ...node, attrs };\n}\n"]}
1
+ {"version":3,"file":"generateDomFactory.js","sourceRoot":"","sources":["../../src/aotCodegen/generateDomFactory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,EACX,SAAS,EACT,cAAc,GAEf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,aAAa,GAEd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,GAMlB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,aAAa,GACd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAuBnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,uOAAuO;AACvO,MAAM,UAAU,kBAAkB,CAChC,KAAkB,EAClB,IAAY,EACZ,OAAgB,EAChB,UAA6B,EAAE;IAE/B,iFAAiF;IACjF,oEAAoE;IACpE,IAAI,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,KAAK,CACb,yBAAyB,OAAO,uEAAuE,CACxG,CAAC;IACJ,CAAC;IAED,iFAAiF;IACjF,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,OAAO,QAAQ,EAAE,CAAC;IACtC,MAAM,YAAY,GAAG,O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GAAG,CAAC,EAAE,CAAC,CAAC;IACvD,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;QACjD,OAAO,CAAC,IAAI,CAAC,eAAe,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;AAChE,CAAC;AAED,2EAA2E;AAC3E,SAAS,gBAAgB,CAAC,IAAe;IACvC,IAAI,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,EAAE,KAAK,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACtE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;IAC/C,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.aot.generate-dom-factory\",\n \"title\": \"AOT DOM Factory Generator\",\n \"category\": \"compiler\",\n \"description\": \"Generates a DOM factory function from parsed template nodes, producing static HTML with binding placeholders.\",\n \"since\": \"0.0.1\",\n \"stability\": \"experimental\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"aotCodegen.test.ts\" },\n \"integration\": { \"required\": false, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport {\n boundSlotMessage,\n collectSlotNames,\n componentChildDirectiveMessage,\n componentChildDirectives,\n loopConflictMessage,\n sharedSlotMessage,\n sharedSlots,\n isSvgNode,\n svgBindMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport {\n createSerializeContext,\n serializeNode,\n appendChildren,\n enterTemplate,\n type SerializeContext,\n} from './serializeNode';\nimport {\n generateBindings,\n serializeBindings,\n type BindingDescriptor,\n type IfDescriptor,\n type ForDescriptor,\n type SwitchDescriptor,\n type ProjectionDescriptor,\n} from './generateBindings';\nimport {\n collectIfChain,\n stripStructuralDirective,\n isDefaultCase,\n} from './structuralCodegen';\nimport { escapeJS } from './utils';\n\nexport interface AotCodegenResult {\n /** Complete JS code for the factory function + bindings const (includes sub-factory code) */\n code: string;\n /** The factory function name (e.g. \"__f_a7f3\") */\n factoryName: string;\n /** The bindings variable name (e.g. \"__b_a7f3\") */\n bindingsName: string;\n}\n\nexport interface AotCodegenOptions {\n templateComponents?: ReadonlySet<string>;\n wrappable?: boolean;\n anchorSlots?: ReadonlyMap<string, string>;\n sub?: boolean;\n /**\n * In DEV, the template's root factory lists its `<slot>` names and a\n * template component's child factory marks its fragment (BUG-130).\n */\n declareSlots?: boolean;\n}\n\n/**\n * Generate AOT code from a PithyNode tree.\n *\n * Produces:\n * 1. Sub-factory code for structural directives (@if branches, @for bodies, @switch cases)\n * 2. A bindings descriptor array (const __b_{hash} = [...])\n * 3. A DOM factory function (function __f_{hash}(__ctx) { ... })\n *\n * The factory creates DOM nodes via createElement/createTextNode,\n * sets static attributes, and calls __applyBindings with the\n * pre-extracted descriptors.\n *\n * Structural directives generate sub-factory functions (via recursive calls)\n * and comment placeholders in the parent factory. Sub-factory code is prepended\n * to the output so function references resolve correctly.\n *\n * **Phase 5 gap:** AOT factories do not set runtime-only DOM properties that\n * `pithyTreeToDom` assigns (`__pithyCtx`, `__pithyNode`, `__nodeId`,\n * `__slotName`, `__fallbackFactory`). Phase 5's `applyBindings()` will need\n * to set these on the factory-created DOM before wiring reactive effects.\n *\n * @param nodes - Parsed PithyNode tree (from parse5ToPithyTree)\n * @param hash - Unique identifier for this template (used in names)\n * @param scopeId - CSS scope ID (e.g. \"pithy-abc123\")\n *\n * @example\n * ```typescript\n * const result = generateDomFactory(pithyNodes, 'a7f3', 'pithy-abc');\n * // result.code contains the full factory + bindings code\n * // result.factoryName is \"__f_a7f3\"\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.aot.generate-dom-factory\",\"name\":\"generateDomFactory\",\"stability\":\"experimental\",\"signature\":\"(nodes: PithyNode[], hash: string, scopeId?: string, options?: AotCodegenOptions) => AotCodegenResult\"} */\nexport function generateDomFactory(\n nodes: PithyNode[],\n hash: string,\n scopeId?: string,\n options: AotCodegenOptions = {}\n): AotCodegenResult {\n // Validate scopeId — it's interpolated into an attribute name (data-scope-{id}),\n // so it must contain only characters valid in HTML attribute names.\n if (scopeId && !/^[a-zA-Z0-9_-]+$/.test(scopeId)) {\n throw new Error(\n `AOT: invalid scopeId \"${scopeId}\" — must contain only alphanumeric, hyphen, or underscore characters.`\n );\n }\n\n // Sanitize hash to ensure valid JS identifiers (replace non-alphanumeric with _)\n const safeHash = hash.replace(/[^a-zA-Z0-9_$]/g, '_');\n const factoryName = `__f_${safeHash}`;\n const bindingsName = `__b_${safeHash}`;\n\n // Accumulate sub-factory code blocks (emitted before this factory)\n const subFactoryCodeBlocks: string[] = [];\n\n // Accumulate structural descriptors (merged with Phase 1 descriptors)\n const structuralDescriptors: BindingDescriptor[] = [];\n\n const childFactories = new Map<string, string>();\n const slotFactories = new Map<string, Record<string, string>>();\n const subOptions: AotCodegenOptions = {\n templateComponents: options.templateComponents,\n anchorSlots: options.anchorSlots,\n declareSlots: options.declareSlots,\n };\n\n // Generate DOM factory body\n const ctx = createSerializeContext(scopeId);\n\n // Process all nodes recursively, handling structural directives at every level\n const topLevelVarNames = processNodes(\n nodes,\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n subOptions,\n childFactories,\n slotFactories\n );\n\n // Generate Phase 1 binding descriptors (non-structural)\n const phase1Descriptors = generateBindings(\n nodes,\n childFactories,\n slotFactories\n );\n\n // Merge all descriptors: structural first, then Phase 1\n const allDescriptors = [...structuralDescriptors, ...phase1Descriptors];\n const bindingsCode = serializeBindings(allDescriptors);\n\n // Build factory function body\n const bodyLines: string[] = [];\n bodyLines.push(`const f=document.createDocumentFragment();`);\n\n // Add all serialized node creation code\n bodyLines.push(...ctx.lines);\n\n // Append top-level nodes to fragment\n if (topLevelVarNames.length === 1) {\n bodyLines.push(`f.appendChild(${topLevelVarNames[0]});`);\n } else if (topLevelVarNames.length > 1) {\n bodyLines.push(`f.append(${topLevelVarNames.join(',')});`);\n }\n\n let fragment = options.wrappable ? '(__wrap?__wrap(f):f)' : 'f';\n const bindingsArg = allDescriptors.length > 0 ? bindingsName : '[]';\n const drainArg = options.sub ? ',false' : '';\n if (options.declareSlots && options.wrappable) {\n // The runtime reads a root fragment without a slot list as an older build.\n bodyLines.push(\n `const __w=${fragment};`,\n `if(import.meta.env.DEV)__w.__pithyChildFactory=true;`\n );\n fragment = '__w';\n } else if (options.declareSlots && !options.sub) {\n const names = collectSlotNames(nodes).map(n => `'${escapeJS(n)}'`);\n bodyLines.push(\n `if(import.meta.env.DEV)f.__pithySlots=[${names.join(',')}];`\n );\n }\n bodyLines.push(\n `return __applyBindings(${fragment},${bindingsArg},__ctx${drainArg});`\n );\n\n // Assemble final code: sub-factories first, then this factory\n const codeLines: string[] = [];\n\n // Sub-factory code blocks (from structural directives)\n for (const block of subFactoryCodeBlocks) {\n codeLines.push(block);\n }\n\n // Bindings constant (only if non-empty)\n if (allDescriptors.length > 0) {\n codeLines.push(`const ${bindingsName}=${bindingsCode};`);\n }\n\n // Factory function\n codeLines.push(\n `function ${factoryName}(__ctx${options.wrappable ? ',__wrap' : ''}){`\n );\n codeLines.push(...bodyLines);\n codeLines.push(`}`);\n\n return {\n code: codeLines.join('\\n'),\n factoryName,\n bindingsName,\n };\n}\n\n// ─── Internal: recursive tree processing with structural awareness ───────────\n\n/**\n * Process an array of sibling nodes, handling structural directives at every level.\n * Returns the varNames of the processed top-level nodes (for parent.append()).\n *\n * This function replaces the simple for-of loop over serializeNode calls.\n * It detects structural directives (which span siblings for @if chains)\n * and delegates to sub-factory generation, creating comment placeholders\n * in the current factory for the structural nodes.\n *\n * For non-structural elements, it serializes the element shell (no children)\n * via serializeNode, then recursively processes children here.\n */\nfunction processNodes(\n nodes: PithyNode[],\n ctx: SerializeContext,\n safeHash: string,\n scopeId: string | undefined,\n subFactoryCodeBlocks: string[],\n structuralDescriptors: BindingDescriptor[],\n options: AotCodegenOptions,\n childFactories: Map<string, string>,\n slotFactories: Map<string, Record<string, string>>\n): string[] {\n const varNames: string[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n\n // ─── @if/@else-if/@else chain ────────────────────────────────────\n if (node.type === 'element' && node.directives?.if !== undefined) {\n const chain = collectIfChain(nodes, i);\n const pid = node.nodeId ?? `_${i}`;\n i += chain.length - 1; // Skip consumed siblings\n\n // Generate sub-factory for each branch\n const branches: IfDescriptor['branches'] = [];\n for (let b = 0; b < chain.length; b++) {\n const branchNode = chain[b];\n const branchHash = `${safeHash}_if_${pid}_${b}`;\n const stripped = stripStructuralDirective(branchNode);\n if (branchNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: branchNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], branchHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const branch: IfDescriptor['branches'][0] = {\n factory: sub.factoryName,\n };\n if (branchNode.directives?.if !== undefined)\n branch.expr = branchNode.directives.if;\n else if (branchNode.directives?.elseIf !== undefined)\n branch.expr = branchNode.directives.elseIf;\n branches.push(branch);\n }\n\n // Emit comment placeholder\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('if:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n structuralDescriptors.push({ t: 'if', pid, branches });\n continue;\n }\n\n // ─── Orphaned @else-if, @else, @case, @default ────────────────────\n if (\n node.type === 'element' &&\n (node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined ||\n node.directives?.case !== undefined ||\n isDefaultCase(node))\n ) {\n if (\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n )\n console.warn(\n `[pithy:aot] ${node.directives.elseIf !== undefined ? '@else-if' : '@else'} has no @if directly before it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n else\n console.warn(\n `[pithy:aot] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped`\n );\n continue;\n }\n\n // ─── @for loop ───────────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.for) {\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n const pid = node.nodeId ?? `_${i}`;\n const forHash = `${safeHash}_for_${pid}`;\n const stripped = withoutTrackProp(stripStructuralDirective(node));\n const sub = generateDomFactory([stripped], forHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const commentVar = `c${ctx.commentCount++}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('for:${escapeJS(pid)}');`\n );\n markAnchorSlot(ctx, commentVar, options.anchorSlots?.get(pid));\n varNames.push(commentVar);\n\n const forDir = node.directives.for;\n const desc: ForDescriptor = {\n t: 'for',\n pid,\n item: forDir.itemVar,\n expr: forDir.collectionExpr,\n factory: sub.factoryName,\n };\n if (forDir.indexVar) desc.index = forDir.indexVar;\n if (forDir.trackBy) desc.trackBy = forDir.trackBy;\n const forTag = node.originalTagName ?? node.tagName;\n if (forTag) desc.tag = forTag;\n structuralDescriptors.push(desc);\n continue;\n }\n\n // ─── @switch block ───────────────────────────────────────────────\n if (node.type === 'element' && node.directives?.switch !== undefined) {\n const pid = node.nodeId ?? `_${i}`;\n // Ensure the original node has nodeId so generateBindings can find it too\n if (!node.nodeId) node.nodeId = pid;\n\n // Serialize the switch container (without children, without @switch directive).\n // nodeId is guaranteed set above, so data-pid is always emitted.\n const switchShell: PithyNode = {\n ...node,\n children: [],\n directives: stripSwitchDirective(node.directives),\n };\n const shellResult = serializeNode(switchShell, ctx);\n if (shellResult) varNames.push(shellResult.varName);\n warnElement(node, node.originalTagName ?? node.tagName ?? '');\n\n // Generate sub-factory for each @case/@default child\n const cases: SwitchDescriptor['cases'] = [];\n let dropped: string | undefined;\n for (let c = 0; c < (node.children ?? []).length; c++) {\n const caseNode = node.children![c];\n if (\n caseNode.type !== 'element' ||\n (caseNode.directives?.case === undefined && !isDefaultCase(caseNode))\n ) {\n for (const name of caseNode.loopConflicts ?? [])\n console.warn(\n `[pithy:aot] ${loopConflictMessage(caseNode.originalTagName ?? caseNode.tagName ?? '', name)}`\n );\n if (caseNode.type === 'element')\n dropped ??= `<${caseNode.originalTagName ?? caseNode.tagName}>`;\n else if (caseNode.type === 'slot') dropped ??= '<slot>';\n else if (caseNode.type === 'text' && caseNode.textContent?.trim())\n dropped ??= JSON.stringify(caseNode.textContent.trim());\n continue;\n }\n\n const caseHash = `${safeHash}_sw_${pid}_${c}`;\n const stripped = stripStructuralDirective(caseNode);\n if (caseNode.directives?.switch !== undefined)\n stripped.directives = {\n ...stripped.directives,\n switch: caseNode.directives.switch,\n };\n const sub = generateDomFactory([stripped], caseHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n\n const caseDesc: SwitchDescriptor['cases'][0] = {\n factory: sub.factoryName,\n };\n if (caseNode.directives?.case !== undefined)\n caseDesc.val = caseNode.directives.case;\n cases.push(caseDesc);\n }\n\n if (dropped)\n console.warn(\n `[pithy:aot] @switch renders only its @case/@default children; ${dropped} is dropped`\n );\n\n structuralDescriptors.push({\n t: 'switch',\n pid,\n expr: node.directives.switch,\n cases,\n });\n continue;\n }\n\n // ─── Text nodes ─────────────────────────────────────────────────\n if (node.type === 'text') {\n const result = serializeNode(node, ctx);\n if (result) varNames.push(result.varName);\n continue;\n }\n\n // ─── Slot nodes (content projection) ─────────────────────────────\n if (node.type === 'slot') {\n const slotName = node.slotName ?? '';\n const pid = node.nodeId ?? `_slot_${ctx.commentCount}`;\n // A factory is one render scope; only its first slot of a name gets content.\n const dup = structuralDescriptors.some(\n d => d.t === 'proj' && d.name === slotName\n );\n\n // Emit comment anchor for the slot\n const commentVar = `c${ctx.commentCount++}`;\n const anchor = dup ? `slot-dup:${pid}` : `slot:${slotName}`;\n ctx.lines.push(\n `const ${commentVar}=document.createComment('${escapeJS(anchor)}');`\n );\n varNames.push(commentVar);\n\n // Build projection descriptor\n const projDesc: ProjectionDescriptor = {\n t: 'proj',\n pid,\n name: slotName,\n };\n if (dup) projDesc.dup = true;\n\n // Generate sub-factory for fallback content if present\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n const fbHash = `${safeHash}_slot_${pid}`;\n // Roots of the fallback factory, so bare text binds at its root.\n const roots = node.fallbackChildren.map(child =>\n child.parentId === node.nodeId\n ? { ...child, parentId: undefined }\n : child\n );\n const sub = generateDomFactory(roots, fbHash, scopeId, {\n ...options,\n sub: true,\n });\n subFactoryCodeBlocks.push(sub.code);\n projDesc.fallback = sub.factoryName;\n }\n\n structuralDescriptors.push(projDesc);\n continue;\n }\n\n // ─── Regular element (no structural directive on THIS node) ──────\n // Serialize element shell (without children) via serializeNode,\n // then process children recursively with structural awareness.\n if (node.type === 'element') {\n const shell: PithyNode = { ...node, children: [] };\n const result = serializeNode(shell, ctx);\n if (!result) continue;\n\n const tag = node.originalTagName ?? node.tagName ?? '';\n for (const name of componentChildDirectives(node))\n console.warn(\n `[pithy:aot] ${componentChildDirectiveMessage(tag, name)}`\n );\n warnElement(node, tag);\n if (\n node.isComponent &&\n node.nodeId &&\n node.children?.length &&\n options.templateComponents?.has(tag)\n ) {\n const { children, anchorSlots } = asTemplateRoots(\n node.children,\n node.nodeId,\n tag\n );\n const sub = generateDomFactory(\n children,\n `${safeHash}_tpl_${node.nodeId}`,\n scopeId,\n { ...options, wrappable: true, anchorSlots }\n );\n subFactoryCodeBlocks.push(sub.code);\n childFactories.set(node.nodeId, sub.factoryName);\n varNames.push(result.varName);\n continue;\n }\n\n // Each slot mount renders and binds its content afresh, as dev does.\n if (node.isComponent && node.nodeId && node.children?.length) {\n const slots: Record<string, string> = Object.create(null);\n let n = 0;\n for (const [name, group] of groupSlots(\n node.children,\n node.nodeId,\n tag\n )) {\n const sub = generateDomFactory(\n group,\n `${safeHash}_cs_${node.nodeId}_${n++}`,\n scopeId,\n { ...options, sub: true }\n );\n subFactoryCodeBlocks.push(sub.code);\n slots[name] = sub.factoryName;\n }\n slotFactories.set(node.nodeId, slots);\n varNames.push(result.varName);\n continue;\n }\n\n // Recursively process children (handles nested structural directives)\n const leave = enterTemplate(node, result.varName, ctx);\n const childVarNames = processNodes(\n node.children ?? [],\n ctx,\n safeHash,\n scopeId,\n subFactoryCodeBlocks,\n structuralDescriptors,\n options,\n childFactories,\n slotFactories\n );\n\n leave();\n appendChildren(node, result.varName, childVarNames, ctx);\n\n varNames.push(result.varName);\n continue;\n }\n }\n\n return varNames;\n}\n\nfunction markAnchorSlot(\n ctx: SerializeContext,\n commentVar: string,\n slot: string | undefined\n): void {\n if (slot === undefined) return;\n ctx.lines.push(`${commentVar}.__pithyAnchorSlot='${escapeJS(slot)}';`);\n}\n\nconst BLANK = /^[ \\t\\n\\f\\r]*$/;\n\nfunction warnMixedChainSlots(\n nodes: PithyNode[],\n ownerTag: string,\n outcome: string\n): void {\n let chainSlot: string | undefined;\n let inChain = false;\n let chainWarned = false;\n for (const { directives: d } of nodes) {\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n if (d?.if !== undefined) {\n inChain = true;\n chainSlot = d.slot;\n chainWarned = false;\n } else if (!isBranch) {\n inChain = false;\n }\n if (isBranch && inChain && d.slot !== chainSlot && !chainWarned) {\n chainWarned = true;\n console.warn(\n `[pithy:aot] <${ownerTag}>: the branches of an @if chain carry different slots ` +\n `(${chainSlot ?? 'none'} and ${d.slot ?? 'none'}). ${outcome}`\n );\n }\n if (d?.else !== undefined) inChain = false;\n }\n}\n\n/** Groups a component's children by slot name, as `collectSlotMap` does. */\nfunction groupSlots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): Map<string, PithyNode[]> {\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'Each slot keeps only the branches that name it; a branch cut off from its @if is dropped.'\n );\n const groups = new Map<string, PithyNode[]>();\n for (const child of nodes) {\n const name = child.directives?.slot || '';\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const group = groups.get(name);\n if (group) group.push(root);\n else groups.set(name, [root]);\n }\n const blank = (n: PithyNode) =>\n n.type === 'text' && BLANK.test(n.textContent ?? '');\n const main = groups.get('');\n if (main) {\n let start = 0;\n let end = main.length;\n while (start < end && blank(main[start])) start++;\n while (end > start && blank(main[end - 1])) end--;\n if (start < end) groups.set('', main.slice(start, end));\n else groups.delete('');\n }\n return groups;\n}\n\nfunction asTemplateRoots(\n nodes: PithyNode[],\n ownerId: string,\n ownerTag: string\n): { children: PithyNode[]; anchorSlots: Map<string, string> } {\n const anchorSlots = new Map<string, string>();\n warnMixedChainSlots(\n nodes,\n ownerTag,\n 'The whole chain is placed by its first branch.'\n );\n\n const children = nodes.map(child => {\n const root =\n child.parentId === ownerId ? { ...child, parentId: undefined } : child;\n const d = root.directives;\n const isHead = d?.if !== undefined;\n const isBranch = d?.elseIf !== undefined || d?.else !== undefined;\n const isLoop = d?.for !== undefined;\n\n if (!d || d.slot === undefined || !(isHead || isBranch || isLoop))\n return root;\n\n if (root.nodeId && (isHead || isLoop)) anchorSlots.set(root.nodeId, d.slot);\n const { slot: _slot, ...directives } = d;\n return { ...root, directives };\n });\n\n return { children, anchorSlots };\n}\n\n/**\n * Remove the `switch` field from a ParsedDirectives object.\n * Used to serialize the switch container element without the @switch directive\n * (since the directive is captured in the SwitchDescriptor instead).\n */\nfunction stripSwitchDirective(\n d: NonNullable<PithyNode['directives']>\n): PithyNode['directives'] {\n const { switch: _switch, ...rest } = d;\n return Object.keys(rest).length > 0\n ? (rest as PithyNode['directives'])\n : undefined;\n}\n\n/** Build-time copies of dev's `[slot]`, shared-slot and SVG `@bind` warnings. */\nfunction warnElement(node: PithyNode, tag: string): void {\n const d = node.directives;\n // A component's name says nothing about the namespace of what it renders.\n if (!node.isComponent) {\n if (d?.bind !== undefined && isSvgNode(node))\n console.warn(`[pithy:aot] ${svgBindMessage(node.tagName ?? tag)}`);\n return;\n }\n if (d?.bound?.slot !== undefined)\n console.warn(`[pithy:aot] ${boundSlotMessage(tag)}`);\n for (const slot of sharedSlots(node.children ?? []))\n console.warn(`[pithy:aot] ${sharedSlotMessage(tag, slot)}`);\n}\n\n/** `track` belongs to the `@for`, not to a component's props (BUG-110). */\nfunction withoutTrackProp(node: PithyNode): PithyNode {\n if (!node.isComponent || node.attrs?.track === undefined) return node;\n const { track: _track, ...attrs } = node.attrs;\n return { ...node, attrs };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"babelPlugin.d.ts","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAGF,OAAO,KAAK,EAAY,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAGL,KAAK,kBAAkB,EACxB,MAAM,0BAA0B,CAAC;AAWlC,UAAU,WAAY,SAAQ,UAAU;IACtC,mBAAmB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAClC;AAyJD;;GAEG;AACH,mKAAmK;AACnK,MAAM,WAAW,uBAAuB;IACtC,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,uDAAuD;IACvD,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,oHAAoH;IACpH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,sFAAsF;IACtF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;CAChD;AAED;;;;GAIG;AACH,yJAAyJ;AACzJ,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,UAAU,GAAG,SAAS,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,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J;AACzJ,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,UAAU,GAAG,SAAS,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,2DAA2D;IAC3D,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,gFAAgF;IAChF,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,yDAAyD;IACzD,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,eAAe;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC;CACjB;AAoBD;;;;;;;GAOG;AACH,wLAAwL;AACxL,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,OAAO,CAAC,EAAE,uBAAuB,GAChC,SAAS,CAAC,WAAW,CAAC,CA0uBxB"}
@@ -83,6 +83,62 @@ function scopeStatements(block) {
83
83
  return block.cases.flatMap(c => c.consequent);
84
84
  return [];
85
85
  }
86
+ function afterLeadingImports(body, from) {
87
+ let index = from;
88
+ while (index < body.length &&
89
+ (t.isImportDeclaration(body[index]) || isTypeOnlyStatement(body[index]))) {
90
+ index++;
91
+ }
92
+ return index;
93
+ }
94
+ function isTypeOnlyStatement(stmt) {
95
+ if (t.isExportNamedDeclaration(stmt)) {
96
+ if (stmt.exportKind === 'type')
97
+ return true;
98
+ return stmt.declaration ? isTypeOnlyStatement(stmt.declaration) : false;
99
+ }
100
+ if (t.isExportDefaultDeclaration(stmt)) {
101
+ return t.isTSInterfaceDeclaration(stmt.declaration);
102
+ }
103
+ return (t.isTSTypeAliasDeclaration(stmt) ||
104
+ t.isTSInterfaceDeclaration(stmt) ||
105
+ t.isTSDeclareFunction(stmt) ||
106
+ ('declare' in stmt && !!stmt.declare) ||
107
+ (t.isTSImportEqualsDeclaration(stmt) && stmt.importKind === 'type'));
108
+ }
109
+ function hasValueBinding(path, name) {
110
+ if (!path.scope.hasBinding(name))
111
+ return false;
112
+ const binding = path.scope.getBinding(name);
113
+ if (!binding)
114
+ return true;
115
+ const { node, parent } = binding.path;
116
+ return !((t.isImportDeclaration(parent) && parent.importKind === 'type') ||
117
+ (t.isImportSpecifier(node) && node.importKind === 'type') ||
118
+ (t.isTSImportEqualsDeclaration(node) && node.importKind === 'type'));
119
+ }
120
+ function isInstantiated(decl) {
121
+ if (!t.isTSModuleBlock(decl.body))
122
+ return true;
123
+ return decl.body.body.some(stmt => {
124
+ if (t.isExportNamedDeclaration(stmt)) {
125
+ const inner = stmt.declaration;
126
+ if (!inner)
127
+ return true;
128
+ if (t.isTSTypeAliasDeclaration(inner) ||
129
+ t.isTSInterfaceDeclaration(inner))
130
+ return false;
131
+ return t.isTSModuleDeclaration(inner)
132
+ ? !inner.declare && isInstantiated(inner)
133
+ : true;
134
+ }
135
+ if (t.isTSImportEqualsDeclaration(stmt))
136
+ return stmt.isExport;
137
+ if (t.isTSModuleDeclaration(stmt))
138
+ return !stmt.declare && isInstantiated(stmt);
139
+ return !isTypeOnlyStatement(stmt);
140
+ });
141
+ }
86
142
  function declaredTsValueNames(path) {
87
143
  const names = new Set();
88
144
  for (let scope = path.scope; scope; scope = scope.parent) {
@@ -94,7 +150,9 @@ function declaredTsValueNames(path) {
94
150
  ? stmt.declaration
95
151
  : stmt;
96
152
  if ((t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) &&
97
- t.isIdentifier(decl.id)) {
153
+ t.isIdentifier(decl.id) &&
154
+ !isTypeOnlyStatement(decl) &&
155
+ !(t.isTSModuleDeclaration(decl) && !isInstantiated(decl))) {
98
156
  declared.add(decl.id.name);
99
157
  }
100
158
  }
@@ -270,10 +328,7 @@ export default function pithyBabelPlugin(options) {
270
328
  t.isStringLiteral(body[importInsertIndex].expression)) {
271
329
  importInsertIndex++;
272
330
  }
273
- while (importInsertIndex < body.length &&
274
- t.isImportDeclaration(body[importInsertIndex])) {
275
- importInsertIndex++;
276
- }
331
+ importInsertIndex = afterLeadingImports(body, importInsertIndex);
277
332
  path.node.body.splice(importInsertIndex, 0, importDecl);
278
333
  }
279
334
  }
@@ -302,10 +357,7 @@ export default function pithyBabelPlugin(options) {
302
357
  t.isStringLiteral(bodyForFactory[insertIndex].expression)) {
303
358
  insertIndex++;
304
359
  }
305
- while (insertIndex < bodyForFactory.length &&
306
- t.isImportDeclaration(bodyForFactory[insertIndex])) {
307
- insertIndex++;
308
- }
360
+ insertIndex = afterLeadingImports(bodyForFactory, insertIndex);
309
361
  path.node.body.splice(insertIndex, 0, ...statementsToInject);
310
362
  // 3. Strip unused `html` import when all html`` tags were AOT-compiled.
311
363
  // This enables Rollup to tree-shake html() → parseHtml → parse5 entirely.
@@ -347,9 +399,8 @@ export default function pithyBabelPlugin(options) {
347
399
  // When we detected a @pithyjs/core html import, match its local name (handles aliases).
348
400
  // When no @pithyjs/core import was found, fall back to matching literal "html" (bare usage),
349
401
  // but skip if "html" is known to come from a foreign package.
350
- const tagName = t.isIdentifier(path.node.tag)
351
- ? path.node.tag.name
352
- : null;
402
+ const tag = unwrapTs(path.node.tag);
403
+ const tagName = t.isIdentifier(tag) ? tag.name : null;
353
404
  if (!tagName)
354
405
  return;
355
406
  if (foreignHtmlLocalNames.has(tagName))
@@ -400,13 +451,14 @@ export default function pithyBabelPlugin(options) {
400
451
  CallExpression(path) {
401
452
  if (rewrittenCalls.has(path.node))
402
453
  return;
403
- const callee = path.node.callee;
454
+ const callee = unwrapTs(path.node.callee);
404
455
  if (!t.isIdentifier(callee) ||
405
456
  !pithyCoreHtmlLocalNames.has(callee.name))
406
457
  return;
407
458
  if (path.scope.getBinding(callee.name)?.kind !== 'module')
408
459
  return;
409
- const [templateArg, contextArg, cssArg] = path.node.arguments;
460
+ const [rawTemplateArg, contextArg, cssArg] = path.node.arguments;
461
+ const templateArg = unwrapTs(rawTemplateArg);
410
462
  const templateStr = t.isStringLiteral(templateArg)
411
463
  ? templateArg.value
412
464
  : t.isTemplateLiteral(templateArg) &&
@@ -505,14 +557,15 @@ export default function pithyBabelPlugin(options) {
505
557
  continue;
506
558
  const value = unwrapTs(prop.value);
507
559
  if (!t.isNewExpression(value) ||
508
- !t.isIdentifier(value.callee, { name: 'Set' }))
560
+ !t.isIdentifier(unwrapTs(value.callee), { name: 'Set' }))
509
561
  continue;
510
562
  const list = unwrapTs(value.arguments[0]);
511
563
  if (!t.isArrayExpression(list))
512
564
  continue;
513
565
  for (const element of list.elements) {
514
- if (t.isStringLiteral(element))
515
- names.add(element.value);
566
+ const entry = unwrapTs(element);
567
+ if (t.isStringLiteral(entry))
568
+ names.add(entry.value);
516
569
  }
517
570
  }
518
571
  return names;
@@ -537,10 +590,12 @@ export default function pithyBabelPlugin(options) {
537
590
  if (reference.findParent(p => p.isTSTypeQuery()))
538
591
  return true;
539
592
  const call = reference.findParent(p => unwrapTs(p.node) !== reference.node)?.node;
540
- return (t.isCallExpression(call) &&
541
- t.isIdentifier(call.callee) &&
542
- pithyCoreHtmlLocalNames.has(call.callee.name) &&
543
- reference.scope.getBinding(call.callee.name)?.kind === 'module' &&
593
+ if (!t.isCallExpression(call))
594
+ return false;
595
+ const callee = unwrapTs(call.callee);
596
+ return (t.isIdentifier(callee) &&
597
+ pithyCoreHtmlLocalNames.has(callee.name) &&
598
+ reference.scope.getBinding(callee.name)?.kind === 'module' &&
544
599
  unwrapTs(call.arguments[1]) === reference.node);
545
600
  });
546
601
  contextsInHtmlCalls.set(binding, stays);
@@ -580,7 +635,7 @@ export default function pithyBabelPlugin(options) {
580
635
  ? attrReports
581
636
  : collectIdentifiers(reportTrees, true).attrReports.filter(({ attr, value }) => !attr.includes(TEMPLATE_HOLE) && !value.includes(TEMPLATE_HOLE));
582
637
  for (const report of reports) {
583
- warnOnStringLikeComponentAttr(path, report, name => path.scope.hasBinding(name) || tsNames.has(name), quoteForTemplateSource, 'no binding in this module');
638
+ warnOnStringLikeComponentAttr(path, report, name => hasValueBinding(path, name) || tsNames.has(name), quoteForTemplateSource, 'no binding in this module');
584
639
  }
585
640
  // Compute which imported identifiers are actually used as components
586
641
  const usedComponents = new Set();
@@ -617,7 +672,7 @@ export default function pithyBabelPlugin(options) {
617
672
  function quoteForCallForm(path, templateArg) {
618
673
  if (sourceFile(path)?.endsWith('.pithy'))
619
674
  return quoteForHtmlSource;
620
- const raw = templateArg.extra?.raw;
675
+ const raw = templateArg?.extra?.raw;
621
676
  if (typeof raw !== 'string')
622
677
  return quoteForTemplateSource;
623
678
  return raw.startsWith("'")
@@ -702,6 +757,7 @@ export default function pithyBabelPlugin(options) {
702
757
  // Call AOT codegen
703
758
  const aotResult = generateDomFactory(trees, hash, scopeId, {
704
759
  templateComponents,
760
+ declareSlots: true,
705
761
  });
706
762
  // Only increment counter after successful codegen — if codegen
707
763
  // throws, the hash slot stays available for the next attempt.
@@ -1 +1 @@
1
- {"version":3,"file":"babelPlugin.js","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EACL,sBAAsB,GAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,aAAa,EACb,4BAA4B,EAE5B,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMnD,SAAS,eAAe,CAAC,IAAkB;IACzC,IAAI,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,I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,wBAAwB,EAAE,CAAC;YAE3B,IAAI,CAAC,WAAW,CACd,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CACjE,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,iBAAiB,CACf,IAAI,EACJ,iCAAiC;gBAC/B,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CACrD,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.babel.html-context-plugin\",\n \"title\": \"Babel HTML Context Injection Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel plugin that injects compilation context into html`…` tagged template literals and AOT-compiles both the tagged form and literal html(template, context) calls, with scope ID generation.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"babelPluginAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport * as t from '@babel/types';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport { parseFragment } from 'parse5';\nimport {\n extractUsedIdentifiers,\n type ComponentAttrReport,\n type ComponentScopesMap,\n} from './extractUsedIdentifiers';\nimport {\n parseTemplate,\n warnOnLowercaseComponentTags,\n type PithyNode,\n warnsOnComponentProp,\n} from '@pithyjs/compiler';\nimport { createHash } from 'crypto';\nimport { parse as babelParse } from '@babel/parser';\nimport { generateDomFactory } from '../aotCodegen';\n\ninterface PluginState extends PluginPass {\n importedIdentifiers: Set<string>;\n}\n\nfunction stringLikeNames(node: t.Expression): string[] | null {\n if (t.isIdentifier(node)) return [node.name];\n if (t.isNumericLiteral(node)) return [];\n if (\n t.isBinaryExpression(node) &&\n (node.operator === '-' || node.operator === '/')\n ) {\n const left = t.isExpression(node.left) ? stringLikeNames(node.left) : null;\n const right = stringLikeNames(node.right);\n return left && right ? [...left, ...right] : null;\n }\n if (\n t.isNewExpression(node) &&\n t.isIdentifier(node.callee) &&\n node.arguments.length === 0\n ) {\n return [node.callee.name];\n }\n if (\n t.isUnaryExpression(node) &&\n (node.operator === 'typeof' || node.operator === 'void')\n ) {\n return stringLikeNames(node.argument);\n }\n if (t.isSequenceExpression(node)) {\n const parts = node.expressions.map(stringLikeNames);\n return parts.every(p => p !== null) ? parts.flat() : null;\n }\n if (t.isMemberExpression(node)) {\n let root: t.Expression = node;\n while (\n t.isMemberExpression(root) &&\n !root.computed &&\n t.isIdentifier(root.property)\n ) {\n root = root.object;\n }\n if (!t.isIdentifier(root)) return null;\n return HOST_ROOTS.has(root.name) ? [] : [root.name];\n }\n return null;\n}\n\nconst HOST_ROOTS = new Set([\n 'window',\n 'document',\n 'location',\n 'navigator',\n 'history',\n 'localStorage',\n 'sessionStorage',\n 'console',\n 'performance',\n 'crypto',\n 'screen',\n]);\n\nconst typeScopedNames = new WeakMap<t.Node, Set<string>>();\n\nfunction scopeStatements(block: t.Node): t.Statement[] {\n if (\n t.isProgram(block) ||\n t.isBlockStatement(block) ||\n t.isStaticBlock(block) ||\n t.isTSModuleBlock(block)\n )\n return block.body;\n if (t.isFunction(block) && t.isBlockStatement(block.body))\n return block.body.body;\n if (t.isSwitchStatement(block)) return block.cases.flatMap(c => c.consequent);\n return [];\n}\n\nfunction declaredTsValueNames(path: NodePath): Set<string> {\n const names = new Set<string>();\n for (let scope = path.scope; scope; scope = scope.parent) {\n let declared = typeScopedNames.get(scope.block);\n if (!declared) {\n declared = new Set();\n for (const stmt of scopeStatements(scope.block)) {\n const decl =\n t.isExportNamedDeclaration(stmt) && stmt.declaration\n ? stmt.declaration\n : stmt;\n if (\n (t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) &&\n t.isIdentifier(decl.id)\n ) {\n declared.add(decl.id.name);\n }\n }\n typeScopedNames.set(scope.block, declared);\n }\n declared.forEach(name => names.add(name));\n }\n return names;\n}\n\nfunction quoteForHtmlSource(value: string): string {\n return `\"'${value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')}'\"`;\n}\n\nfunction quoteForDoubleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/[\\\\\"]/g, '\\\\$&');\n}\n\nfunction quoteForSingleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nfunction quoteForTemplateSource(value: string): string {\n return quoteForHtmlSource(value)\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/`/g, '\\\\`')\n .replace(/\\$\\{/g, '\\\\${');\n}\n\n// A private-use character: not valid in an identifier, so it cannot be collected as a name.\nconst TEMPLATE_HOLE = '';\n\nconst SLOT_DUP_ERROR =\n '[pithy] This module was compiled for a newer @pithyjs/core: upgrade @pithyjs/core to match @pithyjs/vite-plugin.';\n\n// A serialized `dup` descriptor. Template text cannot match: codegen escapes its quotes.\nconst DUP_SLOT_DESCRIPTOR =\n /\\{t:'proj',pid:'[^'\\\\]*',name:'(?:[^'\\\\]|\\\\.)*'(?:,fallback:\\w+)?,dup:__slotDup\\}/;\n\nfunction slotDupCheck(): t.Statement {\n return babelParse(\n `if (__slotDup !== true) throw new Error(${JSON.stringify(SLOT_DUP_ERROR)});`,\n { sourceType: 'module' }\n ).program.body[0];\n}\n\ntype DeclaredName = (name: string) => boolean;\n\n// Names that should never be hoisted into ctx even if seen in expressions\nconst RESERVED_LOCAL_EVENT_NAMES = new Set([\n '$event',\n 'event',\n 'ev',\n 'e',\n 'evt',\n]);\n\n/**\n * Configuration options for the Pithy Babel HTML context injection plugin.\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"PithyBabelPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface PithyBabelPluginOptions\"} */\nexport interface PithyBabelPluginOptions {\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: false. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n /** File path for deterministic scope ID generation (typically the Vite module id). */\n filename?: string;\n /** Receives each template finding. Default: `console.warn` of its `message`. */\n onFinding?: (finding: TemplateFinding) => void;\n}\n\n/**\n * A component attribute that will not reach the component as the author meant:\n * its value does not parse (`unparsed`, the attribute is dropped), or it reads\n * names this module does not bind (`unbound`).\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"TemplateFinding\",\"stability\":\"experimental\",\"signature\":\"interface TemplateFinding\"} */\nexport interface TemplateFinding {\n kind: 'unparsed' | 'unbound';\n tag: string;\n attr: string;\n value: string;\n /** The names read with no binding; empty for `unparsed`. */\n unbound: string[];\n /** The parser's error for `unparsed`; `null` otherwise. */\n error: string | null;\n /** The attribute quoted as a string literal, when that is the likely intent. */\n fix: string | null;\n file: string | null;\n /** 1-based, of the template expression in the module. */\n line: number | null;\n /** 1-based. */\n column: number | null;\n /** The text the plugin warns with. */\n message: string;\n}\n\n/**\n * Generate a deterministic scope ID from a file path.\n * Uses base64url-safe encoding (only [A-Za-z0-9_-]) since the ID is\n * interpolated into attribute names like data-scope-{id}.\n * Note: pithyPlugin uses raw base64 slicing — the two will diverge for\n * paths containing characters that produce +/= in base64.\n */\nfunction generateScopeId(filepath: string): string {\n const base64 = Buffer.from(filepath).toString('base64');\n // Convert to base64url-safe variant: only [A-Za-z0-9_-] allowed\n // (scopeId is interpolated into attribute names like data-scope-{id})\n const safe = base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n return 'pithy-' + safe.slice(0, 6);\n}\n\n/**\n * Babel plugin that transforms `html\\`...\\`` tagged template expressions.\n * In non-AOT mode, rewrites to `html(str, ctx)`. In AOT mode, pre-compiles\n * both the tagged form and `html(literal, context)` calls to a DOM factory\n * function eliminating runtime HTML parsing.\n * @param options - Plugin configuration (AOT mode, component scopes, filename)\n * @returns Babel plugin object\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"pithyBabelPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBabelPluginOptions) => PluginObj<PluginState>\"} */\nexport default function pithyBabelPlugin(\n options?: PithyBabelPluginOptions\n): PluginObj<PluginState> {\n const componentScopes = options?.componentScopes;\n const enableAot = options?.aot ?? false;\n const templateComponents = new Set(Object.keys(componentScopes ?? {}));\n let importedIdentifiers: Set<string>;\n\n // AOT state — accumulated per file, injected in Program.exit\n let aotFactoryBlocks: string[];\n let aotNeedsApplyBindings: boolean;\n let aotNeedsSlotDup: boolean;\n let aotHashCounter: Map<string, number>;\n let aotDisabledByCollision: boolean;\n // Track html`` usage for dead import stripping\n let totalHtmlTagsFound: number;\n let totalHtmlTagsAotCompiled: number;\n // Local names of html imported from @pithyjs/core (handles aliased imports like `import { html as h }`)\n let pithyCoreHtmlLocalNames: Set<string>;\n // Set of local names of html imported from non-@pithyjs/core packages (e.g., lit)\n let foreignHtmlLocalNames: Set<string>;\n let rewrittenCalls: WeakSet<t.Node>;\n let contextsInHtmlCalls: WeakMap<object, boolean>;\n\n return {\n name: 'pithy:html-context-inject',\n\n pre() {\n importedIdentifiers = new Set<string>();\n aotFactoryBlocks = [];\n aotNeedsApplyBindings = false;\n aotNeedsSlotDup = false;\n aotHashCounter = new Map();\n aotDisabledByCollision = false;\n totalHtmlTagsFound = 0;\n totalHtmlTagsAotCompiled = 0;\n pithyCoreHtmlLocalNames = new Set();\n foreignHtmlLocalNames = new Set();\n rewrittenCalls = new WeakSet();\n contextsInHtmlCalls = new WeakMap();\n },\n\n visitor: {\n Program: {\n enter(path, _state) {\n for (const node of path.node.body) {\n if (t.isImportDeclaration(node) && node.importKind !== 'type') {\n for (const spec of node.specifiers) {\n // Skip type-only specifiers — they don't exist at runtime\n if (t.isImportSpecifier(spec) && spec.importKind === 'type')\n continue;\n if (\n t.isImportSpecifier(spec) ||\n t.isImportDefaultSpecifier(spec) ||\n t.isImportNamespaceSpecifier(spec)\n ) {\n importedIdentifiers.add(spec.local.name);\n }\n // Detect html imports and track their source package\n if (\n t.isImportSpecifier(spec) &&\n spec.importKind !== 'type' &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === 'html'\n ) {\n if (node.source.value === '@pithyjs/core') {\n pithyCoreHtmlLocalNames.add(spec.local.name);\n } else {\n foreignHtmlLocalNames.add(spec.local.name);\n }\n }\n }\n }\n }\n\n // Check for __applyBindings binding collision early — if a user-defined\n // binding exists, AOT factories would reference the wrong symbol.\n for (const name of ['__applyBindings', '__slotDup']) {\n if (enableAot && path.scope.hasBinding(name)) {\n aotDisabledByCollision = true;\n console.warn(\n `[pithy:aot] Disabling AOT — existing binding \"${name}\" ` +\n `would shadow the runtime import.`\n );\n break;\n }\n }\n },\n\n exit(path) {\n if (aotFactoryBlocks.length === 0) return;\n\n // 1. Add __applyBindings import (only if needed)\n if (aotNeedsApplyBindings) {\n const imported = (name: string) =>\n path.node.body.some(\n stmt =>\n t.isImportDeclaration(stmt) &&\n stmt.importKind !== 'type' &&\n stmt.source.value === '@pithyjs/core/runtime/applyBindings' &&\n stmt.specifiers.some(\n s =>\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.local) &&\n s.local.name === name\n )\n );\n const missing = ['__applyBindings'];\n if (aotNeedsSlotDup) missing.push('__slotDup');\n const names = missing.filter(name => !imported(name));\n\n if (names.length) {\n const importDecl = t.importDeclaration(\n names.map(name =>\n t.importSpecifier(t.identifier(name), t.identifier(name))\n ),\n t.stringLiteral('@pithyjs/core/runtime/applyBindings')\n );\n // Insert after directive prologues and existing imports.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let importInsertIndex = 0;\n const body = path.node.body;\n while (\n importInsertIndex < body.length &&\n t.isExpressionStatement(body[importInsertIndex]) &&\n t.isStringLiteral(\n (body[importInsertIndex] as t.ExpressionStatement).expression\n )\n ) {\n importInsertIndex++;\n }\n while (\n importInsertIndex < body.length &&\n t.isImportDeclaration(body[importInsertIndex])\n ) {\n importInsertIndex++;\n }\n path.node.body.splice(importInsertIndex, 0, importDecl);\n }\n }\n\n // 2. Parse factory code blocks into AST and inject after last import\n const statementsToInject: t.Program['body'] = [];\n // Vite's SSR runner reads a missing export of an inlined module as undefined.\n if (aotNeedsSlotDup) statementsToInject.push(slotDupCheck());\n\n for (const block of aotFactoryBlocks) {\n const ast = babelParse(block, {\n sourceType: 'module',\n plugins: [],\n });\n if (ast.program?.body) {\n statementsToInject.push(...ast.program.body);\n }\n }\n\n if (statementsToInject.length === 0) return;\n\n // Find insertion point: after directive prologues and import declarations.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let insertIndex = 0;\n const bodyForFactory = path.node.body;\n while (\n insertIndex < bodyForFactory.length &&\n t.isExpressionStatement(bodyForFactory[insertIndex]) &&\n t.isStringLiteral(\n (bodyForFactory[insertIndex] as t.ExpressionStatement).expression\n )\n ) {\n insertIndex++;\n }\n while (\n insertIndex < bodyForFactory.length &&\n t.isImportDeclaration(bodyForFactory[insertIndex])\n ) {\n insertIndex++;\n }\n\n path.node.body.splice(insertIndex, 0, ...statementsToInject);\n\n // 3. Strip unused `html` import when all html`` tags were AOT-compiled.\n // This enables Rollup to tree-shake html() → parseHtml → parse5 entirely.\n // Safety: use Babel binding analysis (scope.crawl + getBinding) to verify\n // the html identifier has no remaining references after AOT transforms.\n // This covers all non-tagged-template usages: html(), const t = html, etc.\n if (\n enableAot &&\n totalHtmlTagsFound > 0 &&\n totalHtmlTagsFound === totalHtmlTagsAotCompiled &&\n pithyCoreHtmlLocalNames.size > 0\n ) {\n // Re-crawl scope to get accurate reference counts after AOT transforms\n path.scope.crawl();\n const unreferenced = new Set(\n [...pithyCoreHtmlLocalNames].filter(\n name => !(path.scope.getBinding(name)?.references ?? 0)\n )\n );\n\n for (let i = path.node.body.length - 1; i >= 0; i--) {\n const stmt = path.node.body[i];\n if (!t.isImportDeclaration(stmt) || stmt.importKind === 'type')\n continue;\n\n // Only strip html from @pithyjs/core — never touch other packages (e.g., lit)\n if (stmt.source.value !== '@pithyjs/core') continue;\n\n const kept = stmt.specifiers.filter(\n s =>\n !(\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.imported) &&\n s.imported.name === 'html' &&\n unreferenced.has(s.local.name)\n )\n );\n if (kept.length === stmt.specifiers.length) continue;\n stmt.specifiers = kept;\n // If no specifiers remain, remove the entire import declaration\n if (kept.length === 0) {\n path.node.body.splice(i, 1);\n }\n }\n }\n },\n },\n\n TaggedTemplateExpression(path) {\n // Only transform html`` from @pithyjs/core — leave other packages' html (e.g., lit) untouched.\n // When we detected a @pithyjs/core html import, match its local name (handles aliases).\n // When no @pithyjs/core import was found, fall back to matching literal \"html\" (bare usage),\n // but skip if \"html\" is known to come from a foreign package.\n const tagName = t.isIdentifier(path.node.tag)\n ? path.node.tag.name\n : null;\n if (!tagName) return;\n if (foreignHtmlLocalNames.has(tagName)) return;\n if (\n pithyCoreHtmlLocalNames.size > 0\n ? !pithyCoreHtmlLocalNames.has(tagName)\n : tagName !== 'html'\n )\n return;\n\n totalHtmlTagsFound++;\n\n const quasi = path.node.quasi;\n const templateStr = quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('');\n\n // Warn about lowercase component tags used for imported components\n if (importedIdentifiers.size > 0) {\n warnOnLowercaseComponentTags(templateStr, importedIdentifiers);\n }\n\n const trees = parseComponentTemplate(templateStr, importedIdentifiers);\n if (trees.length === 0) return;\n\n const reportTrees =\n quasi.expressions.length === 0\n ? trees\n : parseComponentTemplate(\n quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join(TEMPLATE_HOLE),\n importedIdentifiers,\n true\n );\n const contextObject = buildContextObject(path, trees, reportTrees);\n\n // ── AOT codegen path ──────────────────────────────────────────────\n if (enableAot && !aotDisabledByCollision) {\n // Templates with ${expr} expressions can't be AOT-compiled safely.\n // PithyJS uses {{ expr }} syntax, not ${}, so this is an edge case guard.\n if (quasi.expressions.length > 0) {\n // Fall through to non-AOT path below\n reportJitFallback(\n path,\n `Template contains \\${expr} expressions — skipping AOT. ` +\n `Refactor to {{ expr }} syntax for AOT compilation.`\n );\n } else if (emitFactory(path, trees, templateStr, contextObject)) {\n return;\n }\n }\n\n // ── Non-AOT path (original behavior) ─────────────────────────────\n const runtimeCall = t.callExpression(path.node.tag, [\n quasi,\n contextObject,\n ]);\n rewrittenCalls.add(runtimeCall);\n path.replaceWith(runtimeCall);\n },\n\n CallExpression(path) {\n if (rewrittenCalls.has(path.node)) return;\n const callee = path.node.callee;\n if (\n !t.isIdentifier(callee) ||\n !pithyCoreHtmlLocalNames.has(callee.name)\n )\n return;\n if (path.scope.getBinding(callee.name)?.kind !== 'module') return;\n\n const [templateArg, contextArg, cssArg] = path.node.arguments;\n const templateStr = t.isStringLiteral(templateArg)\n ? templateArg.value\n : t.isTemplateLiteral(templateArg) &&\n templateArg.expressions.length === 0\n ? templateArg.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('')\n : null;\n const context = contextLiteral(path, contextArg);\n const componentNames = declaredComponents(context);\n\n if (templateStr !== null) {\n reportCallFormAttrs(\n path,\n templateStr,\n componentNames,\n contextStaysInHtmlCalls(path, contextArg) ? context : null,\n quoteForCallForm(path, templateArg)\n );\n }\n\n if (!enableAot || aotDisabledByCollision) return;\n\n totalHtmlTagsFound++;\n\n if (templateStr === null) {\n reportJitFallback(\n path,\n `html() is called with a template that is not a string literal — skipping AOT. ` +\n `Pass the template as a literal.`\n );\n return;\n }\n\n if (cssArg !== undefined && !isAbsentCss(cssArg)) {\n reportJitFallback(\n path,\n `html() is called with a css argument — skipping AOT.`\n );\n return;\n }\n\n if (contextArg && !context) {\n reportJitFallback(\n path,\n `html() is called with a second argument that is not an object literal, so it may be a css string or a context the build cannot read — skipping AOT. ` +\n `Pass the context as an object literal, inline or bound by const.`\n );\n return;\n }\n\n try {\n warnOnLowercaseComponentTags(templateStr, componentNames);\n } catch (err) {\n reportJitFallback(\n path,\n `html() template has a tag that cannot be resolved to a component at build time — skipping AOT. ` +\n `Name the component in a literal \\`__importedIdentifiers: new Set([...])\\` in the context. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return;\n }\n\n emitFactory(\n path,\n parseComponentTemplate(templateStr, componentNames),\n templateStr,\n t.isExpression(contextArg) ? contextArg : t.objectExpression([])\n );\n },\n },\n };\n\n function unwrapTs(node: t.Node | null | undefined): t.Node | null {\n let current = node ?? null;\n while (\n t.isTSAsExpression(current) ||\n t.isTSSatisfiesExpression(current) ||\n t.isTSTypeAssertion(current) ||\n t.isTSNonNullExpression(current) ||\n t.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n }\n\n function isAbsentCss(cssArg: t.Node): boolean {\n const css = unwrapTs(cssArg);\n return (\n t.isIdentifier(css, { name: 'undefined' }) ||\n t.isNullLiteral(css) ||\n t.isStringLiteral(css, { value: '' }) ||\n t.isUnaryExpression(css, { operator: 'void' })\n );\n }\n\n function contextLiteral(\n path: NodePath,\n contextArg: t.Node | undefined\n ): t.ObjectExpression | null {\n const arg = unwrapTs(contextArg);\n if (t.isObjectExpression(arg)) return arg;\n if (!t.isIdentifier(arg)) return null;\n const binding = path.scope.getBinding(arg.name);\n if (binding?.kind !== 'const' || !binding.path.isVariableDeclarator())\n return null;\n if (!t.isIdentifier(binding.path.node.id)) return null;\n const init = unwrapTs(binding.path.node.init);\n return t.isObjectExpression(init) ? init : null;\n }\n\n function declaredComponents(literal: t.ObjectExpression | null): Set<string> {\n const names = new Set<string>();\n if (!literal) return names;\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop)) {\n names.clear();\n continue;\n }\n if (prop.computed) continue;\n const key = t.isIdentifier(prop.key)\n ? prop.key.name\n : t.isStringLiteral(prop.key)\n ? prop.key.value\n : null;\n if (key !== '__importedIdentifiers') continue;\n names.clear();\n if (!t.isObjectProperty(prop)) continue;\n const value = unwrapTs(prop.value);\n if (\n !t.isNewExpression(value) ||\n !t.isIdentifier(value.callee, { name: 'Set' })\n )\n continue;\n const list = unwrapTs(value.arguments[0]);\n if (!t.isArrayExpression(list)) continue;\n for (const element of list.elements) {\n if (t.isStringLiteral(element)) names.add(element.value);\n }\n }\n return names;\n }\n\n function sourceFile(path: NodePath): string | undefined {\n return (\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename\n );\n }\n\n function contextStaysInHtmlCalls(\n path: NodePath,\n contextArg: t.Node | undefined\n ): boolean {\n const arg = unwrapTs(contextArg);\n if (!t.isIdentifier(arg)) return true;\n const binding = path.scope.getBinding(arg.name);\n if (!binding) return true;\n // AOT rewrites earlier html() calls into factory calls that receive the\n // same context, so classify the references once, before any rewrite.\n let stays = contextsInHtmlCalls.get(binding);\n if (stays === undefined) {\n stays = binding.referencePaths.every(reference => {\n if (reference.findParent(p => p.isTSTypeQuery())) return true;\n const call = reference.findParent(\n p => unwrapTs(p.node) !== reference.node\n )?.node;\n return (\n t.isCallExpression(call) &&\n t.isIdentifier(call.callee) &&\n pithyCoreHtmlLocalNames.has(call.callee.name) &&\n reference.scope.getBinding(call.callee.name)?.kind === 'module' &&\n unwrapTs(call.arguments[1]) === reference.node\n );\n });\n contextsInHtmlCalls.set(binding, stays);\n }\n return stays;\n }\n\n function contextKeys(literal: t.ObjectExpression | null): Set<string> | null {\n if (!literal) return null;\n const keys = new Set<string>();\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop) || prop.computed) return null;\n if (t.isIdentifier(prop.key)) keys.add(prop.key.name);\n else if (t.isStringLiteral(prop.key)) keys.add(prop.key.value);\n }\n return keys;\n }\n\n function parseComponentTemplate(\n templateStr: string,\n componentNames: Set<string>,\n quiet = false\n ): PithyNode[] {\n // `importedIdentifiers` is what makes component tags components at all;\n // `withSource: false` keeps interpolation scanning on parse5's decoded\n // text, because codegen locates interpolations with indexOf(interp.raw)\n // against decoded textContent and a raw source slice would carry entities.\n return parseTemplate(templateStr, parseFragment, {\n importedIdentifiers: componentNames,\n withSource: false,\n quiet,\n }).nodes;\n }\n\n function buildContextObject(\n path: NodePath,\n trees: PithyNode[],\n reportTrees: PithyNode[]\n ): t.ObjectExpression {\n // Collect identifiers referenced by expressions in the template\n const { usedIdentifiers, attrReports } = collectIdentifiers(trees);\n\n const tsNames = declaredTsValueNames(path);\n const reports =\n reportTrees === trees\n ? attrReports\n : collectIdentifiers(reportTrees, true).attrReports.filter(\n ({ attr, value }) =>\n !attr.includes(TEMPLATE_HOLE) && !value.includes(TEMPLATE_HOLE)\n );\n for (const report of reports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n name => path.scope.hasBinding(name) || tsNames.has(name),\n quoteForTemplateSource,\n 'no binding in this module'\n );\n }\n\n // Compute which imported identifiers are actually used as components\n const usedComponents = new Set<string>();\n const collectComponents = (node: PithyNode) => {\n if (node.type === 'element' && node.isComponent && node.originalTagName) {\n usedComponents.add(node.originalTagName);\n }\n for (const child of node.children ?? []) collectComponents(child);\n };\n for (const tree of trees) collectComponents(tree);\n\n const filteredUsed = [...usedIdentifiers].filter(\n id => !RESERVED_LOCAL_EVENT_NAMES.has(id)\n );\n\n return t.objectExpression([\n // Only hoist filtered used identifiers\n ...filteredUsed.map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add only the components that are actually used in the template\n ...[...usedComponents].map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add imported identifiers as a special property for downstream checks\n t.objectProperty(\n t.identifier('__importedIdentifiers'),\n t.newExpression(t.identifier('Set'), [\n t.arrayExpression(\n [...importedIdentifiers].map(id => t.stringLiteral(id))\n ),\n ])\n ),\n ]);\n }\n\n function collectIdentifiers(\n trees: PithyNode[],\n quiet = false\n ): {\n usedIdentifiers: Set<string>;\n attrReports: ComponentAttrReport[];\n } {\n const usedIdentifiers = new Set<string>();\n const attrReports: ComponentAttrReport[] = [];\n for (const tree of trees) {\n const ids = extractUsedIdentifiers(\n tree,\n componentScopes,\n report => attrReports.push(report),\n quiet\n );\n ids.forEach(id => usedIdentifiers.add(id));\n }\n return { usedIdentifiers, attrReports };\n }\n\n function quoteForCallForm(\n path: NodePath,\n templateArg: t.Node\n ): (value: string) => string {\n if (sourceFile(path)?.endsWith('.pithy')) return quoteForHtmlSource;\n const raw = templateArg.extra?.raw;\n if (typeof raw !== 'string') return quoteForTemplateSource;\n return raw.startsWith(\"'\")\n ? quoteForSingleQuotedSource\n : quoteForDoubleQuotedSource;\n }\n\n function reportCallFormAttrs(\n path: NodePath,\n templateStr: string,\n componentNames: Set<string>,\n context: t.ObjectExpression | null,\n quote: (value: string) => string\n ): void {\n if (componentNames.size === 0) return;\n const keys = contextKeys(context);\n const isDeclared: DeclaredName = name =>\n keys === null ||\n keys.has(name) ||\n (path.scope.hasBinding(name) && !path.scope.getBinding(name));\n const trees = parseComponentTemplate(templateStr, componentNames, true);\n for (const report of collectIdentifiers(trees, true).attrReports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n isDeclared,\n quote,\n 'no entry in the html() context'\n );\n }\n }\n\n function warnOnStringLikeComponentAttr(\n path: NodePath,\n { tag, attr, value, names, parsed, expression, error }: ComponentAttrReport,\n isDeclared: DeclaredName,\n quote: (value: string) => string,\n missing: string\n ): void {\n if (warnsOnComponentProp(attr, value)) return;\n let outcome = `does not parse (Failed to parse expression: ${error}), so the attribute is dropped`;\n let unbound: string[] = [];\n if (parsed) {\n const collected = new Set(names);\n const candidates = expression ? stringLikeNames(expression) : null;\n unbound = [...new Set(candidates ?? [])].filter(\n name => collected.has(name) && !isDeclared(name)\n );\n if (unbound.length === 0) return;\n outcome = `reads ${unbound.map(n => `\\`${n}\\``).join(', ')}, which ${unbound.length === 1 ? 'has' : 'have'} ${missing}, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime`;\n }\n\n const fix =\n parsed || !/[()[\\]{};=]/.test(value) ? `${attr}=${quote(value)}` : null;\n const advice = fix ? ` To pass a string, quote it: ${fix}.` : '';\n\n const file = sourceFile(path) ?? null;\n const loc = path.node.loc?.start;\n const where = file\n ? ` (${file}${loc ? `:${loc.line}:${loc.column + 1}` : ''})`\n : '';\n const finding: TemplateFinding = {\n kind: parsed ? 'unbound' : 'unparsed',\n tag,\n attr,\n value,\n unbound,\n error: parsed ? null : (error ?? null),\n fix,\n file,\n line: loc?.line ?? null,\n column: loc ? loc.column + 1 : null,\n message: `[pithy] <${tag} ${attr}=\"${value}\">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`,\n };\n if (options?.onFinding) options.onFinding(finding);\n else console.warn(finding.message);\n }\n\n function reportJitFallback(path: NodePath, reason: string): void {\n const where = options?.filename ? ` (${options.filename})` : '';\n if (options?.strictAot) {\n throw path.buildCodeFrameError(\n `[pithy:aot:jit-fallback] ${reason}${where}`\n );\n }\n console.warn(\n `[pithy:aot:jit-fallback] ${reason} ` +\n `The template will throw at runtime unless the app calls loadJITCompiler() at startup.${where}`\n );\n }\n\n function emitFactory(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n context: t.Expression\n ): boolean {\n try {\n // Generate deterministic hash from template content\n const rawHash = createHash('sha256')\n .update(templateStr)\n .digest('hex')\n .slice(0, 8);\n const count = aotHashCounter.get(rawHash) ?? 0;\n const hash = count > 0 ? `${rawHash}_${count}` : rawHash;\n\n // Generate scope ID from filename (or fall back to hash)\n const filename =\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename ??\n '';\n const scopeId = filename\n ? generateScopeId(filename)\n : `pithy-${rawHash.slice(0, 6)}`;\n\n // Call AOT codegen\n const aotResult = generateDomFactory(trees, hash, scopeId, {\n templateComponents,\n });\n\n // Only increment counter after successful codegen — if codegen\n // throws, the hash slot stays available for the next attempt.\n aotHashCounter.set(rawHash, count + 1);\n\n // Accumulate factory code for Program.exit injection\n aotFactoryBlocks.push(aotResult.code);\n // Detect actual applyBindings call sites rather than any occurrence of the\n // identifier name. This avoids false positives from template text that may\n // contain the string \"__applyBindings\" inside HTML or attribute values.\n if (aotResult.code.includes('return __applyBindings(')) {\n aotNeedsApplyBindings = true;\n }\n if (DUP_SLOT_DESCRIPTOR.test(aotResult.code)) aotNeedsSlotDup = true;\n\n totalHtmlTagsAotCompiled++;\n\n path.replaceWith(\n t.callExpression(t.identifier(aotResult.factoryName), [context])\n );\n return true;\n } catch (err) {\n reportJitFallback(\n path,\n `Codegen failed — skipping AOT. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return false;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"babelPlugin.js","sourceRoot":"","sources":["../../src/babelPlugin/babelPlugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EACL,sBAAsB,GAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,aAAa,EACb,4BAA4B,EAE5B,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMnD,SAAS,eAAe,CAAC,IAAkB;IACzC,IAAI,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7C,IAAI,CAAC,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC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C,CAAC,CAAC;YAEvC,qDAAqD;YACrD,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YACtC,2EAA2E;YAC3E,2EAA2E;YAC3E,wEAAwE;YACxE,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,yBAAyB,CAAC,EAAE,CAAC;gBACvD,qBAAqB,GAAG,IAAI,CAAC;YAC/B,CAAC;YACD,IAAI,mBAAmB,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;gBAAE,eAAe,GAAG,IAAI,CAAC;YAErE,wBAAwB,EAAE,CAAC;YAE3B,IAAI,CAAC,WAAW,CACd,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CACjE,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,iBAAiB,CACf,IAAI,EACJ,iCAAiC;gBAC/B,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CACrD,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.babel.html-context-plugin\",\n \"title\": \"Babel HTML Context Injection Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel plugin that injects compilation context into html`…` tagged template literals and AOT-compiles both the tagged form and literal html(template, context) calls, with scope ID generation.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"babelPluginAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport * as t from '@babel/types';\nimport type { NodePath, PluginObj, PluginPass } from '@babel/core';\nimport { parseFragment } from 'parse5';\nimport {\n extractUsedIdentifiers,\n type ComponentAttrReport,\n type ComponentScopesMap,\n} from './extractUsedIdentifiers';\nimport {\n parseTemplate,\n warnOnLowercaseComponentTags,\n type PithyNode,\n warnsOnComponentProp,\n} from '@pithyjs/compiler';\nimport { createHash } from 'crypto';\nimport { parse as babelParse } from '@babel/parser';\nimport { generateDomFactory } from '../aotCodegen';\n\ninterface PluginState extends PluginPass {\n importedIdentifiers: Set<string>;\n}\n\nfunction stringLikeNames(node: t.Expression): string[] | null {\n if (t.isIdentifier(node)) return [node.name];\n if (t.isNumericLiteral(node)) return [];\n if (\n t.isBinaryExpression(node) &&\n (node.operator === '-' || node.operator === '/')\n ) {\n const left = t.isExpression(node.left) ? stringLikeNames(node.left) : null;\n const right = stringLikeNames(node.right);\n return left && right ? [...left, ...right] : null;\n }\n if (\n t.isNewExpression(node) &&\n t.isIdentifier(node.callee) &&\n node.arguments.length === 0\n ) {\n return [node.callee.name];\n }\n if (\n t.isUnaryExpression(node) &&\n (node.operator === 'typeof' || node.operator === 'void')\n ) {\n return stringLikeNames(node.argument);\n }\n if (t.isSequenceExpression(node)) {\n const parts = node.expressions.map(stringLikeNames);\n return parts.every(p => p !== null) ? parts.flat() : null;\n }\n if (t.isMemberExpression(node)) {\n let root: t.Expression = node;\n while (\n t.isMemberExpression(root) &&\n !root.computed &&\n t.isIdentifier(root.property)\n ) {\n root = root.object;\n }\n if (!t.isIdentifier(root)) return null;\n return HOST_ROOTS.has(root.name) ? [] : [root.name];\n }\n return null;\n}\n\nconst HOST_ROOTS = new Set([\n 'window',\n 'document',\n 'location',\n 'navigator',\n 'history',\n 'localStorage',\n 'sessionStorage',\n 'console',\n 'performance',\n 'crypto',\n 'screen',\n]);\n\nconst typeScopedNames = new WeakMap<t.Node, Set<string>>();\n\nfunction scopeStatements(block: t.Node): t.Statement[] {\n if (\n t.isProgram(block) ||\n t.isBlockStatement(block) ||\n t.isStaticBlock(block) ||\n t.isTSModuleBlock(block)\n )\n return block.body;\n if (t.isFunction(block) && t.isBlockStatement(block.body))\n return block.body.body;\n if (t.isSwitchStatement(block)) return block.cases.flatMap(c => c.consequent);\n return [];\n}\n\nfunction afterLeadingImports(body: t.Statement[], from: number): number {\n let index = from;\n while (\n index < body.length &&\n (t.isImportDeclaration(body[index]) || isTypeOnlyStatement(body[index]))\n ) {\n index++;\n }\n return index;\n}\n\nfunction isTypeOnlyStatement(stmt: t.Statement): boolean {\n if (t.isExportNamedDeclaration(stmt)) {\n if (stmt.exportKind === 'type') return true;\n return stmt.declaration ? isTypeOnlyStatement(stmt.declaration) : false;\n }\n if (t.isExportDefaultDeclaration(stmt)) {\n return t.isTSInterfaceDeclaration(stmt.declaration);\n }\n return (\n t.isTSTypeAliasDeclaration(stmt) ||\n t.isTSInterfaceDeclaration(stmt) ||\n t.isTSDeclareFunction(stmt) ||\n ('declare' in stmt && !!stmt.declare) ||\n (t.isTSImportEqualsDeclaration(stmt) && stmt.importKind === 'type')\n );\n}\n\nfunction hasValueBinding(path: NodePath, name: string): boolean {\n if (!path.scope.hasBinding(name)) return false;\n const binding = path.scope.getBinding(name);\n if (!binding) return true;\n const { node, parent } = binding.path;\n return !(\n (t.isImportDeclaration(parent) && parent.importKind === 'type') ||\n (t.isImportSpecifier(node) && node.importKind === 'type') ||\n (t.isTSImportEqualsDeclaration(node) && node.importKind === 'type')\n );\n}\n\nfunction isInstantiated(decl: t.TSModuleDeclaration): boolean {\n if (!t.isTSModuleBlock(decl.body)) return true;\n return decl.body.body.some(stmt => {\n if (t.isExportNamedDeclaration(stmt)) {\n const inner = stmt.declaration;\n if (!inner) return true;\n if (\n t.isTSTypeAliasDeclaration(inner) ||\n t.isTSInterfaceDeclaration(inner)\n )\n return false;\n return t.isTSModuleDeclaration(inner)\n ? !inner.declare && isInstantiated(inner)\n : true;\n }\n if (t.isTSImportEqualsDeclaration(stmt)) return stmt.isExport;\n if (t.isTSModuleDeclaration(stmt))\n return !stmt.declare && isInstantiated(stmt);\n return !isTypeOnlyStatement(stmt);\n });\n}\n\nfunction declaredTsValueNames(path: NodePath): Set<string> {\n const names = new Set<string>();\n for (let scope = path.scope; scope; scope = scope.parent) {\n let declared = typeScopedNames.get(scope.block);\n if (!declared) {\n declared = new Set();\n for (const stmt of scopeStatements(scope.block)) {\n const decl =\n t.isExportNamedDeclaration(stmt) && stmt.declaration\n ? stmt.declaration\n : stmt;\n if (\n (t.isTSEnumDeclaration(decl) || t.isTSModuleDeclaration(decl)) &&\n t.isIdentifier(decl.id) &&\n !isTypeOnlyStatement(decl) &&\n !(t.isTSModuleDeclaration(decl) && !isInstantiated(decl))\n ) {\n declared.add(decl.id.name);\n }\n }\n typeScopedNames.set(scope.block, declared);\n }\n declared.forEach(name => names.add(name));\n }\n return names;\n}\n\nfunction quoteForHtmlSource(value: string): string {\n return `\"'${value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')}'\"`;\n}\n\nfunction quoteForDoubleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/[\\\\\"]/g, '\\\\$&');\n}\n\nfunction quoteForSingleQuotedSource(value: string): string {\n return quoteForHtmlSource(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\nfunction quoteForTemplateSource(value: string): string {\n return quoteForHtmlSource(value)\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/`/g, '\\\\`')\n .replace(/\\$\\{/g, '\\\\${');\n}\n\n// A private-use character: not valid in an identifier, so it cannot be collected as a name.\nconst TEMPLATE_HOLE = '';\n\nconst SLOT_DUP_ERROR =\n '[pithy] This module was compiled for a newer @pithyjs/core: upgrade @pithyjs/core to match @pithyjs/vite-plugin.';\n\n// A serialized `dup` descriptor. Template text cannot match: codegen escapes its quotes.\nconst DUP_SLOT_DESCRIPTOR =\n /\\{t:'proj',pid:'[^'\\\\]*',name:'(?:[^'\\\\]|\\\\.)*'(?:,fallback:\\w+)?,dup:__slotDup\\}/;\n\nfunction slotDupCheck(): t.Statement {\n return babelParse(\n `if (__slotDup !== true) throw new Error(${JSON.stringify(SLOT_DUP_ERROR)});`,\n { sourceType: 'module' }\n ).program.body[0];\n}\n\ntype DeclaredName = (name: string) => boolean;\n\n// Names that should never be hoisted into ctx even if seen in expressions\nconst RESERVED_LOCAL_EVENT_NAMES = new Set([\n '$event',\n 'event',\n 'ev',\n 'e',\n 'evt',\n]);\n\n/**\n * Configuration options for the Pithy Babel HTML context injection plugin.\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"PithyBabelPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface PithyBabelPluginOptions\"} */\nexport interface PithyBabelPluginOptions {\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: false. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n /** File path for deterministic scope ID generation (typically the Vite module id). */\n filename?: string;\n /** Receives each template finding. Default: `console.warn` of its `message`. */\n onFinding?: (finding: TemplateFinding) => void;\n}\n\n/**\n * A component attribute that will not reach the component as the author meant:\n * its value does not parse (`unparsed`, the attribute is dropped), or it reads\n * names this module does not bind (`unbound`).\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"TemplateFinding\",\"stability\":\"experimental\",\"signature\":\"interface TemplateFinding\"} */\nexport interface TemplateFinding {\n kind: 'unparsed' | 'unbound';\n tag: string;\n attr: string;\n value: string;\n /** The names read with no binding; empty for `unparsed`. */\n unbound: string[];\n /** The parser's error for `unparsed`; `null` otherwise. */\n error: string | null;\n /** The attribute quoted as a string literal, when that is the likely intent. */\n fix: string | null;\n file: string | null;\n /** 1-based, of the template expression in the module. */\n line: number | null;\n /** 1-based. */\n column: number | null;\n /** The text the plugin warns with. */\n message: string;\n}\n\n/**\n * Generate a deterministic scope ID from a file path.\n * Uses base64url-safe encoding (only [A-Za-z0-9_-]) since the ID is\n * interpolated into attribute names like data-scope-{id}.\n * Note: pithyPlugin uses raw base64 slicing — the two will diverge for\n * paths containing characters that produce +/= in base64.\n */\nfunction generateScopeId(filepath: string): string {\n const base64 = Buffer.from(filepath).toString('base64');\n // Convert to base64url-safe variant: only [A-Za-z0-9_-] allowed\n // (scopeId is interpolated into attribute names like data-scope-{id})\n const safe = base64\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n return 'pithy-' + safe.slice(0, 6);\n}\n\n/**\n * Babel plugin that transforms `html\\`...\\`` tagged template expressions.\n * In non-AOT mode, rewrites to `html(str, ctx)`. In AOT mode, pre-compiles\n * both the tagged form and `html(literal, context)` calls to a DOM factory\n * function eliminating runtime HTML parsing.\n * @param options - Plugin configuration (AOT mode, component scopes, filename)\n * @returns Babel plugin object\n */\n/** @codexApi {\"parent\":\"pithy.babel.html-context-plugin\",\"name\":\"pithyBabelPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: PithyBabelPluginOptions) => PluginObj<PluginState>\"} */\nexport default function pithyBabelPlugin(\n options?: PithyBabelPluginOptions\n): PluginObj<PluginState> {\n const componentScopes = options?.componentScopes;\n const enableAot = options?.aot ?? false;\n const templateComponents = new Set(Object.keys(componentScopes ?? {}));\n let importedIdentifiers: Set<string>;\n\n // AOT state — accumulated per file, injected in Program.exit\n let aotFactoryBlocks: string[];\n let aotNeedsApplyBindings: boolean;\n let aotNeedsSlotDup: boolean;\n let aotHashCounter: Map<string, number>;\n let aotDisabledByCollision: boolean;\n // Track html`` usage for dead import stripping\n let totalHtmlTagsFound: number;\n let totalHtmlTagsAotCompiled: number;\n // Local names of html imported from @pithyjs/core (handles aliased imports like `import { html as h }`)\n let pithyCoreHtmlLocalNames: Set<string>;\n // Set of local names of html imported from non-@pithyjs/core packages (e.g., lit)\n let foreignHtmlLocalNames: Set<string>;\n let rewrittenCalls: WeakSet<t.Node>;\n let contextsInHtmlCalls: WeakMap<object, boolean>;\n\n return {\n name: 'pithy:html-context-inject',\n\n pre() {\n importedIdentifiers = new Set<string>();\n aotFactoryBlocks = [];\n aotNeedsApplyBindings = false;\n aotNeedsSlotDup = false;\n aotHashCounter = new Map();\n aotDisabledByCollision = false;\n totalHtmlTagsFound = 0;\n totalHtmlTagsAotCompiled = 0;\n pithyCoreHtmlLocalNames = new Set();\n foreignHtmlLocalNames = new Set();\n rewrittenCalls = new WeakSet();\n contextsInHtmlCalls = new WeakMap();\n },\n\n visitor: {\n Program: {\n enter(path, _state) {\n for (const node of path.node.body) {\n if (t.isImportDeclaration(node) && node.importKind !== 'type') {\n for (const spec of node.specifiers) {\n // Skip type-only specifiers — they don't exist at runtime\n if (t.isImportSpecifier(spec) && spec.importKind === 'type')\n continue;\n if (\n t.isImportSpecifier(spec) ||\n t.isImportDefaultSpecifier(spec) ||\n t.isImportNamespaceSpecifier(spec)\n ) {\n importedIdentifiers.add(spec.local.name);\n }\n // Detect html imports and track their source package\n if (\n t.isImportSpecifier(spec) &&\n spec.importKind !== 'type' &&\n t.isIdentifier(spec.imported) &&\n spec.imported.name === 'html'\n ) {\n if (node.source.value === '@pithyjs/core') {\n pithyCoreHtmlLocalNames.add(spec.local.name);\n } else {\n foreignHtmlLocalNames.add(spec.local.name);\n }\n }\n }\n }\n }\n\n // Check for __applyBindings binding collision early — if a user-defined\n // binding exists, AOT factories would reference the wrong symbol.\n for (const name of ['__applyBindings', '__slotDup']) {\n if (enableAot && path.scope.hasBinding(name)) {\n aotDisabledByCollision = true;\n console.warn(\n `[pithy:aot] Disabling AOT — existing binding \"${name}\" ` +\n `would shadow the runtime import.`\n );\n break;\n }\n }\n },\n\n exit(path) {\n if (aotFactoryBlocks.length === 0) return;\n\n // 1. Add __applyBindings import (only if needed)\n if (aotNeedsApplyBindings) {\n const imported = (name: string) =>\n path.node.body.some(\n stmt =>\n t.isImportDeclaration(stmt) &&\n stmt.importKind !== 'type' &&\n stmt.source.value === '@pithyjs/core/runtime/applyBindings' &&\n stmt.specifiers.some(\n s =>\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.local) &&\n s.local.name === name\n )\n );\n const missing = ['__applyBindings'];\n if (aotNeedsSlotDup) missing.push('__slotDup');\n const names = missing.filter(name => !imported(name));\n\n if (names.length) {\n const importDecl = t.importDeclaration(\n names.map(name =>\n t.importSpecifier(t.identifier(name), t.identifier(name))\n ),\n t.stringLiteral('@pithyjs/core/runtime/applyBindings')\n );\n // Insert after directive prologues and existing imports.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let importInsertIndex = 0;\n const body = path.node.body;\n while (\n importInsertIndex < body.length &&\n t.isExpressionStatement(body[importInsertIndex]) &&\n t.isStringLiteral(\n (body[importInsertIndex] as t.ExpressionStatement).expression\n )\n ) {\n importInsertIndex++;\n }\n importInsertIndex = afterLeadingImports(body, importInsertIndex);\n path.node.body.splice(importInsertIndex, 0, importDecl);\n }\n }\n\n // 2. Parse factory code blocks into AST and inject after last import\n const statementsToInject: t.Program['body'] = [];\n // Vite's SSR runner reads a missing export of an inlined module as undefined.\n if (aotNeedsSlotDup) statementsToInject.push(slotDupCheck());\n\n for (const block of aotFactoryBlocks) {\n const ast = babelParse(block, {\n sourceType: 'module',\n plugins: [],\n });\n if (ast.program?.body) {\n statementsToInject.push(...ast.program.body);\n }\n }\n\n if (statementsToInject.length === 0) return;\n\n // Find insertion point: after directive prologues and import declarations.\n // Two-phase scan: first skip all consecutive directives, then all imports.\n let insertIndex = 0;\n const bodyForFactory = path.node.body;\n while (\n insertIndex < bodyForFactory.length &&\n t.isExpressionStatement(bodyForFactory[insertIndex]) &&\n t.isStringLiteral(\n (bodyForFactory[insertIndex] as t.ExpressionStatement).expression\n )\n ) {\n insertIndex++;\n }\n insertIndex = afterLeadingImports(bodyForFactory, insertIndex);\n\n path.node.body.splice(insertIndex, 0, ...statementsToInject);\n\n // 3. Strip unused `html` import when all html`` tags were AOT-compiled.\n // This enables Rollup to tree-shake html() → parseHtml → parse5 entirely.\n // Safety: use Babel binding analysis (scope.crawl + getBinding) to verify\n // the html identifier has no remaining references after AOT transforms.\n // This covers all non-tagged-template usages: html(), const t = html, etc.\n if (\n enableAot &&\n totalHtmlTagsFound > 0 &&\n totalHtmlTagsFound === totalHtmlTagsAotCompiled &&\n pithyCoreHtmlLocalNames.size > 0\n ) {\n // Re-crawl scope to get accurate reference counts after AOT transforms\n path.scope.crawl();\n const unreferenced = new Set(\n [...pithyCoreHtmlLocalNames].filter(\n name => !(path.scope.getBinding(name)?.references ?? 0)\n )\n );\n\n for (let i = path.node.body.length - 1; i >= 0; i--) {\n const stmt = path.node.body[i];\n if (!t.isImportDeclaration(stmt) || stmt.importKind === 'type')\n continue;\n\n // Only strip html from @pithyjs/core — never touch other packages (e.g., lit)\n if (stmt.source.value !== '@pithyjs/core') continue;\n\n const kept = stmt.specifiers.filter(\n s =>\n !(\n t.isImportSpecifier(s) &&\n s.importKind !== 'type' &&\n t.isIdentifier(s.imported) &&\n s.imported.name === 'html' &&\n unreferenced.has(s.local.name)\n )\n );\n if (kept.length === stmt.specifiers.length) continue;\n stmt.specifiers = kept;\n // If no specifiers remain, remove the entire import declaration\n if (kept.length === 0) {\n path.node.body.splice(i, 1);\n }\n }\n }\n },\n },\n\n TaggedTemplateExpression(path) {\n // Only transform html`` from @pithyjs/core — leave other packages' html (e.g., lit) untouched.\n // When we detected a @pithyjs/core html import, match its local name (handles aliases).\n // When no @pithyjs/core import was found, fall back to matching literal \"html\" (bare usage),\n // but skip if \"html\" is known to come from a foreign package.\n const tag = unwrapTs(path.node.tag);\n const tagName = t.isIdentifier(tag) ? tag.name : null;\n if (!tagName) return;\n if (foreignHtmlLocalNames.has(tagName)) return;\n if (\n pithyCoreHtmlLocalNames.size > 0\n ? !pithyCoreHtmlLocalNames.has(tagName)\n : tagName !== 'html'\n )\n return;\n\n totalHtmlTagsFound++;\n\n const quasi = path.node.quasi;\n const templateStr = quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('');\n\n // Warn about lowercase component tags used for imported components\n if (importedIdentifiers.size > 0) {\n warnOnLowercaseComponentTags(templateStr, importedIdentifiers);\n }\n\n const trees = parseComponentTemplate(templateStr, importedIdentifiers);\n if (trees.length === 0) return;\n\n const reportTrees =\n quasi.expressions.length === 0\n ? trees\n : parseComponentTemplate(\n quasi.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join(TEMPLATE_HOLE),\n importedIdentifiers,\n true\n );\n const contextObject = buildContextObject(path, trees, reportTrees);\n\n // ── AOT codegen path ──────────────────────────────────────────────\n if (enableAot && !aotDisabledByCollision) {\n // Templates with ${expr} expressions can't be AOT-compiled safely.\n // PithyJS uses {{ expr }} syntax, not ${}, so this is an edge case guard.\n if (quasi.expressions.length > 0) {\n // Fall through to non-AOT path below\n reportJitFallback(\n path,\n `Template contains \\${expr} expressions — skipping AOT. ` +\n `Refactor to {{ expr }} syntax for AOT compilation.`\n );\n } else if (emitFactory(path, trees, templateStr, contextObject)) {\n return;\n }\n }\n\n // ── Non-AOT path (original behavior) ─────────────────────────────\n const runtimeCall = t.callExpression(path.node.tag, [\n quasi,\n contextObject,\n ]);\n rewrittenCalls.add(runtimeCall);\n path.replaceWith(runtimeCall);\n },\n\n CallExpression(path) {\n if (rewrittenCalls.has(path.node)) return;\n const callee = unwrapTs(path.node.callee);\n if (\n !t.isIdentifier(callee) ||\n !pithyCoreHtmlLocalNames.has(callee.name)\n )\n return;\n if (path.scope.getBinding(callee.name)?.kind !== 'module') return;\n\n const [rawTemplateArg, contextArg, cssArg] = path.node.arguments;\n const templateArg = unwrapTs(rawTemplateArg);\n const templateStr = t.isStringLiteral(templateArg)\n ? templateArg.value\n : t.isTemplateLiteral(templateArg) &&\n templateArg.expressions.length === 0\n ? templateArg.quasis\n .map(q => q.value.cooked ?? q.value.raw)\n .join('')\n : null;\n const context = contextLiteral(path, contextArg);\n const componentNames = declaredComponents(context);\n\n if (templateStr !== null) {\n reportCallFormAttrs(\n path,\n templateStr,\n componentNames,\n contextStaysInHtmlCalls(path, contextArg) ? context : null,\n quoteForCallForm(path, templateArg)\n );\n }\n\n if (!enableAot || aotDisabledByCollision) return;\n\n totalHtmlTagsFound++;\n\n if (templateStr === null) {\n reportJitFallback(\n path,\n `html() is called with a template that is not a string literal — skipping AOT. ` +\n `Pass the template as a literal.`\n );\n return;\n }\n\n if (cssArg !== undefined && !isAbsentCss(cssArg)) {\n reportJitFallback(\n path,\n `html() is called with a css argument — skipping AOT.`\n );\n return;\n }\n\n if (contextArg && !context) {\n reportJitFallback(\n path,\n `html() is called with a second argument that is not an object literal, so it may be a css string or a context the build cannot read — skipping AOT. ` +\n `Pass the context as an object literal, inline or bound by const.`\n );\n return;\n }\n\n try {\n warnOnLowercaseComponentTags(templateStr, componentNames);\n } catch (err) {\n reportJitFallback(\n path,\n `html() template has a tag that cannot be resolved to a component at build time — skipping AOT. ` +\n `Name the component in a literal \\`__importedIdentifiers: new Set([...])\\` in the context. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return;\n }\n\n emitFactory(\n path,\n parseComponentTemplate(templateStr, componentNames),\n templateStr,\n t.isExpression(contextArg) ? contextArg : t.objectExpression([])\n );\n },\n },\n };\n\n function unwrapTs(node: t.Node | null | undefined): t.Node | null {\n let current = node ?? null;\n while (\n t.isTSAsExpression(current) ||\n t.isTSSatisfiesExpression(current) ||\n t.isTSTypeAssertion(current) ||\n t.isTSNonNullExpression(current) ||\n t.isParenthesizedExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n }\n\n function isAbsentCss(cssArg: t.Node): boolean {\n const css = unwrapTs(cssArg);\n return (\n t.isIdentifier(css, { name: 'undefined' }) ||\n t.isNullLiteral(css) ||\n t.isStringLiteral(css, { value: '' }) ||\n t.isUnaryExpression(css, { operator: 'void' })\n );\n }\n\n function contextLiteral(\n path: NodePath,\n contextArg: t.Node | undefined\n ): t.ObjectExpression | null {\n const arg = unwrapTs(contextArg);\n if (t.isObjectExpression(arg)) return arg;\n if (!t.isIdentifier(arg)) return null;\n const binding = path.scope.getBinding(arg.name);\n if (binding?.kind !== 'const' || !binding.path.isVariableDeclarator())\n return null;\n if (!t.isIdentifier(binding.path.node.id)) return null;\n const init = unwrapTs(binding.path.node.init);\n return t.isObjectExpression(init) ? init : null;\n }\n\n function declaredComponents(literal: t.ObjectExpression | null): Set<string> {\n const names = new Set<string>();\n if (!literal) return names;\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop)) {\n names.clear();\n continue;\n }\n if (prop.computed) continue;\n const key = t.isIdentifier(prop.key)\n ? prop.key.name\n : t.isStringLiteral(prop.key)\n ? prop.key.value\n : null;\n if (key !== '__importedIdentifiers') continue;\n names.clear();\n if (!t.isObjectProperty(prop)) continue;\n const value = unwrapTs(prop.value);\n if (\n !t.isNewExpression(value) ||\n !t.isIdentifier(unwrapTs(value.callee), { name: 'Set' })\n )\n continue;\n const list = unwrapTs(value.arguments[0]);\n if (!t.isArrayExpression(list)) continue;\n for (const element of list.elements) {\n const entry = unwrapTs(element);\n if (t.isStringLiteral(entry)) names.add(entry.value);\n }\n }\n return names;\n }\n\n function sourceFile(path: NodePath): string | undefined {\n return (\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename\n );\n }\n\n function contextStaysInHtmlCalls(\n path: NodePath,\n contextArg: t.Node | undefined\n ): boolean {\n const arg = unwrapTs(contextArg);\n if (!t.isIdentifier(arg)) return true;\n const binding = path.scope.getBinding(arg.name);\n if (!binding) return true;\n // AOT rewrites earlier html() calls into factory calls that receive the\n // same context, so classify the references once, before any rewrite.\n let stays = contextsInHtmlCalls.get(binding);\n if (stays === undefined) {\n stays = binding.referencePaths.every(reference => {\n if (reference.findParent(p => p.isTSTypeQuery())) return true;\n const call = reference.findParent(\n p => unwrapTs(p.node) !== reference.node\n )?.node;\n if (!t.isCallExpression(call)) return false;\n const callee = unwrapTs(call.callee);\n return (\n t.isIdentifier(callee) &&\n pithyCoreHtmlLocalNames.has(callee.name) &&\n reference.scope.getBinding(callee.name)?.kind === 'module' &&\n unwrapTs(call.arguments[1]) === reference.node\n );\n });\n contextsInHtmlCalls.set(binding, stays);\n }\n return stays;\n }\n\n function contextKeys(literal: t.ObjectExpression | null): Set<string> | null {\n if (!literal) return null;\n const keys = new Set<string>();\n for (const prop of literal.properties) {\n if (t.isSpreadElement(prop) || prop.computed) return null;\n if (t.isIdentifier(prop.key)) keys.add(prop.key.name);\n else if (t.isStringLiteral(prop.key)) keys.add(prop.key.value);\n }\n return keys;\n }\n\n function parseComponentTemplate(\n templateStr: string,\n componentNames: Set<string>,\n quiet = false\n ): PithyNode[] {\n // `importedIdentifiers` is what makes component tags components at all;\n // `withSource: false` keeps interpolation scanning on parse5's decoded\n // text, because codegen locates interpolations with indexOf(interp.raw)\n // against decoded textContent and a raw source slice would carry entities.\n return parseTemplate(templateStr, parseFragment, {\n importedIdentifiers: componentNames,\n withSource: false,\n quiet,\n }).nodes;\n }\n\n function buildContextObject(\n path: NodePath,\n trees: PithyNode[],\n reportTrees: PithyNode[]\n ): t.ObjectExpression {\n // Collect identifiers referenced by expressions in the template\n const { usedIdentifiers, attrReports } = collectIdentifiers(trees);\n\n const tsNames = declaredTsValueNames(path);\n const reports =\n reportTrees === trees\n ? attrReports\n : collectIdentifiers(reportTrees, true).attrReports.filter(\n ({ attr, value }) =>\n !attr.includes(TEMPLATE_HOLE) && !value.includes(TEMPLATE_HOLE)\n );\n for (const report of reports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n name => hasValueBinding(path, name) || tsNames.has(name),\n quoteForTemplateSource,\n 'no binding in this module'\n );\n }\n\n // Compute which imported identifiers are actually used as components\n const usedComponents = new Set<string>();\n const collectComponents = (node: PithyNode) => {\n if (node.type === 'element' && node.isComponent && node.originalTagName) {\n usedComponents.add(node.originalTagName);\n }\n for (const child of node.children ?? []) collectComponents(child);\n };\n for (const tree of trees) collectComponents(tree);\n\n const filteredUsed = [...usedIdentifiers].filter(\n id => !RESERVED_LOCAL_EVENT_NAMES.has(id)\n );\n\n return t.objectExpression([\n // Only hoist filtered used identifiers\n ...filteredUsed.map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add only the components that are actually used in the template\n ...[...usedComponents].map(id =>\n t.objectProperty(t.identifier(id), t.identifier(id), false, true)\n ),\n // Add imported identifiers as a special property for downstream checks\n t.objectProperty(\n t.identifier('__importedIdentifiers'),\n t.newExpression(t.identifier('Set'), [\n t.arrayExpression(\n [...importedIdentifiers].map(id => t.stringLiteral(id))\n ),\n ])\n ),\n ]);\n }\n\n function collectIdentifiers(\n trees: PithyNode[],\n quiet = false\n ): {\n usedIdentifiers: Set<string>;\n attrReports: ComponentAttrReport[];\n } {\n const usedIdentifiers = new Set<string>();\n const attrReports: ComponentAttrReport[] = [];\n for (const tree of trees) {\n const ids = extractUsedIdentifiers(\n tree,\n componentScopes,\n report => attrReports.push(report),\n quiet\n );\n ids.forEach(id => usedIdentifiers.add(id));\n }\n return { usedIdentifiers, attrReports };\n }\n\n function quoteForCallForm(\n path: NodePath,\n templateArg: t.Node | null\n ): (value: string) => string {\n if (sourceFile(path)?.endsWith('.pithy')) return quoteForHtmlSource;\n const raw = templateArg?.extra?.raw;\n if (typeof raw !== 'string') return quoteForTemplateSource;\n return raw.startsWith(\"'\")\n ? quoteForSingleQuotedSource\n : quoteForDoubleQuotedSource;\n }\n\n function reportCallFormAttrs(\n path: NodePath,\n templateStr: string,\n componentNames: Set<string>,\n context: t.ObjectExpression | null,\n quote: (value: string) => string\n ): void {\n if (componentNames.size === 0) return;\n const keys = contextKeys(context);\n const isDeclared: DeclaredName = name =>\n keys === null ||\n keys.has(name) ||\n (path.scope.hasBinding(name) && !path.scope.getBinding(name));\n const trees = parseComponentTemplate(templateStr, componentNames, true);\n for (const report of collectIdentifiers(trees, true).attrReports) {\n warnOnStringLikeComponentAttr(\n path,\n report,\n isDeclared,\n quote,\n 'no entry in the html() context'\n );\n }\n }\n\n function warnOnStringLikeComponentAttr(\n path: NodePath,\n { tag, attr, value, names, parsed, expression, error }: ComponentAttrReport,\n isDeclared: DeclaredName,\n quote: (value: string) => string,\n missing: string\n ): void {\n if (warnsOnComponentProp(attr, value)) return;\n let outcome = `does not parse (Failed to parse expression: ${error}), so the attribute is dropped`;\n let unbound: string[] = [];\n if (parsed) {\n const collected = new Set(names);\n const candidates = expression ? stringLikeNames(expression) : null;\n unbound = [...new Set(candidates ?? [])].filter(\n name => collected.has(name) && !isDeclared(name)\n );\n if (unbound.length === 0) return;\n outcome = `reads ${unbound.map(n => `\\`${n}\\``).join(', ')}, which ${unbound.length === 1 ? 'has' : 'have'} ${missing}, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime`;\n }\n\n const fix =\n parsed || !/[()[\\]{};=]/.test(value) ? `${attr}=${quote(value)}` : null;\n const advice = fix ? ` To pass a string, quote it: ${fix}.` : '';\n\n const file = sourceFile(path) ?? null;\n const loc = path.node.loc?.start;\n const where = file\n ? ` (${file}${loc ? `:${loc.line}:${loc.column + 1}` : ''})`\n : '';\n const finding: TemplateFinding = {\n kind: parsed ? 'unbound' : 'unparsed',\n tag,\n attr,\n value,\n unbound,\n error: parsed ? null : (error ?? null),\n fix,\n file,\n line: loc?.line ?? null,\n column: loc ? loc.column + 1 : null,\n message: `[pithy] <${tag} ${attr}=\"${value}\">: a component attribute is a JavaScript expression, and this one ${outcome}.${advice}${where}`,\n };\n if (options?.onFinding) options.onFinding(finding);\n else console.warn(finding.message);\n }\n\n function reportJitFallback(path: NodePath, reason: string): void {\n const where = options?.filename ? ` (${options.filename})` : '';\n if (options?.strictAot) {\n throw path.buildCodeFrameError(\n `[pithy:aot:jit-fallback] ${reason}${where}`\n );\n }\n console.warn(\n `[pithy:aot:jit-fallback] ${reason} ` +\n `The template will throw at runtime unless the app calls loadJITCompiler() at startup.${where}`\n );\n }\n\n function emitFactory(\n path: NodePath,\n trees: PithyNode[],\n templateStr: string,\n context: t.Expression\n ): boolean {\n try {\n // Generate deterministic hash from template content\n const rawHash = createHash('sha256')\n .update(templateStr)\n .digest('hex')\n .slice(0, 8);\n const count = aotHashCounter.get(rawHash) ?? 0;\n const hash = count > 0 ? `${rawHash}_${count}` : rawHash;\n\n // Generate scope ID from filename (or fall back to hash)\n const filename =\n options?.filename ??\n (path.hub as { file?: { opts?: { filename?: string } } })?.file?.opts\n ?.filename ??\n '';\n const scopeId = filename\n ? generateScopeId(filename)\n : `pithy-${rawHash.slice(0, 6)}`;\n\n // Call AOT codegen\n const aotResult = generateDomFactory(trees, hash, scopeId, {\n templateComponents,\n declareSlots: true,\n });\n\n // Only increment counter after successful codegen — if codegen\n // throws, the hash slot stays available for the next attempt.\n aotHashCounter.set(rawHash, count + 1);\n\n // Accumulate factory code for Program.exit injection\n aotFactoryBlocks.push(aotResult.code);\n // Detect actual applyBindings call sites rather than any occurrence of the\n // identifier name. This avoids false positives from template text that may\n // contain the string \"__applyBindings\" inside HTML or attribute values.\n if (aotResult.code.includes('return __applyBindings(')) {\n aotNeedsApplyBindings = true;\n }\n if (DUP_SLOT_DESCRIPTOR.test(aotResult.code)) aotNeedsSlotDup = true;\n\n totalHtmlTagsAotCompiled++;\n\n path.replaceWith(\n t.callExpression(t.identifier(aotResult.factoryName), [context])\n );\n return true;\n } catch (err) {\n reportJitFallback(\n path,\n `Codegen failed — skipping AOT. ` +\n (err instanceof Error ? err.message : String(err))\n );\n return false;\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"validateTemplate.d.ts","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAIjI,OAAyB,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAWnE,uKAAuK;AACvK,MAAM,WAAW,uBAAuB;IACtC,sGAAsG;IACtG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,yGAAyG;IACzG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,8MAA8M;AAC9M,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,eAAe,EAAE,CAAC,CAoC5B"}
1
+ {"version":3,"file":"validateTemplate.d.ts","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAEjI,OAAyB,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AASnE,uKAAuK;AACvK,MAAM,WAAW,uBAAuB;IACtC,sGAAsG;IACtG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,yGAAyG;IACzG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,8MAA8M;AAC9M,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,eAAe,EAAE,CAAC,CAkC5B"}
@@ -1,11 +1,7 @@
1
1
  /** @codex { "id": "pithy.babel.validate-template", "title": "Template Validation", "category": "compiler", "risk": "medium" } */
2
- import * as babel from '@babel/core';
3
- import { createRequire } from 'node:module';
4
2
  import pithyBabelPlugin from './babelPlugin.js';
5
3
  import { compilePithyModule } from '../pithyPlugin/plugin.js';
6
- import { readsTemplates } from '../htmlTransform/htmlTransform.js';
7
- const presetTypescript = createRequire(import.meta.url).resolve('@babel/preset-typescript');
8
- // Babel needs a name to pick the TS preset; it is not reported.
4
+ import { readsTemplates, transformTypeScriptModule, } from '../htmlTransform/htmlTransform.js';
9
5
  const UNNAMED = 'module.ts';
10
6
  /**
11
7
  * The component-attribute findings the Vite plugin warns about, for one module,
@@ -37,7 +33,7 @@ export async function validateTemplate(code, options = {}) {
37
33
  if (!readsTemplates(source))
38
34
  return [];
39
35
  const findings = [];
40
- babel.transformSync(source, {
36
+ transformTypeScriptModule(source, {
41
37
  filename,
42
38
  plugins: [
43
39
  () => pithyBabelPlugin({
@@ -46,8 +42,6 @@ export async function validateTemplate(code, options = {}) {
46
42
  onFinding: finding => findings.push(finding),
47
43
  }),
48
44
  ],
49
- presets: [[presetTypescript, { onlyRemoveTypeImports: true }]],
50
- parserOpts: { sourceType: 'module', plugins: ['typescript'] },
51
45
  configFile: false,
52
46
  babelrc: false,
53
47
  code: false,
@@ -1 +1 @@
1
- {"version":3,"file":"validateTemplate.js","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAEjI,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,gBAA0C,MAAM,eAAe,CAAC;AAEvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,MAAM,gBAAgB,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAC7D,0BAA0B,CAC3B,CAAC;AAEF,gEAAgE;AAChE,MAAM,OAAO,GAAG,WAAW,CAAC;AAe5B;;;;;;;;;;;;;;;;GAgBG;AACH,8MAA8M;AAC9M,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,IAAY,EACZ,UAAmC,EAAE;IAErC,MAAM,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;IAC5B,MAAM,QAAQ,GAAG,EAAE,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,I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IAAI,EAAE,IAAI;YACV,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SACrD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.babel.validate-template\", \"title\": \"Template Validation\", \"category\": \"compiler\", \"risk\": \"medium\" } */\n\nimport * as babel from '@babel/core';\nimport { createRequire } from 'node:module';\nimport pithyBabelPlugin, { type TemplateFinding } from './babelPlugin';\nimport type { ComponentScopesMap } from './extractUsedIdentifiers';\nimport { compilePithyModule } from '../pithyPlugin/plugin';\nimport { readsTemplates } from '../htmlTransform/htmlTransform';\n\nconst presetTypescript = createRequire(import.meta.url).resolve(\n '@babel/preset-typescript'\n);\n\n// Babel needs a name to pick the TS preset; it is not reported.\nconst UNNAMED = 'module.ts';\n\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"ValidateTemplateOptions\",\"stability\":\"experimental\",\"signature\":\"interface ValidateTemplateOptions\"} */\nexport interface ValidateTemplateOptions {\n /** The module's path or id. Without it the module is read as `.ts` and findings carry no location. */\n filename?: string;\n /**\n * The map `htmlTransformPlugin` is given. Pass ui-kit's `componentScopes`\n * for an app's findings: without it `<For>`'s loop names read as unbound.\n */\n componentScopes?: ComponentScopesMap;\n /** For a `.pithy` file, esbuild's tsconfig as JSON, in place of the `tsconfig.json` above `filename`. */\n tsconfigRaw?: string;\n}\n\n/**\n * The component-attribute findings the Vite plugin warns about, for one module,\n * without building it.\n *\n * Runs the steps the plugin chain runs: a `.pithy` file is compiled and\n * transpiled as `pithyPlugin` does, then the plugin's own Babel pass checks it.\n * A finding's `message`, `line` and `column` are those the dev server and the\n * build print; for a `.pithy` file they refer to the compiled module. Like the\n * chain, it checks `.ts` and `.pithy` files only, skips a module with no `html`\n * template, and returns `[]` for both.\n *\n * @param code - A `.ts` module using `html` templates, or a `.pithy` file.\n * @param options - The filename and the component scopes.\n * @returns One finding per attribute, in source order; empty when all is well.\n * @throws The parser's error when a module the transform reads does not parse,\n * as the build would.\n */\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"validateTemplate\",\"stability\":\"experimental\",\"signature\":\"(code: string, options?: ValidateTemplateOptions) => Promise<TemplateFinding[]>\"} */\nexport async function validateTemplate(\n code: string,\n options: ValidateTemplateOptions = {}\n): Promise<TemplateFinding[]> {\n const id = options.filename;\n const filename = id?.split(/[?#]/, 1)[0] ?? UNNAMED;\n const isPithy = filename.endsWith('.pithy');\n if (!isPithy && !filename.endsWith('.ts')) return [];\n\n const source = isPithy\n ? (await compilePithyModule(code, id ?? filename, options.tsconfigRaw)).code\n : code;\n if (!readsTemplates(source)) return [];\n const findings: TemplateFinding[] = [];\n babel.transformSync(source, {\n filename,\n plugins: [\n () =>\n pithyBabelPlugin({\n filename,\n componentScopes: options.componentScopes,\n onFinding: finding => findings.push(finding),\n }),\n ],\n presets: [[presetTypescript, { onlyRemoveTypeImports: true }]],\n parserOpts: { sourceType: 'module', plugins: ['typescript'] },\n configFile: false,\n babelrc: false,\n code: false,\n });\n if (id !== undefined) return findings;\n return findings.map(f => {\n const at = f.message.lastIndexOf(` (${UNNAMED}`);\n return {\n ...f,\n file: null,\n message: at < 0 ? f.message : f.message.slice(0, at),\n };\n });\n}\n"]}
1
+ {"version":3,"file":"validateTemplate.js","sourceRoot":"","sources":["../../src/babelPlugin/validateTemplate.ts"],"names":[],"mappings":"AAAA,iIAAiI;AAEjI,OAAO,gBAA0C,MAAM,eAAe,CAAC;AAEvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EACL,cAAc,EACd,yBAAyB,GAC1B,MAAM,gCAAgC,CAAC;AAExC,MAAM,OAAO,GAAG,WAAW,CAAC;AAe5B;;;;;;;;;;;;;;;;GAgBG;AACH,8MAA8M;AAC9M,MAAM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G,CAAC;YACJ,IAAI,EAAE,IAAI;YACV,OAAO,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SACrD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.babel.validate-template\", \"title\": \"Template Validation\", \"category\": \"compiler\", \"risk\": \"medium\" } */\n\nimport pithyBabelPlugin, { type TemplateFinding } from './babelPlugin';\nimport type { ComponentScopesMap } from './extractUsedIdentifiers';\nimport { compilePithyModule } from '../pithyPlugin/plugin';\nimport {\n readsTemplates,\n transformTypeScriptModule,\n} from '../htmlTransform/htmlTransform';\n\nconst UNNAMED = 'module.ts';\n\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"ValidateTemplateOptions\",\"stability\":\"experimental\",\"signature\":\"interface ValidateTemplateOptions\"} */\nexport interface ValidateTemplateOptions {\n /** The module's path or id. Without it the module is read as `.ts` and findings carry no location. */\n filename?: string;\n /**\n * The map `htmlTransformPlugin` is given. Pass ui-kit's `componentScopes`\n * for an app's findings: without it `<For>`'s loop names read as unbound.\n */\n componentScopes?: ComponentScopesMap;\n /** For a `.pithy` file, esbuild's tsconfig as JSON, in place of the `tsconfig.json` above `filename`. */\n tsconfigRaw?: string;\n}\n\n/**\n * The component-attribute findings the Vite plugin warns about, for one module,\n * without building it.\n *\n * Runs the steps the plugin chain runs: a `.pithy` file is compiled and\n * transpiled as `pithyPlugin` does, then the plugin's own Babel pass checks it.\n * A finding's `message`, `line` and `column` are those the dev server and the\n * build print; for a `.pithy` file they refer to the compiled module. Like the\n * chain, it checks `.ts` and `.pithy` files only, skips a module with no `html`\n * template, and returns `[]` for both.\n *\n * @param code - A `.ts` module using `html` templates, or a `.pithy` file.\n * @param options - The filename and the component scopes.\n * @returns One finding per attribute, in source order; empty when all is well.\n * @throws The parser's error when a module the transform reads does not parse,\n * as the build would.\n */\n/** @codexApi {\"parent\":\"pithy.babel.validate-template\",\"name\":\"validateTemplate\",\"stability\":\"experimental\",\"signature\":\"(code: string, options?: ValidateTemplateOptions) => Promise<TemplateFinding[]>\"} */\nexport async function validateTemplate(\n code: string,\n options: ValidateTemplateOptions = {}\n): Promise<TemplateFinding[]> {\n const id = options.filename;\n const filename = id?.split(/[?#]/, 1)[0] ?? UNNAMED;\n const isPithy = filename.endsWith('.pithy');\n if (!isPithy && !filename.endsWith('.ts')) return [];\n\n const source = isPithy\n ? (await compilePithyModule(code, id ?? filename, options.tsconfigRaw)).code\n : code;\n if (!readsTemplates(source)) return [];\n const findings: TemplateFinding[] = [];\n transformTypeScriptModule(source, {\n filename,\n plugins: [\n () =>\n pithyBabelPlugin({\n filename,\n componentScopes: options.componentScopes,\n onFinding: finding => findings.push(finding),\n }),\n ],\n configFile: false,\n babelrc: false,\n code: false,\n });\n if (id !== undefined) return findings;\n return findings.map(f => {\n const at = f.message.lastIndexOf(` (${UNNAMED}`);\n return {\n ...f,\n file: null,\n message: at < 0 ? f.message : f.message.slice(0, at),\n };\n });\n}\n"]}
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import type { PluginOption } from 'vite';
17
17
  import type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers.js';
18
+ import * as babel from '@babel/core';
18
19
  /**
19
20
  * Whether the template transform reads `code` at all: it holds an `html`
20
21
  * tagged template, or imports `html` from `@pithyjs/core` (an alias included).
@@ -24,6 +25,7 @@ import type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers.j
24
25
  * @returns `true` when the transform parses it.
25
26
  */
26
27
  export declare function readsTemplates(code: string): boolean;
28
+ export declare function transformTypeScriptModule(code: string, options: Omit<babel.TransformOptions, 'parserOpts'>): babel.BabelFileResult | null;
27
29
  /** @codexApi {"parent":"pithy.vite.html-transform-plugin","name":"HtmlTransformPluginOptions","stability":"stable","signature":"interface HtmlTransformPluginOptions"} */
28
30
  export interface HtmlTransformPluginOptions {
29
31
  /** Map of component names to variables they inject into children's scope */
@@ -1 +1 @@
1
- {"version":3,"file":"htmlTransform.d.ts","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,MAAM,CAAC;AAIzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAShF;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAKpD;AAED,0KAA0K;AAC1K,MAAM,WAAW,0BAA0B;IACzC,4EAA4E;IAC5E,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,kFAAkF;IAClF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,oHAAoH;IACpH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qLAAqL;AACrL,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,0BAA0B,GACnC,YAAY,CAkEd"}
1
+ {"version":3,"file":"htmlTransform.d.ts","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAEF,OAAO,KAAK,EAAkB,YAAY,EAAkB,MAAM,MAAM,CAAC;AAIzE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AAErC;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMpD;AA2BD,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,YAAY,CAAC,GAClD,KAAK,CAAC,eAAe,GAAG,IAAI,CAoB9B;AAED,0KAA0K;AAC1K,MAAM,WAAW,0BAA0B;IACzC,4EAA4E;IAC5E,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,kFAAkF;IAClF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,oHAAoH;IACpH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qLAAqL;AACrL,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,0BAA0B,GACnC,YAAY,CAwFd"}
@@ -15,9 +15,6 @@
15
15
  */
16
16
  import pithyBabelPlugin from '../babelPlugin/babelPlugin.js';
17
17
  import * as babel from '@babel/core';
18
- import { createRequire } from 'node:module';
19
- // Babel resolves preset names from the app, which may not see this package's deps.
20
- const presetTypescript = createRequire(import.meta.url).resolve('@babel/preset-typescript');
21
18
  /**
22
19
  * Whether the template transform reads `code` at all: it holds an `html`
23
20
  * tagged template, or imports `html` from `@pithyjs/core` (an alias included).
@@ -28,8 +25,55 @@ const presetTypescript = createRequire(import.meta.url).resolve('@babel/preset-t
28
25
  */
29
26
  export function readsTemplates(code) {
30
27
  return (code.includes('html`') ||
28
+ /\bhtml\s*(?:!|\s+as\s+[\w.]+)?[\s)]*`/.test(code) ||
31
29
  /import\s*\{[^}]*\bhtml\b[^}]*\}\s*from\s+['"]@pithyjs\/core['"]/.test(code));
32
30
  }
31
+ const DECORATOR_DIALECTS = [
32
+ [
33
+ 'typescript',
34
+ 'decorators-legacy',
35
+ 'decoratorAutoAccessors',
36
+ 'explicitResourceManagement',
37
+ ],
38
+ [
39
+ 'typescript',
40
+ ['decorators', {}],
41
+ 'decoratorAutoAccessors',
42
+ 'explicitResourceManagement',
43
+ ],
44
+ ];
45
+ const dropTypeOnlyImportEquals = () => ({
46
+ visitor: {
47
+ TSImportEqualsDeclaration(path) {
48
+ if (path.node.importKind === 'type')
49
+ path.remove();
50
+ },
51
+ },
52
+ });
53
+ const parsedTo = (err) => err.pos ?? -1;
54
+ export function transformTypeScriptModule(code, options) {
55
+ let parseError;
56
+ for (const plugins of DECORATOR_DIALECTS) {
57
+ try {
58
+ return babel.transformSync(code, {
59
+ ...options,
60
+ plugins: [dropTypeOnlyImportEquals, ...(options.plugins ?? [])],
61
+ parserOpts: {
62
+ sourceType: 'module',
63
+ plugins,
64
+ createParenthesizedExpressions: true,
65
+ },
66
+ });
67
+ }
68
+ catch (err) {
69
+ if (err.code !== 'BABEL_PARSE_ERROR')
70
+ throw err;
71
+ if (parseError === undefined || parsedTo(err) > parsedTo(parseError))
72
+ parseError = err;
73
+ }
74
+ }
75
+ throw parseError;
76
+ }
33
77
  /**
34
78
  * Vite plugin that transforms `html\`\`` tagged templates and literal `html()` calls
35
79
  * in `.ts` and compiled `.pithy` modules using Babel.
@@ -55,6 +99,7 @@ export function readsTemplates(code) {
55
99
  export function htmlTransformPlugin(options) {
56
100
  let resolvedAot = false;
57
101
  let sourceMaps = true;
102
+ let lowering = null;
58
103
  const plugin = {
59
104
  name: 'pithy:html-transform',
60
105
  enforce: 'pre',
@@ -62,6 +107,8 @@ export function htmlTransformPlugin(options) {
62
107
  // Default: AOT enabled in build, disabled in dev (for faster HMR)
63
108
  resolvedAot = options?.aot ?? config.command === 'build';
64
109
  sourceMaps = config.command === 'serve' || !!config.build?.sourcemap;
110
+ const { target, supported } = config.esbuild || {};
111
+ lowering = target || supported ? { target, supported } : null;
65
112
  const plugins = config.plugins ?? [];
66
113
  const sfc = plugins.findIndex(p => p.name === 'vite-plugin-pithy');
67
114
  if (sfc !== -1 && sfc > plugins.indexOf(plugin)) {
@@ -74,40 +121,49 @@ export function htmlTransformPlugin(options) {
74
121
  const normalizedId = id.split(/[?#]/, 1)[0];
75
122
  // Fast-path: skip files with no pithy tagged templates.
76
123
  // Check for html` (common case) or aliased html import from @pithyjs/core.
77
- if (!normalizedId.endsWith('.ts') && !normalizedId.endsWith('.pithy'))
124
+ const isPithy = normalizedId.endsWith('.pithy');
125
+ if (!normalizedId.endsWith('.ts') && !isPithy)
78
126
  return;
79
- if (!readsTemplates(code))
127
+ const reads = readsTemplates(code);
128
+ if (!reads && !(isPithy && lowering))
80
129
  return;
130
+ if (!reads)
131
+ return lowerPithy(code, null, normalizedId);
81
132
  const babelPluginOptions = {
82
133
  componentScopes: options?.componentScopes,
83
134
  aot: resolvedAot,
84
135
  strictAot: options?.strictAot,
85
136
  filename: normalizedId,
86
137
  };
87
- const result = babel.transformSync(code, {
138
+ const result = transformTypeScriptModule(code, {
88
139
  filename: normalizedId,
89
140
  plugins: [() => pithyBabelPlugin(babelPluginOptions)],
90
- presets: [
91
- [
92
- presetTypescript,
93
- {
94
- onlyRemoveTypeImports: true,
95
- },
96
- ],
97
- ],
98
- parserOpts: {
99
- sourceType: 'module',
100
- plugins: ['typescript'],
101
- },
102
141
  configFile: false,
103
142
  sourceMaps,
104
143
  });
105
- return {
144
+ const transformed = {
106
145
  code: result?.code ?? code,
107
146
  map: result?.map ?? null,
108
147
  };
148
+ return isPithy && lowering
149
+ ? lowerPithy(transformed.code, transformed.map, normalizedId)
150
+ : transformed;
109
151
  },
110
152
  };
153
+ async function lowerPithy(code, map, id) {
154
+ const { transformWithEsbuild } = await import('vite');
155
+ const lowered = await transformWithEsbuild(code, id, {
156
+ loader: 'js',
157
+ target: lowering?.target,
158
+ supported: {
159
+ 'dynamic-import': true,
160
+ 'import-meta': true,
161
+ ...lowering?.supported,
162
+ },
163
+ sourcemap: sourceMaps,
164
+ }, map ?? undefined);
165
+ return { code: lowered.code, map: lowered.map };
166
+ }
111
167
  return plugin;
112
168
  }
113
169
  //# sourceMappingURL=htmlTransform.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"htmlTransform.js","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAGF,OAAO,gBAEN,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EA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G,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5C,wDAAwD;YACxD,2EAA2E;YAC3E,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBACnE,OAAO;YACT,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;gBAAE,OAAO;YAElC,MAAM,kBAAkB,GAA4B;gBAClD,eAAe,EAAE,OAAO,EAAE,eAAe;gBACzC,GAAG,EAAE,WAAW;gBAChB,SAAS,EAAE,OAAO,EAAE,SAAS;gBAC7B,QAAQ,EAAE,YAAY;aACvB,CAAC;YAEF,MAAM,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE;gBACvC,QAAQ,EAAE,YAAY;gBACtB,OAAO,EAAE,CAAC,GAAG,EAAE,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;gBACrD,OAAO,EAAE;oBACP;wBACE,gBAAgB;wBAChB;4BACE,qBAAqB,EAAE,IAAI;yBAC5B;qBACF;iBACF;gBACD,UAAU,EAAE;oBACV,UAAU,EAAE,QAAQ;oBACpB,OAAO,EAAE,CAAC,YAAY,CAAC;iBACxB;gBACD,UAAU,EAAE,KAAK;gBACjB,UAAU;aACX,CAAC,CAAC;YAEH,OAAO;gBACL,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,IAAI;gBAC1B,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,IAAI;aACzB,CAAC;QACJ,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.html-transform-plugin\",\n \"title\": \"HTML Transform Vite Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel-based Vite plugin that transforms html`…` tagged templates and literal html() calls in .ts and compiled .pithy modules, with optional AOT compilation to eliminate runtime HTML parsing.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"htmlTransformAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport type { PluginOption, ResolvedConfig } from 'vite';\nimport pithyBabelPlugin, {\n type PithyBabelPluginOptions,\n} from '../babelPlugin/babelPlugin';\nimport type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers';\nimport * as babel from '@babel/core';\nimport { createRequire } from 'node:module';\n\n// Babel resolves preset names from the app, which may not see this package's deps.\nconst presetTypescript = createRequire(import.meta.url).resolve(\n '@babel/preset-typescript'\n);\n\n/**\n * Whether the template transform reads `code` at all: it holds an `html`\n * tagged template, or imports `html` from `@pithyjs/core` (an alias included).\n * Any other module skips Babel, so syntax only esbuild handles still builds.\n *\n * @param code - The module source.\n * @returns `true` when the transform parses it.\n */\nexport function readsTemplates(code: string): boolean {\n return (\n code.includes('html`') ||\n /import\\s*\\{[^}]*\\bhtml\\b[^}]*\\}\\s*from\\s+['\"]@pithyjs\\/core['\"]/.test(code)\n );\n}\n\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"HtmlTransformPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface HtmlTransformPluginOptions\"} */\nexport interface HtmlTransformPluginOptions {\n /** Map of component names to variables they inject into children's scope */\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: true in build mode, false in dev. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n}\n\n/**\n * Vite plugin that transforms `html\\`\\`` tagged templates and literal `html()` calls\n * in `.ts` and compiled `.pithy` modules using Babel.\n *\n * In build mode, templates are AOT-compiled to eliminate runtime HTML parsing.\n * In dev mode, tagged templates only get their context injected and still render\n * through the runtime compiler, unless `aot` is explicitly enabled.\n * `pithyPlugin()` must be listed before this plugin.\n *\n * @param options - Plugin configuration for AOT mode, strict AOT, and component scopes\n * @returns A Vite plugin that transforms html tagged templates\n *\n * @example\n * ```ts\n * import { htmlTransformPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [htmlTransformPlugin({ aot: true })],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"htmlTransformPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: HtmlTransformPluginOptions) => PluginOption\"} */\nexport function htmlTransformPlugin(\n options?: HtmlTransformPluginOptions\n): PluginOption {\n let resolvedAot = false;\n let sourceMaps = true;\n\n const plugin = {\n name: 'pithy:html-transform',\n enforce: 'pre' as const,\n\n configResolved(config: ResolvedConfig) {\n // Default: AOT enabled in build, disabled in dev (for faster HMR)\n resolvedAot = options?.aot ?? config.command === 'build';\n\n sourceMaps = config.command === 'serve' || !!config.build?.sourcemap;\n\n const plugins = config.plugins ?? [];\n const sfc = plugins.findIndex(p => p.name === 'vite-plugin-pithy');\n if (sfc !== -1 && sfc > plugins.indexOf(plugin)) {\n throw new Error(\n '[pithy:html-transform] pithyPlugin() must be listed before htmlTransformPlugin(), ' +\n 'so .pithy files reach the template transform already compiled.'\n );\n }\n },\n\n transform(code: string, id: string) {\n // Strip Vite query/hash suffixes (e.g. component.ts?import → component.ts)\n const normalizedId = id.split(/[?#]/, 1)[0];\n // Fast-path: skip files with no pithy tagged templates.\n // Check for html` (common case) or aliased html import from @pithyjs/core.\n if (!normalizedId.endsWith('.ts') && !normalizedId.endsWith('.pithy'))\n return;\n if (!readsTemplates(code)) return;\n\n const babelPluginOptions: PithyBabelPluginOptions = {\n componentScopes: options?.componentScopes,\n aot: resolvedAot,\n strictAot: options?.strictAot,\n filename: normalizedId,\n };\n\n const result = babel.transformSync(code, {\n filename: normalizedId,\n plugins: [() => pithyBabelPlugin(babelPluginOptions)],\n presets: [\n [\n presetTypescript,\n {\n onlyRemoveTypeImports: true,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript'],\n },\n configFile: false,\n sourceMaps,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map ?? null,\n };\n },\n };\n return plugin;\n}\n"]}
1
+ {"version":3,"file":"htmlTransform.js","sourceRoot":"","sources":["../../src/htmlTransform/htmlTransform.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;EAcE;AAGF,OAAO,gBAEN,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,KAAK,MAAM,aAAa,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,CACL,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QACtB,uCAAuC,CAAC,IAAI,CAAC,IAAI,CAAC;QAClD,iEAAiE,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7E,CAAC;AACJ,CAAC;AAED,MAAM,kBAAkB,GAAqC;IAC3D;QACE,YAAY;QACZ,mBAAmB;QACnB,wBAAwB;QACxB,4BAA4B;KAC7B;IACD;QACE,YAAY;QACZ,CAAC,YAAY,EAAE,EAAE,CAAC;QAClB,wBAAwB;QACxB,4BAA4B;KAC7B;CACF,CAAC;AAEF,MAAM,wBAAwB,GAAG,GAAoB,EAAE,CAAC,CAAC;IACvD,OAAO,EAAE;QACP,yBAAyB,CAAC,IAAI;YAC5B,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,KAAK,MAAM;gBAAE,IAAI,CAAC,MAAM,EAAE,CAAC;QACrD,CAAC;KACF;CACF,CAAC,CAAC;AAEH,MAAM,QAAQ,GAAG,CAAC,GAAY,EAAU,EAAE,CAAE,GAAwB,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAE/E,MAAM,UAAU,yBAAyB,CACvC,IAAY,EACZ,OAAmD;IAEnD,IAAI,UAAmB,CAAC;IACxB,KAAK,MAAM,OAAO,IAAI,kBAAkB,EAAE,CAAC;QACzC,IAAI,CAAC;YACH,OAAO,K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AC,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;gBACrD,UAAU,EAAE,KAAK;gBACjB,UAAU;aACX,CAAC,CAAC;YAEH,MAAM,WAAW,GAAG;gBAClB,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,IAAI;gBAC1B,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,IAAI;aACzB,CAAC;YACF,OAAO,OAAO,IAAI,QAAQ;gBACxB,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,GAAG,EAAE,YAAY,CAAC;gBAC7D,CAAC,CAAC,WAAW,CAAC;QAClB,CAAC;KACF,CAAC;IAEF,KAAK,UAAU,UAAU,CACvB,IAAY,EACZ,GAAwC,EACxC,EAAU;QAEV,MAAM,EAAE,oBAAoB,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;QACtD,MAAM,OAAO,GAAG,MAAM,oBAAoB,CACxC,IAAI,EACJ,EAAE,EACF;YACE,MAAM,EAAE,IAAI;YACZ,MAAM,EAAE,QAAQ,EAAE,MAAM;YACxB,SAAS,EAAE;gBACT,gBAAgB,EAAE,IAAI;gBACtB,aAAa,EAAE,IAAI;gBACnB,GAAG,QAAQ,EAAE,SAAS;aACvB;YACD,SAAS,EAAE,UAAU;SACtB,EACD,GAAG,IAAI,SAAS,CACjB,CAAC;QACF,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC;IAClD,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.vite.html-transform-plugin\",\n \"title\": \"HTML Transform Vite Plugin\",\n \"category\": \"plugin\",\n \"description\": \"Babel-based Vite plugin that transforms html`…` tagged templates and literal html() calls in .ts and compiled .pithy modules, with optional AOT compilation to eliminate runtime HTML parsing.\",\n \"since\": \"0.0.1\",\n \"stability\": \"stable\",\n \"testing\": {\n \"unit\": { \"required\": true, \"covered\": true, \"file\": \"htmlTransformAot.test.ts\" },\n \"integration\": { \"required\": true, \"covered\": false },\n \"e2e\": { \"required\": false, \"covered\": false }\n }\n}\n*/\n\nimport type { ESBuildOptions, PluginOption, ResolvedConfig } from 'vite';\nimport pithyBabelPlugin, {\n type PithyBabelPluginOptions,\n} from '../babelPlugin/babelPlugin';\nimport type { ComponentScopesMap } from '../babelPlugin/extractUsedIdentifiers';\nimport * as babel from '@babel/core';\n\n/**\n * Whether the template transform reads `code` at all: it holds an `html`\n * tagged template, or imports `html` from `@pithyjs/core` (an alias included).\n * Any other module skips Babel, so syntax only esbuild handles still builds.\n *\n * @param code - The module source.\n * @returns `true` when the transform parses it.\n */\nexport function readsTemplates(code: string): boolean {\n return (\n code.includes('html`') ||\n /\\bhtml\\s*(?:!|\\s+as\\s+[\\w.]+)?[\\s)]*`/.test(code) ||\n /import\\s*\\{[^}]*\\bhtml\\b[^}]*\\}\\s*from\\s+['\"]@pithyjs\\/core['\"]/.test(code)\n );\n}\n\nconst DECORATOR_DIALECTS: babel.ParserOptions['plugins'][] = [\n [\n 'typescript',\n 'decorators-legacy',\n 'decoratorAutoAccessors',\n 'explicitResourceManagement',\n ],\n [\n 'typescript',\n ['decorators', {}],\n 'decoratorAutoAccessors',\n 'explicitResourceManagement',\n ],\n];\n\nconst dropTypeOnlyImportEquals = (): babel.PluginObj => ({\n visitor: {\n TSImportEqualsDeclaration(path) {\n if (path.node.importKind === 'type') path.remove();\n },\n },\n});\n\nconst parsedTo = (err: unknown): number => (err as { pos?: number }).pos ?? -1;\n\nexport function transformTypeScriptModule(\n code: string,\n options: Omit<babel.TransformOptions, 'parserOpts'>\n): babel.BabelFileResult | null {\n let parseError: unknown;\n for (const plugins of DECORATOR_DIALECTS) {\n try {\n return babel.transformSync(code, {\n ...options,\n plugins: [dropTypeOnlyImportEquals, ...(options.plugins ?? [])],\n parserOpts: {\n sourceType: 'module',\n plugins,\n createParenthesizedExpressions: true,\n },\n });\n } catch (err) {\n if ((err as { code?: string }).code !== 'BABEL_PARSE_ERROR') throw err;\n if (parseError === undefined || parsedTo(err) > parsedTo(parseError))\n parseError = err;\n }\n }\n throw parseError;\n}\n\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"HtmlTransformPluginOptions\",\"stability\":\"stable\",\"signature\":\"interface HtmlTransformPluginOptions\"} */\nexport interface HtmlTransformPluginOptions {\n /** Map of component names to variables they inject into children's scope */\n componentScopes?: ComponentScopesMap;\n /** Enable AOT template compilation. Default: true in build mode, false in dev. */\n aot?: boolean;\n /** Fail the build if any template falls back to JIT, i.e. any `[pithy:aot:jit-fallback]` report. Default: false. */\n strictAot?: boolean;\n}\n\n/**\n * Vite plugin that transforms `html\\`\\`` tagged templates and literal `html()` calls\n * in `.ts` and compiled `.pithy` modules using Babel.\n *\n * In build mode, templates are AOT-compiled to eliminate runtime HTML parsing.\n * In dev mode, tagged templates only get their context injected and still render\n * through the runtime compiler, unless `aot` is explicitly enabled.\n * `pithyPlugin()` must be listed before this plugin.\n *\n * @param options - Plugin configuration for AOT mode, strict AOT, and component scopes\n * @returns A Vite plugin that transforms html tagged templates\n *\n * @example\n * ```ts\n * import { htmlTransformPlugin } from '@pithyjs/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [htmlTransformPlugin({ aot: true })],\n * });\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.vite.html-transform-plugin\",\"name\":\"htmlTransformPlugin\",\"stability\":\"stable\",\"signature\":\"(options?: HtmlTransformPluginOptions) => PluginOption\"} */\nexport function htmlTransformPlugin(\n options?: HtmlTransformPluginOptions\n): PluginOption {\n let resolvedAot = false;\n let sourceMaps = true;\n let lowering: Pick<ESBuildOptions, 'target' | 'supported'> | null = null;\n\n const plugin = {\n name: 'pithy:html-transform',\n enforce: 'pre' as const,\n\n configResolved(config: ResolvedConfig) {\n // Default: AOT enabled in build, disabled in dev (for faster HMR)\n resolvedAot = options?.aot ?? config.command === 'build';\n\n sourceMaps = config.command === 'serve' || !!config.build?.sourcemap;\n\n const { target, supported } = config.esbuild || {};\n lowering = target || supported ? { target, supported } : null;\n\n const plugins = config.plugins ?? [];\n const sfc = plugins.findIndex(p => p.name === 'vite-plugin-pithy');\n if (sfc !== -1 && sfc > plugins.indexOf(plugin)) {\n throw new Error(\n '[pithy:html-transform] pithyPlugin() must be listed before htmlTransformPlugin(), ' +\n 'so .pithy files reach the template transform already compiled.'\n );\n }\n },\n\n transform(code: string, id: string) {\n // Strip Vite query/hash suffixes (e.g. component.ts?import → component.ts)\n const normalizedId = id.split(/[?#]/, 1)[0];\n // Fast-path: skip files with no pithy tagged templates.\n // Check for html` (common case) or aliased html import from @pithyjs/core.\n const isPithy = normalizedId.endsWith('.pithy');\n if (!normalizedId.endsWith('.ts') && !isPithy) return;\n const reads = readsTemplates(code);\n if (!reads && !(isPithy && lowering)) return;\n if (!reads) return lowerPithy(code, null, normalizedId);\n\n const babelPluginOptions: PithyBabelPluginOptions = {\n componentScopes: options?.componentScopes,\n aot: resolvedAot,\n strictAot: options?.strictAot,\n filename: normalizedId,\n };\n\n const result = transformTypeScriptModule(code, {\n filename: normalizedId,\n plugins: [() => pithyBabelPlugin(babelPluginOptions)],\n configFile: false,\n sourceMaps,\n });\n\n const transformed = {\n code: result?.code ?? code,\n map: result?.map ?? null,\n };\n return isPithy && lowering\n ? lowerPithy(transformed.code, transformed.map, normalizedId)\n : transformed;\n },\n };\n\n async function lowerPithy(\n code: string,\n map: babel.BabelFileResult['map'] | null,\n id: string\n ) {\n const { transformWithEsbuild } = await import('vite');\n const lowered = await transformWithEsbuild(\n code,\n id,\n {\n loader: 'js',\n target: lowering?.target,\n supported: {\n 'dynamic-import': true,\n 'import-meta': true,\n ...lowering?.supported,\n },\n sourcemap: sourceMaps,\n },\n map ?? undefined\n );\n return { code: lowered.code, map: lowered.map };\n }\n\n return plugin;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithyjs/vite-plugin",
3
- "version": "0.2.0-beta.26",
3
+ "version": "0.2.0-beta.28",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/PithyJS/pithyjs.git",
@@ -29,14 +29,13 @@
29
29
  "dependencies": {
30
30
  "@babel/core": "^7.27.4",
31
31
  "@babel/parser": "^7.27.5",
32
- "@babel/preset-typescript": "^7.27.1",
33
32
  "@babel/traverse": "^7.27.4",
34
33
  "@babel/types": "^7.27.3",
35
34
  "fast-glob": "^3.3.0",
36
35
  "parse5": "^7.3.0",
37
- "@pithyjs/compiler": "0.1.0-beta.12",
36
+ "@pithyjs/compiler": "0.1.0-beta.13",
38
37
  "@pithyjs/design-system": "0.1.0-beta.12",
39
- "@pithyjs/router": "0.2.0-beta.24",
38
+ "@pithyjs/router": "0.2.0-beta.25",
40
39
  "@pithyjs/shared": "0.1.0-beta.4"
41
40
  },
42
41
  "devDependencies": {