@pithyjs/core 0.1.0-beta.22 → 0.1.0-beta.23

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.
Files changed (53) hide show
  1. package/README.md +4 -0
  2. package/dist/compile/bindSwitchCases.d.ts.map +1 -1
  3. package/dist/compile/bindSwitchCases.js +2 -1
  4. package/dist/compile/bindSwitchCases.js.map +1 -1
  5. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  6. package/dist/compile/binds/bindComponentsTags.js +20 -68
  7. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  8. package/dist/compile/binds/bindDefaultTwoWay.d.ts.map +1 -1
  9. package/dist/compile/binds/bindDefaultTwoWay.js +2 -1
  10. package/dist/compile/binds/bindDefaultTwoWay.js.map +1 -1
  11. package/dist/compile/binds/bindErrorBoundary.d.ts +2 -0
  12. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  13. package/dist/compile/binds/bindErrorBoundary.js +13 -5
  14. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  15. package/dist/compile/binds/propNames.d.ts +5 -1
  16. package/dist/compile/binds/propNames.d.ts.map +1 -1
  17. package/dist/compile/binds/propNames.js +36 -1
  18. package/dist/compile/binds/propNames.js.map +1 -1
  19. package/dist/compile/binds/propWarnings.d.ts +11 -0
  20. package/dist/compile/binds/propWarnings.d.ts.map +1 -0
  21. package/dist/compile/binds/propWarnings.js +43 -0
  22. package/dist/compile/binds/propWarnings.js.map +1 -0
  23. package/dist/compile/contentProjection.d.ts.map +1 -1
  24. package/dist/compile/contentProjection.js +6 -6
  25. package/dist/compile/contentProjection.js.map +1 -1
  26. package/dist/compile/evalDiagnostics.d.ts +5 -0
  27. package/dist/compile/evalDiagnostics.d.ts.map +1 -1
  28. package/dist/compile/evalDiagnostics.js +5 -0
  29. package/dist/compile/evalDiagnostics.js.map +1 -1
  30. package/dist/compile/forLoops/createLoopManager.d.ts +3 -1
  31. package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
  32. package/dist/compile/forLoops/createLoopManager.js +9 -5
  33. package/dist/compile/forLoops/createLoopManager.js.map +1 -1
  34. package/dist/compile/ssrCrashes.d.ts +6 -0
  35. package/dist/compile/ssrCrashes.d.ts.map +1 -1
  36. package/dist/compile/ssrCrashes.js +17 -1
  37. package/dist/compile/ssrCrashes.js.map +1 -1
  38. package/dist/runtime/applyBindings.js +7 -2
  39. package/dist/runtime/applyBindings.js.map +1 -1
  40. package/dist/runtime/bindings/applyComponent.d.ts +3 -1
  41. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  42. package/dist/runtime/bindings/applyComponent.js +11 -3
  43. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  44. package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
  45. package/dist/runtime/bindings/applyStructural.js +19 -5
  46. package/dist/runtime/bindings/applyStructural.js.map +1 -1
  47. package/dist/runtime/bindings/types.d.ts +2 -0
  48. package/dist/runtime/bindings/types.d.ts.map +1 -1
  49. package/dist/runtime/bindings/types.js.map +1 -1
  50. package/dist/types/globals.d.ts +2 -0
  51. package/dist/types/globals.d.ts.map +1 -1
  52. package/dist/types/globals.js.map +1 -1
  53. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"contentProjection.js","sourceRoot":"","sources":["../../src/compile/contentProjection.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OA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AAiE;QACjE,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;YAClB,KAAK,MAAM,IAAI,IAAI,aAAa,EAAE,CAAC;gBACjC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;oBACpB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;YACD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;gBAClE,OAAO,CAAC,GAAG,CAAC,yCAAyC,IAAI,GAAG,CAAC,CAAC;YAChE,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;YAClE,OAAO,CAAC,GAAG,CACT,6CAA6C,aAAa,CAAC,MAAM,oBAAoB,IAAI,GAAG,CAC7F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,2BAA2B;IAC3B,2EAA2E;IAC3E,yEAAyE;IACzE,6EAA6E;IAC7E,sEAAsE;IACtE,uEAAuE;IACvE,qEAAqE;IACrE,gDAAgD;AAClD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.content-projection\",\n \"title\": \"Content Projection System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { PithyNode } from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\nimport { bindStructuralDirectives } from './compileTemplate';\nimport { nodeExpando } from './nodeExpando';\nimport {\n bindErrorBoundary,\n insertBesideHidden,\n withSlotBoundary,\n isHiddenByBoundary,\n} from './binds/bindErrorBoundary';\nimport { pithyGlobals } from '../types/globals';\nimport { trimBlankEdges } from './trimBlankEdges';\nimport { withinRender } from './ssrCrashes';\n\n/**\n * SlotMap contains renderer functions for each slot name.\n * Each entry is a factory that returns a DocumentFragment of the slot's content.\n */\nexport type SlotMap = Map<\n string,\n (disposers?: (() => void)[], anchor?: Node) => DocumentFragment\n>;\n\n/**\n * SlotDef describes a slot anchor and its fallback content\n */\nexport type FallbackFactory = () => HTMLElement | DocumentFragment | undefined;\n\nexport interface SlotDef {\n name: string;\n anchor: Comment;\n fallbackFactory?: FallbackFactory;\n}\n\ninterface ProjectionExpando {\n __slotName?: string;\n __fallbackFactory?: FallbackFactory;\n __projectionProcessed?: boolean;\n __projectedContent?: boolean;\n}\n\nfunction expando(node: Node): ProjectionExpando {\n return node as Node & ProjectionExpando;\n}\n\nconst outerSlotMaps = new WeakMap<SlotMap, SlotMap>();\n\nfunction slotMapOf(ctx: Record<string, unknown>): SlotMap | undefined {\n return ('__slotMap' in ctx ? ctx.__slotMap : undefined) as\n | SlotMap\n | undefined;\n}\n\n/**\n * The slot map of the template the children behind `slotMap` were written in:\n * what a `<slot>` among those children receives.\n */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"outerSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap | undefined) => SlotMap | undefined\"} */\nexport function outerSlotMap(\n slotMap: SlotMap | undefined\n): SlotMap | undefined {\n return slotMap && outerSlotMaps.get(slotMap);\n}\n\n/** Records `ctx`'s slot map as what a `<slot>` among `slotMap`'s children receives. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"linkOuterSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap, ctx: Record<string, unknown>) => void\"} */\nexport function linkOuterSlotMap(\n slotMap: SlotMap,\n ctx: Record<string, unknown>\n): void {\n const outer = slotMapOf(ctx);\n if (outer) outerSlotMaps.set(slotMap, outer);\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"collectSlotMap\",\"stability\":\"stable\",\"signature\":\"(children: PithyNode[], parentContext: Record<string, any>, host?: Element) => SlotMap\"} */\nexport function collectSlotMap(\n children: PithyNode[],\n parentContext: Record<string, unknown>,\n host?: Element\n): SlotMap {\n const slotMap: SlotMap = new Map();\n const slotGroups = new Map<string, PithyNode[]>();\n linkOuterSlotMap(slotMap, parentContext);\n const outer = slotMapOf(parentContext);\n\n // Group children by slot attribute\n for (const child of children) {\n const slotName = child.directives?.slot || ''; // default slot if no slot attribute\n\n if (!slotGroups.has(slotName)) {\n slotGroups.set(slotName, []);\n }\n slotGroups.get(slotName)!.push(child);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.type === 'text' ? (node.textContent ?? '') : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n\n // Validate slot usage in DEV mode\n if (import.meta.env?.DEV) {\n const slotNames = Array.from(slotGroups.keys());\n const duplicateSlots = slotNames.filter(\n name => name !== '' && slotGroups.get(name)!.length > 1\n );\n if (duplicateSlots.length > 0) {\n console.warn(\n `[ContentProjection] Multiple content nodes targeting the same slot. This is allowed but may indicate a mistake:`,\n duplicateSlots\n );\n }\n }\n\n // Create renderer functions for each slot group.\n // NOTE: We intentionally do NOT cache or clone DocumentFragments here.\n // Using fragment caching + cloneNode(true) would strip custom JS properties\n // like __pithyCtx that binders rely on to resolve projected content\n // expressions (including interpolation, [class], and [attr] bindings)\n // against the *parent* component's context.\n //\n // This behavior is relied upon by regression tests that exercise projected\n // nodes containing such bindings; changing this to reuse or clone\n // fragments will cause those tests to fail and break content projection.\n // pithyTreeToDom is cheap (just creates DOM nodes), so recreating is fine.\n\n for (const [slotName, nodes] of slotGroups) {\n // Capture nodes and context in closure for stable reference\n const capturedNodes = nodes;\n const capturedContext = parentContext;\n\n const render = (\n disposers: (() => void)[] = [],\n at?: Node\n ): DocumentFragment => {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Rendering slot \"${slotName}\" with ${capturedNodes.length} nodes`\n );\n }\n\n const fragment = pithyTreeToDom(capturedNodes, capturedContext);\n // As the AOT renderer does: a branch in the content then finds a boundary\n // the receiver wraps its `<slot>` in.\n withSlotBoundary(at, host, () =>\n withinRender(() => {\n bindStructuralDirectives(\n capturedNodes,\n fragment,\n capturedContext,\n disposers\n );\n bindErrorBoundary(fragment, capturedContext, disposers);\n return fragment;\n })\n );\n // A `<slot>` passed through: the receiving component has already looked for its slots.\n const passed = extractSlotDefs(fragment);\n if (passed.length) mountProjection(passed, outer ?? new Map(), disposers);\n nodeExpando(fragment).__pithyCtx = capturedContext;\n return fragment;\n };\n\n slotMap.set(slotName, render);\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Collected SlotMap with slots:`,\n Array.from(slotMap.keys())\n );\n }\n return slotMap;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"extractSlotDefs\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment) => SlotDef[]\"} */\nexport function extractSlotDefs(fragment: DocumentFragment): SlotDef[] {\n const slotDefs: SlotDef[] = [];\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT, {\n acceptNode: node => {\n const comment = node as Comment;\n return comment.textContent?.startsWith('slot:')\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_REJECT;\n },\n });\n\n let node: Comment | null;\n while ((node = walker.nextNode() as Comment | null)) {\n // Inside a component tag, the slot is that component's content to place.\n if (inComponentTag(node)) continue;\n const slotName = expando(node).__slotName || '';\n const fallbackFactory = expando(node).__fallbackFactory;\n\n slotDefs.push({\n name: slotName,\n anchor: node,\n fallbackFactory,\n });\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Extracted ${slotDefs.length} slot definitions`\n );\n }\n return slotDefs;\n}\n\n/** Whether `node` is inside content a `<slot>` projected. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"inProjectedContent\",\"stability\":\"internal\",\"signature\":\"(node: Node) => boolean\"} */\nexport function inProjectedContent(node: Node): boolean {\n for (let n: Node | null = node; n; n = n.parentNode)\n if (expando(n).__projectedContent) return true;\n return false;\n}\n\nfunction inComponentTag(node: Node): boolean {\n for (let el = node.parentElement; el; el = el.parentElement)\n if (nodeExpando(el).__pithyNode?.isComponent) return true;\n return false;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"mountProjection\",\"stability\":\"stable\",\"signature\":\"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void\"} */\nexport function mountProjection(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n // A slot's content is rendered and then inserted: one render transaction.\n withinRender(() => mountSlots(slotDefs, slotMap, disposers));\n}\n\nfunction mountSlots(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n for (const slotDef of slotDefs) {\n const { name, anchor, fallbackFactory } = slotDef;\n const renderer = slotMap.get(name);\n\n // Skip if this slot has already been processed\n if (expando(anchor).__projectionProcessed) {\n continue;\n }\n\n // Mark this slot as processed to prevent multiple passes\n expando(anchor).__projectionProcessed = true;\n\n const parent = anchor.parentNode;\n // A crash in an earlier slot can have hidden this anchor behind a fallback.\n if (!parent && !isHiddenByBoundary(anchor)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ContentProjection] Slot anchor \"${name}\" has no parent node - skipping`\n );\n }\n continue;\n }\n\n // Determine which content to render\n let contentFragment: HTMLElement | DocumentFragment | null = null;\n let isProjectedContent = false;\n\n if (renderer) {\n // Use projected content\n contentFragment = renderer(disposers, anchor);\n isProjectedContent = true;\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting projected content for slot \"${name}\"`\n );\n }\n } else if (fallbackFactory) {\n // Use fallback content\n contentFragment = fallbackFactory() ?? null;\n const slotNode = nodeExpando(anchor).__pithyNode;\n if (\n contentFragment instanceof DocumentFragment &&\n slotNode?.fallbackChildren\n ) {\n const fallbackCtx = nodeExpando(anchor).__pithyCtx ?? {};\n const fallbackFragment = contentFragment;\n const fallbackNodes = slotNode.fallbackChildren;\n withinRender(() => {\n bindStructuralDirectives(\n fallbackNodes,\n fallbackFragment,\n fallbackCtx,\n disposers\n );\n bindErrorBoundary(fallbackFragment, fallbackCtx, disposers);\n });\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting fallback content for slot \"${name}\"`\n );\n }\n } else {\n // No content to mount\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] No content for slot \"${name}\"`);\n }\n continue;\n }\n\n // Validate content\n if (!contentFragment || contentFragment.childNodes.length === 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Empty content for slot \"${name}\" - skipping`\n );\n }\n continue;\n }\n\n // CRITICAL: Collect nodes BEFORE inserting into DOM (for cleanup tracking)\n // Once inserted, the fragment's childNodes will be empty\n const nodesToInsert: Node[] = Array.from(contentFragment.childNodes);\n\n // Mark nodes for tracking\n for (const node of nodesToInsert) {\n expando(node).__projectedContent = isProjectedContent;\n expando(node).__slotName = name;\n }\n\n // Find and remove any existing content for this slot\n const existingNodes: Node[] = [];\n let current = anchor.nextSibling;\n\n while (current) {\n // Stop if we hit another slot anchor\n if (\n current.nodeType === Node.COMMENT_NODE &&\n (current as Comment).textContent?.startsWith('slot:')\n ) {\n break;\n }\n\n // A sibling no projection marked is the component's own markup.\n const meta = expando(current);\n if (meta.__projectedContent === undefined || meta.__slotName !== name) {\n break;\n }\n existingNodes.push(current);\n\n current = current.nextSibling;\n }\n\n // Simple diffing: only replace if content appears different\n // Compare node count and types as a basic heuristic\n const shouldReplace =\n existingNodes.length !== nodesToInsert.length ||\n existingNodes.some(\n (node, i) => node.nodeType !== nodesToInsert[i]?.nodeType\n );\n\n if (!shouldReplace && existingNodes.length > 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Content for slot \"${name}\" unchanged - skipping replacement`\n );\n }\n continue;\n }\n\n // Remove existing content\n for (const node of existingNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n\n // Insert new content after the anchor comment\n if (!insertBesideHidden(anchor, contentFragment))\n parent?.insertBefore(contentFragment, anchor.nextSibling);\n\n // Track cleanup - remove projected nodes when component unmounts\n disposers.push(() => {\n for (const node of nodesToInsert) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] Cleaned up slot \"${name}\"`);\n }\n });\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Successfully mounted ${nodesToInsert.length} nodes for slot \"${name}\"`\n );\n }\n }\n\n // DEV: Validate slot usage\n // NOTE: We intentionally do NOT warn about unmatched projected slots here.\n // When a component uses @if/@else with different <slot> elements in each\n // branch (e.g., Show has <slot> in @if and <slot name=\"fallback\"> in @else),\n // the currently-rendered branch may not include all slot targets. The\n // projected \"fallback\" content is legitimate — it will be mounted when\n // the @else branch activates. Warnings here would be false positives\n // and fire repeatedly on every reactive toggle.\n}\n"]}
1
+ {"version":3,"file":"contentProjection.js","sourceRoot":"","sources":["../../src/compile/contentProjection.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAa,iBAAiB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,kBAAk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,CAAC,eAAe,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QAE5D,iEAAiE;QACjE,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;YAClB,KAAK,MAAM,IAAI,IAAI,aAAa,EAAE,CAAC;gBACjC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;oBACpB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;YACD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;gBAClE,OAAO,CAAC,GAAG,CAAC,yCAAyC,IAAI,GAAG,CAAC,CAAC;YAChE,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;YAClE,OAAO,CAAC,GAAG,CACT,6CAA6C,aAAa,CAAC,MAAM,oBAAoB,IAAI,GAAG,CAC7F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,2BAA2B;IAC3B,2EAA2E;IAC3E,yEAAyE;IACzE,6EAA6E;IAC7E,sEAAsE;IACtE,uEAAuE;IACvE,qEAAqE;IACrE,gDAAgD;AAClD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.content-projection\",\n \"title\": \"Content Projection System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { PithyNode, sharedSlotMessage, sharedSlots } from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\nimport { bindStructuralDirectives } from './compileTemplate';\nimport { nodeExpando } from './nodeExpando';\nimport {\n bindErrorBoundary,\n insertBesideHidden,\n withSlotBoundary,\n isHiddenByBoundary,\n} from './binds/bindErrorBoundary';\nimport { pithyGlobals } from '../types/globals';\nimport { trimBlankEdges } from './trimBlankEdges';\nimport { withinRender } from './ssrCrashes';\n\n/**\n * SlotMap contains renderer functions for each slot name.\n * Each entry is a factory that returns a DocumentFragment of the slot's content.\n */\nexport type SlotMap = Map<\n string,\n (disposers?: (() => void)[], anchor?: Node) => DocumentFragment\n>;\n\n/**\n * SlotDef describes a slot anchor and its fallback content\n */\nexport type FallbackFactory = () => HTMLElement | DocumentFragment | undefined;\n\nexport interface SlotDef {\n name: string;\n anchor: Comment;\n fallbackFactory?: FallbackFactory;\n}\n\ninterface ProjectionExpando {\n __slotName?: string;\n __fallbackFactory?: FallbackFactory;\n __projectionProcessed?: boolean;\n __projectedContent?: boolean;\n}\n\nfunction expando(node: Node): ProjectionExpando {\n return node as Node & ProjectionExpando;\n}\n\nconst outerSlotMaps = new WeakMap<SlotMap, SlotMap>();\n\nfunction slotMapOf(ctx: Record<string, unknown>): SlotMap | undefined {\n return ('__slotMap' in ctx ? ctx.__slotMap : undefined) as\n | SlotMap\n | undefined;\n}\n\n/**\n * The slot map of the template the children behind `slotMap` were written in:\n * what a `<slot>` among those children receives.\n */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"outerSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap | undefined) => SlotMap | undefined\"} */\nexport function outerSlotMap(\n slotMap: SlotMap | undefined\n): SlotMap | undefined {\n return slotMap && outerSlotMaps.get(slotMap);\n}\n\n/** Records `ctx`'s slot map as what a `<slot>` among `slotMap`'s children receives. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"linkOuterSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap, ctx: Record<string, unknown>) => void\"} */\nexport function linkOuterSlotMap(\n slotMap: SlotMap,\n ctx: Record<string, unknown>\n): void {\n const outer = slotMapOf(ctx);\n if (outer) outerSlotMaps.set(slotMap, outer);\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"collectSlotMap\",\"stability\":\"stable\",\"signature\":\"(children: PithyNode[], parentContext: Record<string, any>, host?: Element) => SlotMap\"} */\nexport function collectSlotMap(\n children: PithyNode[],\n parentContext: Record<string, unknown>,\n host?: Element\n): SlotMap {\n const slotMap: SlotMap = new Map();\n const slotGroups = new Map<string, PithyNode[]>();\n linkOuterSlotMap(slotMap, parentContext);\n const outer = slotMapOf(parentContext);\n\n // Group children by slot attribute\n for (const child of children) {\n const slotName = child.directives?.slot || ''; // default slot if no slot attribute\n\n if (!slotGroups.has(slotName)) {\n slotGroups.set(slotName, []);\n }\n slotGroups.get(slotName)!.push(child);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.type === 'text' ? (node.textContent ?? '') : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n\n if (import.meta.env?.DEV) {\n const tag =\n (host && nodeExpando(host).__pithyNode?.originalTagName) ??\n host?.localName ??\n 'component';\n for (const name of sharedSlots(children))\n console.warn(`[PithyJS] ${sharedSlotMessage(tag, name)}`);\n }\n\n // Create renderer functions for each slot group.\n // NOTE: We intentionally do NOT cache or clone DocumentFragments here.\n // Using fragment caching + cloneNode(true) would strip custom JS properties\n // like __pithyCtx that binders rely on to resolve projected content\n // expressions (including interpolation, [class], and [attr] bindings)\n // against the *parent* component's context.\n //\n // This behavior is relied upon by regression tests that exercise projected\n // nodes containing such bindings; changing this to reuse or clone\n // fragments will cause those tests to fail and break content projection.\n // pithyTreeToDom is cheap (just creates DOM nodes), so recreating is fine.\n\n for (const [slotName, nodes] of slotGroups) {\n // Capture nodes and context in closure for stable reference\n const capturedNodes = nodes;\n const capturedContext = parentContext;\n\n const render = (\n disposers: (() => void)[] = [],\n at?: Node\n ): DocumentFragment => {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Rendering slot \"${slotName}\" with ${capturedNodes.length} nodes`\n );\n }\n\n const fragment = pithyTreeToDom(capturedNodes, capturedContext);\n // As the AOT renderer does: a branch in the content then finds a boundary\n // the receiver wraps its `<slot>` in.\n withSlotBoundary(at, host, () =>\n withinRender(() => {\n bindStructuralDirectives(\n capturedNodes,\n fragment,\n capturedContext,\n disposers\n );\n bindErrorBoundary(fragment, capturedContext, disposers);\n return fragment;\n })\n );\n // A `<slot>` passed through: the receiving component has already looked for its slots.\n const passed = extractSlotDefs(fragment);\n if (passed.length) mountProjection(passed, outer ?? new Map(), disposers);\n nodeExpando(fragment).__pithyCtx = capturedContext;\n return fragment;\n };\n\n slotMap.set(slotName, render);\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Collected SlotMap with slots:`,\n Array.from(slotMap.keys())\n );\n }\n return slotMap;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"extractSlotDefs\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment) => SlotDef[]\"} */\nexport function extractSlotDefs(fragment: DocumentFragment): SlotDef[] {\n const slotDefs: SlotDef[] = [];\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT, {\n acceptNode: node => {\n const comment = node as Comment;\n return comment.textContent?.startsWith('slot:')\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_REJECT;\n },\n });\n\n let node: Comment | null;\n while ((node = walker.nextNode() as Comment | null)) {\n // Inside a component tag, the slot is that component's content to place.\n if (inComponentTag(node)) continue;\n const slotName = expando(node).__slotName || '';\n const fallbackFactory = expando(node).__fallbackFactory;\n\n slotDefs.push({\n name: slotName,\n anchor: node,\n fallbackFactory,\n });\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Extracted ${slotDefs.length} slot definitions`\n );\n }\n return slotDefs;\n}\n\n/** Whether `node` is inside content a `<slot>` projected. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"inProjectedContent\",\"stability\":\"internal\",\"signature\":\"(node: Node) => boolean\"} */\nexport function inProjectedContent(node: Node): boolean {\n for (let n: Node | null = node; n; n = n.parentNode)\n if (expando(n).__projectedContent) return true;\n return false;\n}\n\nfunction inComponentTag(node: Node): boolean {\n for (let el = node.parentElement; el; el = el.parentElement)\n if (nodeExpando(el).__pithyNode?.isComponent) return true;\n return false;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"mountProjection\",\"stability\":\"stable\",\"signature\":\"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void\"} */\nexport function mountProjection(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n // A slot's content is rendered and then inserted: one render transaction.\n withinRender(() => mountSlots(slotDefs, slotMap, disposers));\n}\n\nfunction mountSlots(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n for (const slotDef of slotDefs) {\n const { name, anchor, fallbackFactory } = slotDef;\n const renderer = slotMap.get(name);\n\n // Skip if this slot has already been processed\n if (expando(anchor).__projectionProcessed) {\n continue;\n }\n\n // Mark this slot as processed to prevent multiple passes\n expando(anchor).__projectionProcessed = true;\n\n const parent = anchor.parentNode;\n // A crash in an earlier slot can have hidden this anchor behind a fallback.\n if (!parent && !isHiddenByBoundary(anchor)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ContentProjection] Slot anchor \"${name}\" has no parent node - skipping`\n );\n }\n continue;\n }\n\n // Determine which content to render\n let contentFragment: HTMLElement | DocumentFragment | null = null;\n let isProjectedContent = false;\n\n if (renderer) {\n // Use projected content\n contentFragment = renderer(disposers, anchor);\n isProjectedContent = true;\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting projected content for slot \"${name}\"`\n );\n }\n } else if (fallbackFactory) {\n // Use fallback content\n contentFragment = fallbackFactory() ?? null;\n const slotNode = nodeExpando(anchor).__pithyNode;\n if (\n contentFragment instanceof DocumentFragment &&\n slotNode?.fallbackChildren\n ) {\n const fallbackCtx = nodeExpando(anchor).__pithyCtx ?? {};\n const fallbackFragment = contentFragment;\n const fallbackNodes = slotNode.fallbackChildren;\n withinRender(() => {\n bindStructuralDirectives(\n fallbackNodes,\n fallbackFragment,\n fallbackCtx,\n disposers\n );\n bindErrorBoundary(fallbackFragment, fallbackCtx, disposers);\n });\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting fallback content for slot \"${name}\"`\n );\n }\n } else {\n // No content to mount\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] No content for slot \"${name}\"`);\n }\n continue;\n }\n\n // Validate content\n if (!contentFragment || contentFragment.childNodes.length === 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Empty content for slot \"${name}\" - skipping`\n );\n }\n continue;\n }\n\n // CRITICAL: Collect nodes BEFORE inserting into DOM (for cleanup tracking)\n // Once inserted, the fragment's childNodes will be empty\n const nodesToInsert: Node[] = Array.from(contentFragment.childNodes);\n\n // Mark nodes for tracking\n for (const node of nodesToInsert) {\n expando(node).__projectedContent = isProjectedContent;\n expando(node).__slotName = name;\n }\n\n // Find and remove any existing content for this slot\n const existingNodes: Node[] = [];\n let current = anchor.nextSibling;\n\n while (current) {\n // Stop if we hit another slot anchor\n if (\n current.nodeType === Node.COMMENT_NODE &&\n (current as Comment).textContent?.startsWith('slot:')\n ) {\n break;\n }\n\n // A sibling no projection marked is the component's own markup.\n const meta = expando(current);\n if (meta.__projectedContent === undefined || meta.__slotName !== name) {\n break;\n }\n existingNodes.push(current);\n\n current = current.nextSibling;\n }\n\n // Simple diffing: only replace if content appears different\n // Compare node count and types as a basic heuristic\n const shouldReplace =\n existingNodes.length !== nodesToInsert.length ||\n existingNodes.some(\n (node, i) => node.nodeType !== nodesToInsert[i]?.nodeType\n );\n\n if (!shouldReplace && existingNodes.length > 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Content for slot \"${name}\" unchanged - skipping replacement`\n );\n }\n continue;\n }\n\n // Remove existing content\n for (const node of existingNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n\n // Insert new content after the anchor comment\n if (!insertBesideHidden(anchor, contentFragment))\n parent?.insertBefore(contentFragment, anchor.nextSibling);\n\n // Track cleanup - remove projected nodes when component unmounts\n disposers.push(() => {\n for (const node of nodesToInsert) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] Cleaned up slot \"${name}\"`);\n }\n });\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Successfully mounted ${nodesToInsert.length} nodes for slot \"${name}\"`\n );\n }\n }\n\n // DEV: Validate slot usage\n // NOTE: We intentionally do NOT warn about unmatched projected slots here.\n // When a component uses @if/@else with different <slot> elements in each\n // branch (e.g., Show has <slot> in @if and <slot name=\"fallback\"> in @else),\n // the currently-rendered branch may not include all slot targets. The\n // projected \"fallback\" content is legitimate — it will be mounted when\n // the @else branch activates. Warnings here would be false positives\n // and fire repeatedly on every reactive toggle.\n}\n"]}
@@ -4,4 +4,9 @@ export declare const propEvalMessage: (prop: string, expr: string) => string;
4
4
  export declare const invalidRenderMessage: (tag: string) => string;
5
5
  /** The error a boundary or an SSR crash record receives. */
6
6
  export declare const invalidRenderError: (tag: string) => Error;
7
+ export declare const unexpectedPropsMessage: (tag: string, unexpected: string[], expected: string[], passed: string[]) => string;
8
+ export declare const boundPropMessage: (tag: string, bound: string, prop: string) => string;
9
+ export declare const switchEvalMessage: (kind: "@switch" | "@case", expr: string) => string;
10
+ /** `tag` names the loop: the `@for` element, or `For`. */
11
+ export declare const duplicateKeyMessage: (key: string, tag?: string) => string;
7
12
  //# sourceMappingURL=evalDiagnostics.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"evalDiagnostics.d.ts","sourceRoot":"","sources":["../../src/compile/evalDiagnostics.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,GAAI,MAAM,MAAM,WACF,CAAC;AAE3C,eAAO,MAAM,kBAAkB,yDAA+C,CAAC;AAE/E,eAAO,MAAM,eAAe,GAAI,MAAM,MAAM,EAAE,MAAM,MAAM,WACI,CAAC;AAE/D,eAAO,MAAM,oBAAoB,GAAI,KAAK,MAAM,WAC6B,CAAC;AAE9E,4DAA4D;AAC5D,eAAO,MAAM,kBAAkB,GAAI,KAAK,MAAM,UAC8B,CAAC"}
1
+ {"version":3,"file":"evalDiagnostics.d.ts","sourceRoot":"","sources":["../../src/compile/evalDiagnostics.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe,GAAI,MAAM,MAAM,WACF,CAAC;AAE3C,eAAO,MAAM,kBAAkB,yDAA+C,CAAC;AAE/E,eAAO,MAAM,eAAe,GAAI,MAAM,MAAM,EAAE,MAAM,MAAM,WACI,CAAC;AAE/D,eAAO,MAAM,oBAAoB,GAAI,KAAK,MAAM,WAC6B,CAAC;AAE9E,4DAA4D;AAC5D,eAAO,MAAM,kBAAkB,GAAI,KAAK,MAAM,UAC8B,CAAC;AAE7E,eAAO,MAAM,sBAAsB,GACjC,KAAK,MAAM,EACX,YAAY,MAAM,EAAE,EACpB,UAAU,MAAM,EAAE,EAClB,QAAQ,MAAM,EAAE,WAEiJ,CAAC;AAEpK,eAAO,MAAM,gBAAgB,GAAI,KAAK,MAAM,EAAE,OAAO,MAAM,EAAE,MAAM,MAAM,WACiJ,CAAC;AAE3N,eAAO,MAAM,iBAAiB,GAAI,MAAM,SAAS,GAAG,OAAO,EAAE,MAAM,MAAM,WACvB,CAAC;AAEnD,0DAA0D;AAC1D,eAAO,MAAM,mBAAmB,GAAI,KAAK,MAAM,EAAE,MAAM,MAAM,WACyB,CAAC"}
@@ -5,4 +5,9 @@ export const propEvalMessage = (prop, expr) => `[PithyJS] ⚠️ Failed to evalu
5
5
  export const invalidRenderMessage = (tag) => `[PithyJS] ❌ Invalid render result from <${tag}>. Expected { el, destroy }`;
6
6
  /** The error a boundary or an SSR crash record receives. */
7
7
  export const invalidRenderError = (tag) => new Error(`Invalid render result from <${tag}>; expected { el, destroy }`);
8
+ export const unexpectedPropsMessage = (tag, unexpected, expected, passed) => `[PithyJS] 🔍 Component <${tag}> received unexpected props: ${unexpected.join(', ')}\nExpected props: ${expected.join(', ')}\nPassed props: ${passed.join(', ')}`;
9
+ export const boundPropMessage = (tag, bound, prop) => `[PithyJS] <${tag}> [${bound}] sets an attribute on the rendered root, not the \`${prop}\` prop. Write ${prop}="…" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`;
10
+ export const switchEvalMessage = (kind, expr) => `[PithyJS] ❌ Error evaluating ${kind}="${expr}"`;
11
+ /** `tag` names the loop: the `@for` element, or `For`. */
12
+ export const duplicateKeyMessage = (key, tag) => `[PithyJS] ⚠️ Duplicate @for key ${JSON.stringify(key)}${tag ? ` on <${tag}>` : ''}`;
8
13
  //# sourceMappingURL=evalDiagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"evalDiagnostics.js","sourceRoot":"","sources":["../../src/compile/evalDiagnostics.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,EAAE,CAC9C,iCAAiC,IAAI,GAAG,CAAC;AAE3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,4CAA4C,CAAC;AAE/E,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,IAAY,EAAE,EAAE,CAC5D,yCAAyC,IAAI,QAAQ,IAAI,GAAG,CAAC;AAE/D,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAW,EAAE,EAAE,CAClD,2CAA2C,GAAG,6BAA6B,CAAC;AAE9E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAE,EAAE,CAChD,IAAI,KAAK,CAAC,+BAA+B,GAAG,6BAA6B,CAAC,CAAC","sourcesContent":["// Shared by the dev and build binders, so both paths word these the same way.\n\nexport const textEvalMessage = (expr: string) =>\n `[PithyJS] ❌ Error evaluating '${expr}'`;\n\nexport const classesEvalMessage = '[PithyJS] ⚠️ Failed to evaluate [classes]:';\n\nexport const propEvalMessage = (prop: string, expr: string) =>\n `[PithyJS] ⚠️ Failed to evaluate prop \"${prop}\" = \"${expr}\"`;\n\nexport const invalidRenderMessage = (tag: string) =>\n `[PithyJS] ❌ Invalid render result from <${tag}>. Expected { el, destroy }`;\n\n/** The error a boundary or an SSR crash record receives. */\nexport const invalidRenderError = (tag: string) =>\n new Error(`Invalid render result from <${tag}>; expected { el, destroy }`);\n"]}
1
+ {"version":3,"file":"evalDiagnostics.js","sourceRoot":"","sources":["../../src/compile/evalDiagnostics.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,EAAE,CAC9C,iCAAiC,IAAI,GAAG,CAAC;AAE3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,4CAA4C,CAAC;AAE/E,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,IAAY,EAAE,EAAE,CAC5D,yCAAyC,IAAI,QAAQ,IAAI,GAAG,CAAC;AAE/D,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAW,EAAE,EAAE,CAClD,2CAA2C,GAAG,6BAA6B,CAAC;AAE9E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAE,EAAE,CAChD,IAAI,KAAK,CAAC,+BAA+B,GAAG,6BAA6B,CAAC,CAAC;AAE7E,MAAM,CAAC,MAAM,sBAAsB,GAAG,CACpC,GAAW,EACX,UAAoB,EACpB,QAAkB,EAClB,MAAgB,EAChB,EAAE,CACF,2BAA2B,GAAG,gCAAgC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAEpK,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAW,EAAE,KAAa,EAAE,IAAY,EAAE,EAAE,CAC3E,cAAc,GAAG,MAAM,KAAK,uDAAuD,IAAI,kBAAkB,IAAI,2GAA2G,CAAC;AAE3N,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,IAAyB,EAAE,IAAY,EAAE,EAAE,CAC3E,gCAAgC,IAAI,KAAK,IAAI,GAAG,CAAC;AAEnD,0DAA0D;AAC1D,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,GAAW,EAAE,GAAY,EAAE,EAAE,CAC/D,mCAAmC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,QAAQ,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC","sourcesContent":["// Shared by the dev and build binders, so both paths word these the same way.\n\nexport const textEvalMessage = (expr: string) =>\n `[PithyJS] ❌ Error evaluating '${expr}'`;\n\nexport const classesEvalMessage = '[PithyJS] ⚠️ Failed to evaluate [classes]:';\n\nexport const propEvalMessage = (prop: string, expr: string) =>\n `[PithyJS] ⚠️ Failed to evaluate prop \"${prop}\" = \"${expr}\"`;\n\nexport const invalidRenderMessage = (tag: string) =>\n `[PithyJS] ❌ Invalid render result from <${tag}>. Expected { el, destroy }`;\n\n/** The error a boundary or an SSR crash record receives. */\nexport const invalidRenderError = (tag: string) =>\n new Error(`Invalid render result from <${tag}>; expected { el, destroy }`);\n\nexport const unexpectedPropsMessage = (\n tag: string,\n unexpected: string[],\n expected: string[],\n passed: string[]\n) =>\n `[PithyJS] 🔍 Component <${tag}> received unexpected props: ${unexpected.join(', ')}\\nExpected props: ${expected.join(', ')}\\nPassed props: ${passed.join(', ')}`;\n\nexport const boundPropMessage = (tag: string, bound: string, prop: string) =>\n `[PithyJS] <${tag}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`;\n\nexport const switchEvalMessage = (kind: '@switch' | '@case', expr: string) =>\n `[PithyJS] ❌ Error evaluating ${kind}=\"${expr}\"`;\n\n/** `tag` names the loop: the `@for` element, or `For`. */\nexport const duplicateKeyMessage = (key: string, tag?: string) =>\n `[PithyJS] ⚠️ Duplicate @for key ${JSON.stringify(key)}${tag ? ` on <${tag}>` : ''}`;\n"]}
@@ -44,11 +44,13 @@ export interface LoopManagerOptions<T> {
44
44
  oddVar?: string;
45
45
  templateNodes?: PithyNode[];
46
46
  itemFactory?: ChildFactory;
47
+ /** The loop's tag (the `@for` element, or `For`), for diagnostics. */
48
+ tag?: string;
47
49
  }
48
50
  export interface LoopManager<T = unknown> {
49
51
  update: (collection: T[], node?: PithyNode) => void;
50
52
  destroyAll: () => void;
51
53
  }
52
54
  /** @codexApi {"parent":"pithy.directive.loop-manager","name":"createLoopManager","stability":"stable","signature":"<T>(options: LoopManagerOptions<T>) => LoopManager<T>"} */
53
- export declare function createLoopManager<T>({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, }: LoopManagerOptions<T>): LoopManager<T>;
55
+ export declare function createLoopManager<T>({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, tag, }: LoopManagerOptions<T>): LoopManager<T>;
54
56
  //# sourceMappingURL=createLoopManager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createLoopManager.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"],"names":[],"mappings":"AAAA;;;;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ClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,SAAS,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,YAAY,CAAC;IAC3B,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,OAAO;IACtC,MAAM,EAAE,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,SAAS,KAAK,IAAI,CAAC;IACpD,UAAU,EAAE,MAAM,IAAI,CAAC;CACxB;AAED,8KAA8K;AAC9K,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,EACnC,MAAM,EACN,SAAS,EACT,SAAS,EACT,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,OAAO,EACP,MAAM,EACN,aAAa,EACb,WAAW,EACX,GAAG,GACJ,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CA8ZxC"}
@@ -18,6 +18,7 @@ import { findAllNestedLoopNodes } from './loopTraversal.js';
18
18
  import { nodeExpando } from '../nodeExpando.js';
19
19
  import { orderByDocument } from '../disposeOrder.js';
20
20
  import { withBranchBoundary } from '../binds/bindErrorBoundary.js';
21
+ import { duplicateKeyMessage } from '../evalDiagnostics.js';
21
22
  import { withinRender } from '../ssrCrashes.js';
22
23
  /** First real element between [start..end] to use as a flash target. */
23
24
  function firstElInRange(start, end) {
@@ -113,7 +114,7 @@ function isTemplate(node) {
113
114
  return node.localName === 'template' && 'content' in node;
114
115
  }
115
116
  /** @codexApi {"parent":"pithy.directive.loop-manager","name":"createLoopManager","stability":"stable","signature":"<T>(options: LoopManagerOptions<T>) => LoopManager<T>"} */
116
- export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, }) {
117
+ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, tag, }) {
117
118
  // Map of key -> LoopItem (stable across updates as long as key is stable)
118
119
  const items = new Map();
119
120
  // Row keys in on-screen order. `items` keeps insertion order, which a
@@ -149,10 +150,7 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
149
150
  const seen = new Set();
150
151
  for (const k of newKeys) {
151
152
  if (seen.has(k)) {
152
- console.warn('[loop] duplicate key detected:', k, {
153
- node,
154
- collection,
155
- });
153
+ console.warn(duplicateKeyMessage(k, node?.originalTagName ?? node?.tagName ?? tag), { node, collection });
156
154
  }
157
155
  seen.add(k);
158
156
  }
@@ -359,6 +357,12 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
359
357
  directives: { ...node.directives },
360
358
  };
361
359
  delete nodeForRender.directives.for;
360
+ // `track` keys the loop; it is not a prop (BUG-110).
361
+ if (nodeForRender.isComponent &&
362
+ nodeForRender.attrs?.track !== undefined) {
363
+ const { track: _track, ...attrs } = nodeForRender.attrs;
364
+ nodeForRender.attrs = attrs;
365
+ }
362
366
  cachedTemplateFrag = pithyTreeToDom([nodeForRender], parentCtx);
363
367
  markElementsAsLoopGenerated(cachedTemplateFrag, node);
364
368
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createLoopManager.js","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAkBF,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,IAA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AClC,0EAA0E;QAC1E,IAAI,EAAE,GAAG,CAAC,EACR,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;QAClB,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC;YACf,MAAM,GAAG,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;YAC3B,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBAAE,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;;gBAChC,EAAE,GAAG,GAAG,CAAC;QAChB,CAAC;QAED,6BAA6B;QAC7B,IAAI,EAAE,KAAK,GAAG,CAAC,MAAM;YAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;;YAC9B,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAEjB,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED,qCAAqC;IACrC,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5B,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACX,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACX,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.loop-manager\",\n \"title\": \"Advanced Loop Manager\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * createLoopManager.ts\n *\n * A keyed, range-based list renderer optimized for deep nesting and high churn.\n *\n * Highlights:\n * - Uses [start..end] comment markers to represent each item range (stable DOM, easy move/remove).\n * - Minimal-move reordering using LIS (Longest Increasing Subsequence).\n * - Rebuild fast-path for heavy churn (bulk fragment insert for big updates).\n * - Caches nested loop nodes and tags their hosts to skip parent text-binding passes.\n * - Precise (configurable) visual flashing policy for inserts/moves/updates.\n * - Dev-time duplicate key detection.\n */\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport type { ChildFactory } from '../../runtime/bindings/types';\nimport { batch, createRoot, untrack } from '@pithyjs/signals';\nimport { pithyTreeToDom } from '../pithyTreeToDom';\nimport { bindForLoops } from './bindForLoops';\nimport { flashUpdate } from '../binds/bindTextInterpolations';\nimport { bindTemplateDirectives } from '..';\nimport { bindConditionals } from '../binds/bindConditionals';\nimport { bindSwitchCases } from '../bindSwitchCases';\nimport {\n LoopSignals,\n createLoopSignals,\n updateLoopSignals,\n createLoopContext,\n} from './loopSignals';\nimport {\n safeInsertBefore,\n markElementsAsLoopGenerated,\n createItemRange,\n wrapInRange,\n detachRange,\n} from './loopHelpers';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { nodeExpando } from '../nodeExpando';\nimport { orderByDocument } from '../disposeOrder';\nimport { withBranchBoundary } from '../binds/bindErrorBoundary';\nimport { withinRender } from '../ssrCrashes';\n\n// ── Module-scope helpers (hoisted to avoid re-allocation per update() call) ──\n\ntype FlashUpdatePolicy = 'none' | 'identity' | 'shallow-nested-ignored';\n\n/** First real element between [start..end] to use as a flash target. */\nfunction firstElInRange(start: Comment, end: Comment): Element | null {\n let n: ChildNode | null = start.nextSibling;\n while (n && n !== end) {\n if (n.nodeType === Node.ELEMENT_NODE) return n as Element;\n n = n.nextSibling;\n }\n return null;\n}\n\n/** Extract inclusive [start..end] into a fragment (moving the range intact). */\nfunction collectRange(start: Comment, end: Comment): DocumentFragment {\n const frag = document.createDocumentFragment();\n let n: ChildNode | null = start;\n while (n) {\n const next: ChildNode | null = n.nextSibling;\n frag.appendChild(n);\n if (n === end) break;\n n = next;\n }\n return frag;\n}\n\n/** Compare only shallow, non-object fields to decide if update flash is meaningful. */\nfunction shallowChangedIgnoringObjects(a: unknown, b: unknown): boolean {\n if (a === b) return false;\n if (typeof a !== 'object' || a == null || typeof b !== 'object' || b == null)\n return true;\n\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(ar), ...Object.keys(br)]);\n for (const k of keys) {\n const va = ar[k];\n const vb = br[k];\n const objA = va && typeof va === 'object';\n const objB = vb && typeof vb === 'object';\n if (objA || objB) continue; // ignore nested objects/arrays (child loops will flash)\n if (va !== vb) return true;\n }\n return false;\n}\n\nfunction shouldFlashUpdate(\n policy: FlashUpdatePolicy,\n prevItem: unknown,\n nextItem: unknown\n): boolean {\n switch (policy) {\n case 'none':\n return false;\n case 'identity':\n return prevItem !== nextItem;\n case 'shallow-nested-ignored':\n return shallowChangedIgnoringObjects(prevItem, nextItem);\n }\n}\n\n/** Clone a cached template fragment and restore JS metadata properties via parallel walk. */\nfunction cloneFragmentWithContext(\n template: DocumentFragment,\n ctx: Record<string, unknown>\n): DocumentFragment {\n const clone = template.cloneNode(true) as DocumentFragment;\n restoreNodeMetadata(template, clone, ctx);\n return clone;\n}\n\n/**\n * Walk source and target trees in parallel, copying metadata from source to target.\n * `__pithyCtx` is set to the new `ctx` (not copied from source).\n */\nfunction restoreNodeMetadata(\n source: Node,\n target: Node,\n ctx: Record<string, unknown>\n): void {\n const src = nodeExpando(source);\n const tgt = nodeExpando(target);\n\n if (src.__pithyCtx !== undefined) tgt.__pithyCtx = ctx;\n if (src.__pithyNode !== undefined) tgt.__pithyNode = src.__pithyNode;\n if (src.__nodeId !== undefined) tgt.__nodeId = src.__nodeId;\n if (src.__slotName !== undefined) tgt.__slotName = src.__slotName;\n\n // Slot fallback factory captures context — recreate with new ctx\n const srcNode = src.__pithyNode;\n if (\n src.__fallbackFactory !== undefined &&\n srcNode?.fallbackChildren?.length\n ) {\n tgt.__fallbackFactory = () =>\n pithyTreeToDom(srcNode.fallbackChildren!, ctx);\n }\n\n // Walk children in parallel (cloneNode preserves child count/order)\n const srcChildren = source.childNodes;\n const tgtChildren = target.childNodes;\n for (let i = 0; i < srcChildren.length; i++) {\n restoreNodeMetadata(srcChildren[i], tgtChildren[i], ctx);\n }\n if (isTemplate(source) && isTemplate(target))\n restoreNodeMetadata(source.content, target.content, ctx);\n}\n\nfunction isTemplate(node: Node): node is HTMLTemplateElement {\n return (node as Element).localName === 'template' && 'content' in node;\n}\n\n// ── Interfaces ──\n\nexport type { ChildFactory };\n\nexport interface LoopItem {\n key: string;\n fragment: DocumentFragment | Element; // contains [start, ...content..., end]\n signals: LoopSignals;\n start: Comment;\n end: Comment;\n node?: PithyNode; // original AST node (for caching, diagnostics); absent in templateNodes path\n destroy: () => void;\n}\n\nexport interface LoopManagerOptions<T> {\n anchor: Comment; // DOM anchor comment for the whole loop block\n trackByFn: (item: T, index: number) => string; // stable key selector\n parentCtx: Record<string, unknown>; // parent template context\n itemVar: string; // loop item var name (e.g., \"item\")\n indexVar?: string; // loop index var name (e.g., \"i\")\n countVar?: string; // count signal alias (default: \"count\")\n firstVar?: string; // first signal alias (default: \"first\")\n lastVar?: string; // last signal alias (default: \"last\")\n evenVar?: string; // even signal alias (default: \"even\")\n oddVar?: string; // odd signal alias (default: \"odd\")\n templateNodes?: PithyNode[]; // pre-parsed AST children for component-driven loops (e.g. <For>)\n itemFactory?: ChildFactory;\n}\n\nexport interface LoopManager<T = unknown> {\n update: (collection: T[], node?: PithyNode) => void;\n destroyAll: () => void;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-manager\",\"name\":\"createLoopManager\",\"stability\":\"stable\",\"signature\":\"<T>(options: LoopManagerOptions<T>) => LoopManager<T>\"} */\nexport function createLoopManager<T>({\n anchor,\n trackByFn,\n parentCtx,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar,\n templateNodes,\n itemFactory,\n}: LoopManagerOptions<T>): LoopManager<T> {\n // Map of key -> LoopItem (stable across updates as long as key is stable)\n const items = new Map<string, LoopItem>();\n // Row keys in on-screen order. `items` keeps insertion order, which a\n // reorder leaves behind, and the DOM may be detached by teardown time.\n let order: string[] = [];\n let cachedNestedLoopNodes: PithyNode[] | null = null;\n let cachedTemplateFrag: DocumentFragment | null = null;\n\n /**\n * Update the loop to reflect the given collection:\n * - Diff keys (remove missing, add new).\n * - If churn is heavy: rebuild in a single batch (fast path).\n * - Else: compute minimal moves (LIS - Longest Increasing Subsequence), update signals, and reorder DOM ranges.\n */\n function update(collection: T[], node?: PithyNode): void {\n withinRender(() =>\n withBranchBoundary(anchor, () => updateNow(collection, node))\n );\n }\n\n function updateNow(collection: T[], node?: PithyNode): void {\n const liveParent = anchor.parentNode;\n\n // Flashing Policy\n const FLASH_ON_INSERT = true as const;\n const FLASH_ON_MOVE = false as const; // moves typically aren't \"re-renders\"\n const FLASH_ON_UPDATE: FlashUpdatePolicy = 'shallow-nested-ignored';\n\n // NOTE: We intentionally do NOT wrap the entire update() in batch().\n // createLoopItem builds DOM via pithyTreeToDom which creates reactive\n // effects. If those effects are deferred by an outer batch, the flush\n // can re-trigger the parent effect (in For.ts) causing infinite recursion.\n // Per-item batch() around signal updates is safe and sufficient.\n\n // Key Diff\n const newKeys = collection.map((it, idx) => trackByFn(it, idx));\n const newKeySet = new Set(newKeys);\n\n // Dev-time guard for duplicate keys (can corrupt the map & DOM)\n if (import.meta.env?.DEV) {\n const seen = new Set<string>();\n for (const k of newKeys) {\n if (seen.has(k)) {\n console.warn('[loop] duplicate key detected:', k, {\n node,\n collection,\n });\n }\n seen.add(k);\n }\n }\n\n if (!liveParent) {\n for (const [key, loopItem] of items) {\n if (!newKeySet.has(key)) {\n loopItem.destroy();\n items.delete(key);\n }\n }\n collection.forEach((item, idx) => {\n const existing = items.get(newKeys[idx]);\n if (existing) syncSignals(existing, item, idx, collection.length);\n });\n order = order.filter(k => items.has(k));\n return;\n }\n\n // Remove items that no longer exist\n let removedCount = 0;\n items.forEach((loopItem, key) => {\n if (!newKeySet.has(key)) {\n loopItem.destroy(); // unsubscribes + removes its DOM range\n items.delete(key);\n removedCount++;\n }\n });\n\n // Count additions\n const addedCount = newKeys.reduce(\n (acc, k) => acc + (items.has(k) ? 0 : 1),\n 0\n );\n\n // Churn heuristic (how much of the list changed)\n const n = newKeys.length;\n const churn = (addedCount + removedCount) / Math.max(1, n);\n\n // Rebuild Fast-Path\n // For very heavy churn, a single rebuild is often faster than many moves.\n const REBUILD_THRESHOLD = 0.5;\n if (churn > REBUILD_THRESHOLD) {\n const batchFrag = document.createDocumentFragment();\n\n for (let idx = 0; idx < collection.length; idx++) {\n const key = newKeys[idx];\n const item = collection[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n // Move entire range into the batchFrag fragment\n batchFrag.appendChild(collectRange(existing.start, existing.end));\n } else {\n // Create new item\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(\n node,\n item,\n idx,\n collection.length,\n key\n );\n items.set(key, created);\n batchFrag.appendChild(created.fragment);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n }\n }\n\n // Insert everything at once before the anchor\n safeInsertBefore(liveParent, batchFrag, anchor);\n order = newKeys.filter(k => items.has(k));\n return;\n }\n\n // Minimal-Move Path (LIS)\n // Goal: only move items that are out of order (items in LIS keep their place).\n\n // Current DOM order of existing items (sort by document position)\n const existingItems = Array.from(items.values());\n existingItems.sort((a, b) => {\n const pos = a.start.compareDocumentPosition(b.start);\n // if a follows b, put b first (i.e., a after b => return 1)\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n return 1;\n });\n const oldOrder = existingItems.map(i => i.key);\n\n // Map key -> new position\n const newPos = new Map<string, number>();\n newKeys.forEach((k, i) => newPos.set(k, i));\n\n // Sequence of positions for old items that still exist\n const seq: number[] = [];\n const seqKeys: string[] = [];\n for (const k of oldOrder) {\n const p = newPos.get(k);\n if (p != null) {\n seq.push(p);\n seqKeys.push(k);\n }\n }\n\n // Compute LIS over positions and mark keys to keep (no move)\n const lisIdxs = lis(seq); // indices into seq[]\n const keep = new Set(lisIdxs.map(i => seqKeys[i]));\n\n // Reorder by iterating the new order backwards and inserting before a moving cursor\n let cursor: ChildNode = anchor;\n\n for (let idx = collection.length - 1; idx >= 0; idx--) {\n const item = collection[idx];\n const key = newKeys[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n\n if (keep.has(key)) {\n // Already in good relative position, don't move; just advance cursor\n cursor = existing.start;\n } else {\n // Move the entire range right before the cursor\n const rangeFrag = collectRange(existing.start, existing.end);\n safeInsertBefore(liveParent, rangeFrag, cursor);\n if (FLASH_ON_MOVE) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n cursor = existing.start;\n }\n } else {\n // New item: create and insert before cursor\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(node, item, idx, collection.length, key);\n items.set(key, created);\n safeInsertBefore(liveParent, created.fragment, cursor);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n cursor = created.start;\n }\n }\n order = newKeys.filter(k => items.has(k));\n }\n\n function syncSignals(\n existing: LoopItem,\n item: T,\n idx: number,\n total: number\n ): T {\n const prev = untrack(existing.signals.itemSig) as T;\n batch(() => {\n if (prev !== item) existing.signals.itemSig.set(item);\n updateLoopSignals(existing.signals, idx, total);\n });\n return prev;\n }\n\n /**\n * Create a new LoopItem:\n * - Build the item's DOM from the AST node and local ctx.\n * - Tag top-level elements with __pithyCtx (so events resolve nearest context).\n * - Cache & tag nested loop hosts to skip parent text-binding.\n * - Bind template directives first; then bind nested loops inside this item.\n * - Wrap the item range with [start..end] markers (for move/remove).\n */\n function createLoopItem(\n node: PithyNode | undefined,\n item: T,\n idx: number,\n total: number,\n key: string\n ): LoopItem {\n return createRoot(disposeRoot => buildLoopItem(disposeRoot));\n\n function buildLoopItem(disposeRoot: () => void): LoopItem {\n const signals = createLoopSignals(item, idx, total);\n const ctx = createLoopContext(\n parentCtx,\n signals,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar\n );\n\n if (itemFactory) {\n const built = itemFactory(ctx);\n for (const n of Array.from(built.el.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n const { start, end } = createItemRange(key);\n const destroy = () => {\n built.destroy();\n disposeRoot();\n detachRange(start, end);\n };\n return {\n key,\n fragment: wrapInRange(start, built.el, end),\n signals,\n start,\n end,\n destroy,\n };\n }\n\n // 1) Build static DOM for this item\n let fragmentFromNode: DocumentFragment;\n\n if (!cachedTemplateFrag) {\n // First item: build template from AST once and cache it.\n // Use parentCtx so the cached template does not retain per-item signals.\n // restoreNodeMetadata replaces __pithyCtx with the real per-item ctx on each clone.\n if (templateNodes) {\n cachedTemplateFrag = pithyTreeToDom(templateNodes, parentCtx);\n } else {\n const nodeForRender = {\n ...node!,\n directives: { ...node!.directives },\n };\n delete nodeForRender.directives.for;\n cachedTemplateFrag = pithyTreeToDom([nodeForRender], parentCtx);\n markElementsAsLoopGenerated(cachedTemplateFrag, node!);\n }\n // Clone for this item (cache stays pristine)\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n } else {\n // Subsequent items: clone cached DOM + restore metadata\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n }\n\n // 2) Tag local context on top-level elements for nearest-ctx event resolution\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n\n // 3) Find nested loop nodes ONCE per AST source (cache on the node or in closure)\n const astChildren =\n templateNodes ?? (node?.isComponent ? [] : node!.children || []);\n const allNestedLoopNodes: PithyNode[] = templateNodes\n ? (cachedNestedLoopNodes ??= templateNodes.flatMap(tn => {\n // Include root template nodes that themselves carry @for\n // (findAllNestedLoopNodes skips the root, which is correct for\n // the directive path but misses top-level loops in templateNodes)\n const nested = findAllNestedLoopNodes(tn);\n if (tn.directives?.for) nested.unshift(tn);\n return nested;\n }))\n : ((node as PithyNode & { __nested?: PithyNode[] }).__nested ??=\n findAllNestedLoopNodes(node!));\n\n // 4) Build a data-pid => element map for this fragment and tag hosts to skip text-binding\n const pidMap = new Map<string, Element>();\n (fragmentFromNode as Element | DocumentFragment)\n .querySelectorAll?.('[data-pid]')\n .forEach(el => pidMap.set(el.getAttribute('data-pid')!, el as Element));\n\n for (const n of allNestedLoopNodes) {\n if (!n.nodeId) continue;\n const host = pidMap.get(n.nodeId);\n if (host) nodeExpando(host).__pithySkipText = true; // parent text binder must skip this subtree\n }\n\n // 5) Bind structural directives in the same order as compileTemplate\n const disposers: (() => void)[] = [];\n\n // 5a) Switch/case, then conditionals outside switch cases\n const structuralProcessedIds = bindSwitchCases(\n astChildren,\n fragmentFromNode,\n ctx,\n new Set<string>(),\n disposers\n );\n bindConditionals(\n astChildren,\n fragmentFromNode,\n ctx,\n structuralProcessedIds,\n disposers\n );\n\n // 5c) Bind nested loops (pass processedNodeIds to skip loops inside conditionals)\n const nestedLoopDisposers: (() => void)[] = [];\n bindForLoops(\n allNestedLoopNodes,\n fragmentFromNode,\n ctx,\n nestedLoopDisposers,\n structuralProcessedIds\n );\n disposers.push(...nestedLoopDisposers);\n\n // 5d) Bind template directives (text interpolations, events, etc.)\n bindTemplateDirectives(fragmentFromNode, ctx, disposers);\n orderByDocument(disposers);\n\n // 5e) Mark top-level elements to prevent parent from re-binding their text content\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n nodeExpando(n).__pithySkipText = true;\n }\n }\n\n // 7) Wrap the whole item in [start..end] comments so we can move/remove it as a unit\n const { start, end } = createItemRange(key);\n const grouped = wrapInRange(start, fragmentFromNode, end);\n\n // 8) Cleanup function: unsubscribe effects/listeners and detach DOM range\n const destroy = () => {\n for (let i = disposers.length - 1; i >= 0; i--) disposers[i]();\n disposeRoot();\n detachRange(start, end);\n };\n\n return { key, fragment: grouped, node, signals, start, end, destroy };\n }\n }\n\n // Last row first.\n function destroyAll(): void {\n for (let i = order.length - 1; i >= 0; i--) {\n const item = items.get(order[i]);\n if (!item) continue;\n items.delete(order[i]);\n item.destroy();\n }\n items.forEach(item => item.destroy());\n items.clear();\n order = [];\n }\n\n return { update, destroyAll };\n}\n\n/**\n * O(n log n) Longest Increasing Subsequence.\n * Given an array of numbers `a`, returns the indices into `a` that form\n * a strictly increasing subsequence with maximal length.\n *\n * We use LIS on the sequence of \"new positions\" for existing items to minimize DOM moves:\n * - Items in the LIS are already in correct relative order and don't need to move.\n * - Only the remaining items are moved to their new positions.\n */\nfunction lis(a: number[]): number[] {\n const res: number[] = []; // res[k] is the index i of the smallest tail of an increasing subsequence of length k+1\n const m: number[] = []; // m[i] points to predecessor index for i in the LIS\n\n for (let i = 0; i < a.length; i++) {\n // binary search in res to find the length of the LIS that a[i] can extend\n let lo = 0,\n hi = res.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (a[res[mid]] < a[i]) lo = mid + 1;\n else hi = mid;\n }\n\n // update res and predecessor\n if (lo === res.length) res.push(i);\n else res[lo] = i;\n\n m[i] = lo ? res[lo - 1] : -1;\n }\n\n // reconstruct LIS indices from res/m\n let k = res[res.length - 1];\n const out: number[] = [];\n for (let i = res.length - 1; i >= 0; i--) {\n out[i] = k;\n k = m[k];\n }\n return out;\n}\n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CAAC;;YAC9B,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAEjB,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED,qCAAqC;IACrC,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5B,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACX,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACX,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.loop-manager\",\n \"title\": \"Advanced Loop Manager\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * createLoopManager.ts\n *\n * A keyed, range-based list renderer optimized for deep nesting and high churn.\n *\n * Highlights:\n * - Uses [start..end] comment markers to represent each item range (stable DOM, easy move/remove).\n * - Minimal-move reordering using LIS (Longest Increasing Subsequence).\n * - Rebuild fast-path for heavy churn (bulk fragment insert for big updates).\n * - Caches nested loop nodes and tags their hosts to skip parent text-binding passes.\n * - Precise (configurable) visual flashing policy for inserts/moves/updates.\n * - Dev-time duplicate key detection.\n */\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport type { ChildFactory } from '../../runtime/bindings/types';\nimport { batch, createRoot, untrack } from '@pithyjs/signals';\nimport { pithyTreeToDom } from '../pithyTreeToDom';\nimport { bindForLoops } from './bindForLoops';\nimport { flashUpdate } from '../binds/bindTextInterpolations';\nimport { bindTemplateDirectives } from '..';\nimport { bindConditionals } from '../binds/bindConditionals';\nimport { bindSwitchCases } from '../bindSwitchCases';\nimport {\n LoopSignals,\n createLoopSignals,\n updateLoopSignals,\n createLoopContext,\n} from './loopSignals';\nimport {\n safeInsertBefore,\n markElementsAsLoopGenerated,\n createItemRange,\n wrapInRange,\n detachRange,\n} from './loopHelpers';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { nodeExpando } from '../nodeExpando';\nimport { orderByDocument } from '../disposeOrder';\nimport { withBranchBoundary } from '../binds/bindErrorBoundary';\nimport { duplicateKeyMessage } from '../evalDiagnostics';\nimport { withinRender } from '../ssrCrashes';\n\n// ── Module-scope helpers (hoisted to avoid re-allocation per update() call) ──\n\ntype FlashUpdatePolicy = 'none' | 'identity' | 'shallow-nested-ignored';\n\n/** First real element between [start..end] to use as a flash target. */\nfunction firstElInRange(start: Comment, end: Comment): Element | null {\n let n: ChildNode | null = start.nextSibling;\n while (n && n !== end) {\n if (n.nodeType === Node.ELEMENT_NODE) return n as Element;\n n = n.nextSibling;\n }\n return null;\n}\n\n/** Extract inclusive [start..end] into a fragment (moving the range intact). */\nfunction collectRange(start: Comment, end: Comment): DocumentFragment {\n const frag = document.createDocumentFragment();\n let n: ChildNode | null = start;\n while (n) {\n const next: ChildNode | null = n.nextSibling;\n frag.appendChild(n);\n if (n === end) break;\n n = next;\n }\n return frag;\n}\n\n/** Compare only shallow, non-object fields to decide if update flash is meaningful. */\nfunction shallowChangedIgnoringObjects(a: unknown, b: unknown): boolean {\n if (a === b) return false;\n if (typeof a !== 'object' || a == null || typeof b !== 'object' || b == null)\n return true;\n\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(ar), ...Object.keys(br)]);\n for (const k of keys) {\n const va = ar[k];\n const vb = br[k];\n const objA = va && typeof va === 'object';\n const objB = vb && typeof vb === 'object';\n if (objA || objB) continue; // ignore nested objects/arrays (child loops will flash)\n if (va !== vb) return true;\n }\n return false;\n}\n\nfunction shouldFlashUpdate(\n policy: FlashUpdatePolicy,\n prevItem: unknown,\n nextItem: unknown\n): boolean {\n switch (policy) {\n case 'none':\n return false;\n case 'identity':\n return prevItem !== nextItem;\n case 'shallow-nested-ignored':\n return shallowChangedIgnoringObjects(prevItem, nextItem);\n }\n}\n\n/** Clone a cached template fragment and restore JS metadata properties via parallel walk. */\nfunction cloneFragmentWithContext(\n template: DocumentFragment,\n ctx: Record<string, unknown>\n): DocumentFragment {\n const clone = template.cloneNode(true) as DocumentFragment;\n restoreNodeMetadata(template, clone, ctx);\n return clone;\n}\n\n/**\n * Walk source and target trees in parallel, copying metadata from source to target.\n * `__pithyCtx` is set to the new `ctx` (not copied from source).\n */\nfunction restoreNodeMetadata(\n source: Node,\n target: Node,\n ctx: Record<string, unknown>\n): void {\n const src = nodeExpando(source);\n const tgt = nodeExpando(target);\n\n if (src.__pithyCtx !== undefined) tgt.__pithyCtx = ctx;\n if (src.__pithyNode !== undefined) tgt.__pithyNode = src.__pithyNode;\n if (src.__nodeId !== undefined) tgt.__nodeId = src.__nodeId;\n if (src.__slotName !== undefined) tgt.__slotName = src.__slotName;\n\n // Slot fallback factory captures context — recreate with new ctx\n const srcNode = src.__pithyNode;\n if (\n src.__fallbackFactory !== undefined &&\n srcNode?.fallbackChildren?.length\n ) {\n tgt.__fallbackFactory = () =>\n pithyTreeToDom(srcNode.fallbackChildren!, ctx);\n }\n\n // Walk children in parallel (cloneNode preserves child count/order)\n const srcChildren = source.childNodes;\n const tgtChildren = target.childNodes;\n for (let i = 0; i < srcChildren.length; i++) {\n restoreNodeMetadata(srcChildren[i], tgtChildren[i], ctx);\n }\n if (isTemplate(source) && isTemplate(target))\n restoreNodeMetadata(source.content, target.content, ctx);\n}\n\nfunction isTemplate(node: Node): node is HTMLTemplateElement {\n return (node as Element).localName === 'template' && 'content' in node;\n}\n\n// ── Interfaces ──\n\nexport type { ChildFactory };\n\nexport interface LoopItem {\n key: string;\n fragment: DocumentFragment | Element; // contains [start, ...content..., end]\n signals: LoopSignals;\n start: Comment;\n end: Comment;\n node?: PithyNode; // original AST node (for caching, diagnostics); absent in templateNodes path\n destroy: () => void;\n}\n\nexport interface LoopManagerOptions<T> {\n anchor: Comment; // DOM anchor comment for the whole loop block\n trackByFn: (item: T, index: number) => string; // stable key selector\n parentCtx: Record<string, unknown>; // parent template context\n itemVar: string; // loop item var name (e.g., \"item\")\n indexVar?: string; // loop index var name (e.g., \"i\")\n countVar?: string; // count signal alias (default: \"count\")\n firstVar?: string; // first signal alias (default: \"first\")\n lastVar?: string; // last signal alias (default: \"last\")\n evenVar?: string; // even signal alias (default: \"even\")\n oddVar?: string; // odd signal alias (default: \"odd\")\n templateNodes?: PithyNode[]; // pre-parsed AST children for component-driven loops (e.g. <For>)\n itemFactory?: ChildFactory;\n /** The loop's tag (the `@for` element, or `For`), for diagnostics. */\n tag?: string;\n}\n\nexport interface LoopManager<T = unknown> {\n update: (collection: T[], node?: PithyNode) => void;\n destroyAll: () => void;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-manager\",\"name\":\"createLoopManager\",\"stability\":\"stable\",\"signature\":\"<T>(options: LoopManagerOptions<T>) => LoopManager<T>\"} */\nexport function createLoopManager<T>({\n anchor,\n trackByFn,\n parentCtx,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar,\n templateNodes,\n itemFactory,\n tag,\n}: LoopManagerOptions<T>): LoopManager<T> {\n // Map of key -> LoopItem (stable across updates as long as key is stable)\n const items = new Map<string, LoopItem>();\n // Row keys in on-screen order. `items` keeps insertion order, which a\n // reorder leaves behind, and the DOM may be detached by teardown time.\n let order: string[] = [];\n let cachedNestedLoopNodes: PithyNode[] | null = null;\n let cachedTemplateFrag: DocumentFragment | null = null;\n\n /**\n * Update the loop to reflect the given collection:\n * - Diff keys (remove missing, add new).\n * - If churn is heavy: rebuild in a single batch (fast path).\n * - Else: compute minimal moves (LIS - Longest Increasing Subsequence), update signals, and reorder DOM ranges.\n */\n function update(collection: T[], node?: PithyNode): void {\n withinRender(() =>\n withBranchBoundary(anchor, () => updateNow(collection, node))\n );\n }\n\n function updateNow(collection: T[], node?: PithyNode): void {\n const liveParent = anchor.parentNode;\n\n // Flashing Policy\n const FLASH_ON_INSERT = true as const;\n const FLASH_ON_MOVE = false as const; // moves typically aren't \"re-renders\"\n const FLASH_ON_UPDATE: FlashUpdatePolicy = 'shallow-nested-ignored';\n\n // NOTE: We intentionally do NOT wrap the entire update() in batch().\n // createLoopItem builds DOM via pithyTreeToDom which creates reactive\n // effects. If those effects are deferred by an outer batch, the flush\n // can re-trigger the parent effect (in For.ts) causing infinite recursion.\n // Per-item batch() around signal updates is safe and sufficient.\n\n // Key Diff\n const newKeys = collection.map((it, idx) => trackByFn(it, idx));\n const newKeySet = new Set(newKeys);\n\n // Dev-time guard for duplicate keys (can corrupt the map & DOM)\n if (import.meta.env?.DEV) {\n const seen = new Set<string>();\n for (const k of newKeys) {\n if (seen.has(k)) {\n console.warn(\n duplicateKeyMessage(\n k,\n node?.originalTagName ?? node?.tagName ?? tag\n ),\n { node, collection }\n );\n }\n seen.add(k);\n }\n }\n\n if (!liveParent) {\n for (const [key, loopItem] of items) {\n if (!newKeySet.has(key)) {\n loopItem.destroy();\n items.delete(key);\n }\n }\n collection.forEach((item, idx) => {\n const existing = items.get(newKeys[idx]);\n if (existing) syncSignals(existing, item, idx, collection.length);\n });\n order = order.filter(k => items.has(k));\n return;\n }\n\n // Remove items that no longer exist\n let removedCount = 0;\n items.forEach((loopItem, key) => {\n if (!newKeySet.has(key)) {\n loopItem.destroy(); // unsubscribes + removes its DOM range\n items.delete(key);\n removedCount++;\n }\n });\n\n // Count additions\n const addedCount = newKeys.reduce(\n (acc, k) => acc + (items.has(k) ? 0 : 1),\n 0\n );\n\n // Churn heuristic (how much of the list changed)\n const n = newKeys.length;\n const churn = (addedCount + removedCount) / Math.max(1, n);\n\n // Rebuild Fast-Path\n // For very heavy churn, a single rebuild is often faster than many moves.\n const REBUILD_THRESHOLD = 0.5;\n if (churn > REBUILD_THRESHOLD) {\n const batchFrag = document.createDocumentFragment();\n\n for (let idx = 0; idx < collection.length; idx++) {\n const key = newKeys[idx];\n const item = collection[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n // Move entire range into the batchFrag fragment\n batchFrag.appendChild(collectRange(existing.start, existing.end));\n } else {\n // Create new item\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(\n node,\n item,\n idx,\n collection.length,\n key\n );\n items.set(key, created);\n batchFrag.appendChild(created.fragment);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n }\n }\n\n // Insert everything at once before the anchor\n safeInsertBefore(liveParent, batchFrag, anchor);\n order = newKeys.filter(k => items.has(k));\n return;\n }\n\n // Minimal-Move Path (LIS)\n // Goal: only move items that are out of order (items in LIS keep their place).\n\n // Current DOM order of existing items (sort by document position)\n const existingItems = Array.from(items.values());\n existingItems.sort((a, b) => {\n const pos = a.start.compareDocumentPosition(b.start);\n // if a follows b, put b first (i.e., a after b => return 1)\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n return 1;\n });\n const oldOrder = existingItems.map(i => i.key);\n\n // Map key -> new position\n const newPos = new Map<string, number>();\n newKeys.forEach((k, i) => newPos.set(k, i));\n\n // Sequence of positions for old items that still exist\n const seq: number[] = [];\n const seqKeys: string[] = [];\n for (const k of oldOrder) {\n const p = newPos.get(k);\n if (p != null) {\n seq.push(p);\n seqKeys.push(k);\n }\n }\n\n // Compute LIS over positions and mark keys to keep (no move)\n const lisIdxs = lis(seq); // indices into seq[]\n const keep = new Set(lisIdxs.map(i => seqKeys[i]));\n\n // Reorder by iterating the new order backwards and inserting before a moving cursor\n let cursor: ChildNode = anchor;\n\n for (let idx = collection.length - 1; idx >= 0; idx--) {\n const item = collection[idx];\n const key = newKeys[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n\n if (keep.has(key)) {\n // Already in good relative position, don't move; just advance cursor\n cursor = existing.start;\n } else {\n // Move the entire range right before the cursor\n const rangeFrag = collectRange(existing.start, existing.end);\n safeInsertBefore(liveParent, rangeFrag, cursor);\n if (FLASH_ON_MOVE) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n cursor = existing.start;\n }\n } else {\n // New item: create and insert before cursor\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(node, item, idx, collection.length, key);\n items.set(key, created);\n safeInsertBefore(liveParent, created.fragment, cursor);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n cursor = created.start;\n }\n }\n order = newKeys.filter(k => items.has(k));\n }\n\n function syncSignals(\n existing: LoopItem,\n item: T,\n idx: number,\n total: number\n ): T {\n const prev = untrack(existing.signals.itemSig) as T;\n batch(() => {\n if (prev !== item) existing.signals.itemSig.set(item);\n updateLoopSignals(existing.signals, idx, total);\n });\n return prev;\n }\n\n /**\n * Create a new LoopItem:\n * - Build the item's DOM from the AST node and local ctx.\n * - Tag top-level elements with __pithyCtx (so events resolve nearest context).\n * - Cache & tag nested loop hosts to skip parent text-binding.\n * - Bind template directives first; then bind nested loops inside this item.\n * - Wrap the item range with [start..end] markers (for move/remove).\n */\n function createLoopItem(\n node: PithyNode | undefined,\n item: T,\n idx: number,\n total: number,\n key: string\n ): LoopItem {\n return createRoot(disposeRoot => buildLoopItem(disposeRoot));\n\n function buildLoopItem(disposeRoot: () => void): LoopItem {\n const signals = createLoopSignals(item, idx, total);\n const ctx = createLoopContext(\n parentCtx,\n signals,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar\n );\n\n if (itemFactory) {\n const built = itemFactory(ctx);\n for (const n of Array.from(built.el.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n const { start, end } = createItemRange(key);\n const destroy = () => {\n built.destroy();\n disposeRoot();\n detachRange(start, end);\n };\n return {\n key,\n fragment: wrapInRange(start, built.el, end),\n signals,\n start,\n end,\n destroy,\n };\n }\n\n // 1) Build static DOM for this item\n let fragmentFromNode: DocumentFragment;\n\n if (!cachedTemplateFrag) {\n // First item: build template from AST once and cache it.\n // Use parentCtx so the cached template does not retain per-item signals.\n // restoreNodeMetadata replaces __pithyCtx with the real per-item ctx on each clone.\n if (templateNodes) {\n cachedTemplateFrag = pithyTreeToDom(templateNodes, parentCtx);\n } else {\n const nodeForRender = {\n ...node!,\n directives: { ...node!.directives },\n };\n delete nodeForRender.directives.for;\n // `track` keys the loop; it is not a prop (BUG-110).\n if (\n nodeForRender.isComponent &&\n nodeForRender.attrs?.track !== undefined\n ) {\n const { track: _track, ...attrs } = nodeForRender.attrs;\n nodeForRender.attrs = attrs;\n }\n cachedTemplateFrag = pithyTreeToDom([nodeForRender], parentCtx);\n markElementsAsLoopGenerated(cachedTemplateFrag, node!);\n }\n // Clone for this item (cache stays pristine)\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n } else {\n // Subsequent items: clone cached DOM + restore metadata\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n }\n\n // 2) Tag local context on top-level elements for nearest-ctx event resolution\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n\n // 3) Find nested loop nodes ONCE per AST source (cache on the node or in closure)\n const astChildren =\n templateNodes ?? (node?.isComponent ? [] : node!.children || []);\n const allNestedLoopNodes: PithyNode[] = templateNodes\n ? (cachedNestedLoopNodes ??= templateNodes.flatMap(tn => {\n // Include root template nodes that themselves carry @for\n // (findAllNestedLoopNodes skips the root, which is correct for\n // the directive path but misses top-level loops in templateNodes)\n const nested = findAllNestedLoopNodes(tn);\n if (tn.directives?.for) nested.unshift(tn);\n return nested;\n }))\n : ((node as PithyNode & { __nested?: PithyNode[] }).__nested ??=\n findAllNestedLoopNodes(node!));\n\n // 4) Build a data-pid => element map for this fragment and tag hosts to skip text-binding\n const pidMap = new Map<string, Element>();\n (fragmentFromNode as Element | DocumentFragment)\n .querySelectorAll?.('[data-pid]')\n .forEach(el => pidMap.set(el.getAttribute('data-pid')!, el as Element));\n\n for (const n of allNestedLoopNodes) {\n if (!n.nodeId) continue;\n const host = pidMap.get(n.nodeId);\n if (host) nodeExpando(host).__pithySkipText = true; // parent text binder must skip this subtree\n }\n\n // 5) Bind structural directives in the same order as compileTemplate\n const disposers: (() => void)[] = [];\n\n // 5a) Switch/case, then conditionals outside switch cases\n const structuralProcessedIds = bindSwitchCases(\n astChildren,\n fragmentFromNode,\n ctx,\n new Set<string>(),\n disposers\n );\n bindConditionals(\n astChildren,\n fragmentFromNode,\n ctx,\n structuralProcessedIds,\n disposers\n );\n\n // 5c) Bind nested loops (pass processedNodeIds to skip loops inside conditionals)\n const nestedLoopDisposers: (() => void)[] = [];\n bindForLoops(\n allNestedLoopNodes,\n fragmentFromNode,\n ctx,\n nestedLoopDisposers,\n structuralProcessedIds\n );\n disposers.push(...nestedLoopDisposers);\n\n // 5d) Bind template directives (text interpolations, events, etc.)\n bindTemplateDirectives(fragmentFromNode, ctx, disposers);\n orderByDocument(disposers);\n\n // 5e) Mark top-level elements to prevent parent from re-binding their text content\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n nodeExpando(n).__pithySkipText = true;\n }\n }\n\n // 7) Wrap the whole item in [start..end] comments so we can move/remove it as a unit\n const { start, end } = createItemRange(key);\n const grouped = wrapInRange(start, fragmentFromNode, end);\n\n // 8) Cleanup function: unsubscribe effects/listeners and detach DOM range\n const destroy = () => {\n for (let i = disposers.length - 1; i >= 0; i--) disposers[i]();\n disposeRoot();\n detachRange(start, end);\n };\n\n return { key, fragment: grouped, node, signals, start, end, destroy };\n }\n }\n\n // Last row first.\n function destroyAll(): void {\n for (let i = order.length - 1; i >= 0; i--) {\n const item = items.get(order[i]);\n if (!item) continue;\n items.delete(order[i]);\n item.destroy();\n }\n items.forEach(item => item.destroy());\n items.clear();\n order = [];\n }\n\n return { update, destroyAll };\n}\n\n/**\n * O(n log n) Longest Increasing Subsequence.\n * Given an array of numbers `a`, returns the indices into `a` that form\n * a strictly increasing subsequence with maximal length.\n *\n * We use LIS on the sequence of \"new positions\" for existing items to minimize DOM moves:\n * - Items in the LIS are already in correct relative order and don't need to move.\n * - Only the remaining items are moved to their new positions.\n */\nfunction lis(a: number[]): number[] {\n const res: number[] = []; // res[k] is the index i of the smallest tail of an increasing subsequence of length k+1\n const m: number[] = []; // m[i] points to predecessor index for i in the LIS\n\n for (let i = 0; i < a.length; i++) {\n // binary search in res to find the length of the LIS that a[i] can extend\n let lo = 0,\n hi = res.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (a[res[mid]] < a[i]) lo = mid + 1;\n else hi = mid;\n }\n\n // update res and predecessor\n if (lo === res.length) res.push(i);\n else res[lo] = i;\n\n m[i] = lo ? res[lo - 1] : -1;\n }\n\n // reconstruct LIS indices from res/m\n let k = res[res.length - 1];\n const out: number[] = [];\n for (let i = res.length - 1; i >= 0; i--) {\n out[i] = k;\n k = m[k];\n }\n return out;\n}\n"]}
@@ -113,6 +113,12 @@ export declare function hasCrashed(el: Element): boolean;
113
113
  */
114
114
  /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"withinRender","stability":"internal","signature":"<T>(fn: () => T) => T"} */
115
115
  export declare function withinRender<T>(fn: () => T): T;
116
+ /** Logs a component failure, and marks `el` when it failed in a branch. */
117
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"logFailure","stability":"internal","signature":"(el: Element, log: () => void) => void"} */
118
+ export declare function logFailure(el: Element, log: () => void): void;
119
+ /** Whether `el` failed while its branch was built; the pass that binds the inserted branch would retry it (BUG-161). */
120
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"failedInBranch","stability":"internal","signature":"(el: Element) => boolean"} */
121
+ export declare function failedInBranch(el: Element): boolean;
116
122
  /**
117
123
  * Attributes a crash that reached no boundary through the DOM to the boundary
118
124
  * its render sits under (`boundaryContext`): a branch, slot or component built
@@ -1 +1 @@
1
- {"version":3,"file":"ssrCrashes.d.ts","sourceRoot":"","sources":["../../src/compile/ssrCrashes.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAKF,OAAO,EAOL,KAAK,YAAY,EAClB,MAAM,2BAA2B,CAAC;AAEnC;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,EAAE,EAAE,OAAO,CAAC;IACZ,kDAAkD;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,qCAAqC;IACrC,KAAK,EAAE,KAAK,CAAC;CACd;AAwBD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,+IAA+I;AAC/I,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI,CAErD;AA4BD;;;GAGG;AACH,oIAAoI;AACpI,wBAAgB,qBAAqB,IAAI,IAAI,CAK5C;AAED;;;GAGG;AACH,uIAAuI;AACvI,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI,CAI7C;AAQD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,2JAA2J;AAC3J,wBAAgB,gCAAgC,IAAI,cAAc,EAAE,CAMnE;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,0OAA0O;AAC1O,wBAAgB,sBAAsB,CACpC,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,K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,EAAE,MAAM,EACX,KAAK,EAAE,KAAK,EACZ,EAAE,OAAc,EAAE,UAAU,EAAE,GAAE,WAAgB,GAC/C,OAAO,CAiBT;AAyBD;;;;;;;;;;GAUG;AACH,iMAAiM;AACjM,wBAAgB,wBAAwB,CACtC,IAAI,GAAE,QAAQ,GAAG,MAAM,GAAG,SAAoB,EAC9C,KAAK,CAAC,EAAE,UAAU,GACjB,IAAI,CAwDN;AAsGD;;;;GAIG;AACH,iJAAiJ;AACjJ,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI,CAIvD"}
@@ -9,7 +9,7 @@
9
9
  import { untrack } from '@pithyjs/signals';
10
10
  import { pithyGlobals } from '../types/globals.js';
11
11
  import { isSSRMode } from './ssrMode.js';
12
- import { boundaryContext, findParentBoundary, isInHiddenContent, registeredClosest, setBoundaryError, slotOwnerOf, } from './binds/bindErrorBoundary.js';
12
+ import { boundaryContext, findParentBoundary, inBranch, isInHiddenContent, registeredClosest, setBoundaryError, slotOwnerOf, } from './binds/bindErrorBoundary.js';
13
13
  /**
14
14
  * Crashes recorded during the current server render, keyed by the placeholder
15
15
  * element so a later binding pass over the same element can retract its own
@@ -246,6 +246,22 @@ export function withinRender(fn) {
246
246
  resolveAttributedCrashes();
247
247
  }
248
248
  }
249
+ function branchFailures() {
250
+ const g = pithyGlobals();
251
+ return (g.__pithyBranchFailures ?? (g.__pithyBranchFailures = new WeakSet()));
252
+ }
253
+ /** Logs a component failure, and marks `el` when it failed in a branch. */
254
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"logFailure","stability":"internal","signature":"(el: Element, log: () => void) => void"} */
255
+ export function logFailure(el, log) {
256
+ if (inBranch())
257
+ branchFailures().add(el);
258
+ log();
259
+ }
260
+ /** Whether `el` failed while its branch was built; the pass that binds the inserted branch would retry it (BUG-161). */
261
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"failedInBranch","stability":"internal","signature":"(el: Element) => boolean"} */
262
+ export function failedInBranch(el) {
263
+ return branchFailures().has(el);
264
+ }
249
265
  /**
250
266
  * Attributes a crash that reached no boundary through the DOM to the boundary
251
267
  * its render sits under (`boundaryContext`): a branch, slot or component built