@openelement/compiler 1.0.0-alpha.14 → 1.0.0-alpha.16

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 (56) hide show
  1. package/package.json +4 -2
  2. package/src/compiler.d.ts +12 -6
  3. package/src/compiler.js +11 -6
  4. package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +11 -0
  5. package/src/internal/compiler/compiled-artifact-class-candidates.js +46 -0
  6. package/src/internal/compiler/compiled-artifact-style-requests.d.ts +26 -7
  7. package/src/internal/compiler/compiled-artifact-style-requests.js +57 -9
  8. package/src/internal/compiler/plugin.d.ts +68 -49
  9. package/src/internal/compiler/plugin.js +93 -82
  10. package/src/internal/compiler/semantic-core/analyze-module.d.ts +73 -0
  11. package/src/internal/compiler/semantic-core/analyze-module.js +29 -379
  12. package/src/internal/compiler/semantic-core/attribute-classification.js +92 -0
  13. package/src/internal/compiler/semantic-core/compiler-diagnostics.js +2 -16
  14. package/src/internal/compiler/semantic-core/diagnostics/index.d.ts +21 -1
  15. package/src/internal/compiler/semantic-core/diagnostics/index.js +32 -1
  16. package/src/internal/compiler/semantic-core/expression-lowering.js +469 -0
  17. package/src/internal/compiler/semantic-core/expression-registry.js +165 -0
  18. package/src/internal/compiler/semantic-core/function-frontend.js +1229 -0
  19. package/src/internal/compiler/semantic-core/island-policy-statement.js +52 -0
  20. package/src/internal/compiler/semantic-core/jsx-module-id.d.ts +4 -0
  21. package/src/internal/compiler/semantic-core/jsx-module-id.js +7 -0
  22. package/src/internal/compiler/semantic-core/lower-program.d.ts +220 -0
  23. package/src/internal/compiler/semantic-core/lower-program.js +350 -142
  24. package/src/internal/compiler/semantic-core/module-analysis.d.ts +82 -4
  25. package/src/internal/compiler/semantic-core/module-analysis.js +88 -19
  26. package/src/internal/compiler/semantic-core/parse-module.js +16 -16
  27. package/src/internal/compiler/semantic-core/scope-resolution.d.ts +208 -0
  28. package/src/internal/compiler/semantic-core/scope-resolution.js +1121 -0
  29. package/src/internal/compiler/semantic-core/server-component.d.ts +129 -0
  30. package/src/internal/compiler/semantic-core/server-component.js +587 -0
  31. package/src/internal/compiler/semantic-core/type-check.js +1 -1
  32. package/src/internal/compiler/semantic-core/type-erasure.js +156 -0
  33. package/src/internal/compiler/semantic-ir/generated-element/compile.d.ts +61 -0
  34. package/src/internal/compiler/semantic-ir/generated-element/compile.js +137 -0
  35. package/src/internal/compiler/semantic-ir/generated-element/contract.d.ts +201 -0
  36. package/src/internal/compiler/semantic-ir/generated-element/contract.js +147 -0
  37. package/src/internal/compiler/semantic-ir/generated-element/emit.js +452 -0
  38. package/src/internal/compiler/semantic-ir/generated-element/site.js +1195 -0
  39. package/src/internal/compiler/semantic-ir/generated-leaf/claim-emission.js +1372 -0
  40. package/src/internal/compiler/semantic-ir/generated-leaf/codegen-literals.js +31 -0
  41. package/src/internal/compiler/semantic-ir/generated-leaf/component-emission.js +647 -0
  42. package/src/internal/compiler/semantic-ir/generated-leaf/emission.js +388 -0
  43. package/src/internal/compiler/semantic-ir/generated-leaf/generate.js +395 -0
  44. package/src/internal/compiler/semantic-ir/generated-leaf/instance-emission.js +865 -0
  45. package/src/internal/compiler/semantic-ir/generated-leaf/mount-emission.js +960 -0
  46. package/src/internal/compiler/semantic-ir/generated-leaf/server-emission.js +1011 -0
  47. package/src/internal/compiler/semantic-ir/generated-leaf/structure.js +714 -0
  48. package/src/internal/compiler/style-requests.d.ts +35 -7
  49. package/src/internal/compiler/style-requests.js +57 -11
  50. package/src/internal/compiler/tailwind-candidates.d.ts +84 -0
  51. package/src/internal/compiler/tailwind-candidates.js +54 -0
  52. package/src/internal/compiler/semantic-core/compile.d.ts +0 -39
  53. package/src/internal/compiler/semantic-core/compile.js +0 -98
  54. package/src/internal/compiler/semantic-core/emit-module.js +0 -313
  55. package/src/internal/compiler/semantic-core/emit-program.js +0 -121
  56. package/src/internal/compiler/semantic-core/style-imports.js +0 -87
@@ -0,0 +1,1372 @@
1
+ import { BOOLEAN_ATTRIBUTES } from "../../semantic-core/attribute-classification.js";
2
+ import { CLAIM_PARENT, CLAIM_SUFFIX, CLIENT_ONLY_ATTRIBUTE_CHANNELS, CONSUMED_ATTRIBUTE_CHANNELS, HTML_NAMESPACE, IDENTIFIER_PATTERN, INTERNAL_PREFIX, MOUNT_HOST, MOUNT_PROPS, MOUNT_SCOPE, SVG_NAMESPACE, TRANSACTION_VAR, declareReads, dependencyNames, diag, emitDependencySubscriptions, fragmentLineCount, nextName, originArgs, push, pushParts, recordFor, registerRefresh } from "./emission.js";
3
+ import { assertTextBoundaryContext, componentClaimable, componentProjectsChildren, declaredRecipeIdSet, declaredStaticLiteral, directoryParentAllowed, emissionNodes, isDirectoryRootComponent, nodeClaimable, normalizeTextRuns, referencedRecipeIds, staticElementDirectory, textOrdinal, textSlotOrdinals } from "./structure.js";
4
+ import { LEAF_SETUP_HOST_PROPERTY, LEAF_SETUP_SUFFIX, ROOT_SETUP_HOST_PROPERTY, childContextField, childErrorBoundaryField, childErrorReportField, childHostElementField, childPropertyChangeField, componentUsesContextIntrinsic, emitJoinTransaction, emitLifecycleEnvReplay, emitLifecycleReplay, emitSetupAlias, emitSetupBinding, retainedTransactionField, siteKeyLiteral } from "./instance-emission.js";
5
+ import { clientOnlyAttributeAdmitted, emitBranchRelease, emitBranchRollback, emitClientOnlyInstall, emitEntryBuilder, emitListKeyFunction, emitNodesBuilder, emitsRetentionReleaseText } from "./mount-emission.js";
6
+ import { STATIC_STYLES_MARKER } from "@openelement/protocol/part-program";
7
+ //#region src/internal/compiler/semantic-ir/generated-leaf/claim-emission.ts
8
+ /**
9
+ * Module-level activation queue for the shared-cursor claim path (M08-2 B2).
10
+ * The cursor owner initializes it, nested component/recipe claims append to it,
11
+ * and the owner captures it in `try`, clears it in `finally`, then drains the
12
+ * captured local after the whole enclosing structure validated. A verify throw
13
+ * therefore leaves no module-level queue behind.
14
+ */
15
+ const CLAIM_ACTIVATION = `${INTERNAL_PREFIX}claimPhase2`;
16
+ /**
17
+ * Claim-period dynamic-text slot write. The slot is a boundary pair plus an
18
+ * optional Text node: `null` means the server wire carried no text (an empty
19
+ * value), so an equal client value is a no-op and a non-empty one lazily
20
+ * inserts the slot's single Text before the closing marker. An existing Text
21
+ * is value-compared; it is never split, merged, normalized or removed.
22
+ *
23
+ * The lazy node is not part of the projected `nodes` array, so it is owned by a
24
+ * claim-scope range cleanup. The node cursor already points past the consumed
25
+ * close marker, so no index compensation is needed.
26
+ */
27
+ function emitClaimTextSlotWrite(state, slotVar, endVar, record) {
28
+ const valueVar = nextName(state, "value");
29
+ pushParts(state, [
30
+ `const ${valueVar} = displayValue((`,
31
+ { record },
32
+ "));"
33
+ ]);
34
+ push(state, `if (${slotVar} === null) {`);
35
+ push(state, ` if (${valueVar} !== "") {`);
36
+ const lazyVar = nextName(state, "text");
37
+ push(state, ` const ${lazyVar} = document.createTextNode(${valueVar});`);
38
+ push(state, ` ${endVar}.parentNode.insertBefore(${lazyVar}, ${endVar});`);
39
+ push(state, ` ${state.scopeVar}.addRangeCleanup(() => ${lazyVar}.remove());`);
40
+ push(state, ` ${slotVar} = ${lazyVar};`);
41
+ push(state, ` }`);
42
+ push(state, `} else if (${slotVar}.nodeValue !== ${valueVar}) {`);
43
+ push(state, ` ${slotVar}.nodeValue = ${valueVar};`);
44
+ push(state, `}`);
45
+ }
46
+ /**
47
+ * Claim-period attribute write. Each channel compares the current DOM to the
48
+ * target value. `assertSafeUrlAttribute` runs before setting a string
49
+ * attribute. The first value write to an input preserves live edits when
50
+ * the binding still carries the server default.
51
+ */
52
+ function emitClaimAttributeWrite(state, elementVar, name, channel, record, anchor, inputValueClaim) {
53
+ const literal = JSON.stringify(name);
54
+ if (channel === "boolean") {
55
+ const valueVar = nextName(state, "value");
56
+ pushParts(state, [
57
+ `const ${valueVar} = Boolean((`,
58
+ { record },
59
+ "));"
60
+ ], anchor);
61
+ push(state, `if (${elementVar}.hasAttribute(${literal}) !== ${valueVar}) ${elementVar}.toggleAttribute(${literal}, ${valueVar});`, anchor);
62
+ return;
63
+ }
64
+ if (channel === "property") {
65
+ if (!IDENTIFIER_PATTERN.test(name)) {
66
+ diag(state, "OEIR_LEAF_UNSUPPORTED_ATTRIBUTE", `property '${name}' is not a valid identifier`, {
67
+ file: "",
68
+ start: 0,
69
+ end: 0,
70
+ line: 1,
71
+ column: 1
72
+ });
73
+ return;
74
+ }
75
+ const valueVar = nextName(state, "value");
76
+ pushParts(state, [
77
+ `const ${valueVar} = (`,
78
+ { record },
79
+ ");"
80
+ ], anchor);
81
+ if (inputValueClaim !== void 0) {
82
+ const { first, previous } = inputValueClaim;
83
+ push(state, `if (!${first} && Object.is(${previous}, ${valueVar})) return;`, anchor);
84
+ const liveValue = nextName(state, "liveValue");
85
+ const preserveDraft = nextName(state, "preserveDraft");
86
+ push(state, `const ${liveValue} = ${elementVar}.value;`, anchor);
87
+ push(state, `const ${preserveDraft} = ${first} && ${liveValue} !== ${elementVar}.defaultValue && ${elementVar}.getAttribute("value") === attributeValueOf(${valueVar});`, anchor);
88
+ push(state, `if (!${preserveDraft} && ${liveValue} !== ${valueVar}) ${elementVar}.value = ${valueVar};`, anchor);
89
+ push(state, `${previous} = ${valueVar};`, anchor);
90
+ push(state, `${first} = false;`, anchor);
91
+ return;
92
+ }
93
+ push(state, `if (${elementVar}[${literal}] !== ${valueVar}) ${elementVar}[${literal}] = ${valueVar};`, anchor);
94
+ return;
95
+ }
96
+ const valueVar = nextName(state, "value");
97
+ pushParts(state, [
98
+ `const ${valueVar} = attributeValueOf((`,
99
+ { record },
100
+ "));"
101
+ ], anchor);
102
+ push(state, `if (${valueVar} === null) {`, anchor);
103
+ push(state, ` if (${elementVar}.hasAttribute(${literal})) ${elementVar}.removeAttribute(${literal});`, anchor);
104
+ push(state, `} else if (${elementVar}.getAttribute(${literal}) !== ${valueVar}) {`, anchor);
105
+ push(state, ` assertSafeUrlAttribute(${literal}, ${valueVar});`, anchor);
106
+ push(state, ` ${elementVar}.setAttribute(${literal}, ${valueVar});`, anchor);
107
+ push(state, `}`, anchor);
108
+ }
109
+ /**
110
+ * Claim one pure static directory through the M07b consumer. Ordinals are the
111
+ * generator's own literals, not a scan of the live child list.
112
+ *
113
+ * `activate` is `() => {}` on purpose: this path has no dynamic binding. A
114
+ * directory that admits a dynamic slot must pass a real `activate`. Keeping
115
+ * the empty function there would present an incomplete claim as complete.
116
+ */
117
+ function emitClaimedDirectory(state, parentVar, ranges) {
118
+ state.usesStaticSiblingDirectoryConsumer = true;
119
+ const directory = nextName(state, "directory");
120
+ const declaration = ranges.map((range) => `[${declaredStaticLiteral(range)}]`).join(", ");
121
+ push(state, `const ${directory} = openStaticSiblingDirectory(${parentVar}, [${declaration}], ${JSON.stringify(state.directorySource)});`);
122
+ const adopted = [];
123
+ ranges.forEach((range, ordinal) => {
124
+ const claim = nextName(state, "range");
125
+ push(state, `const ${claim} = claimStaticSiblingRange(${directory}, ${ordinal}, ${state.scopeVar}, () => {});`, range.span);
126
+ const interior = nextName(state, "el");
127
+ push(state, `const ${interior} = ${claim}.interior[0];`);
128
+ adopted.push(interior);
129
+ });
130
+ return adopted;
131
+ }
132
+ /**
133
+ * The emitted mismatch expression. The message prefix, the code and the error
134
+ * options live in the runtime (`claim-invariants.ts`); the compiler names the
135
+ * helper and passes the detail, so no contract string is restated here. The
136
+ * optional authored `anchor` only makes the runtime append its additive
137
+ * ` (authored file:line:column)` suffix.
138
+ */
139
+ function claimError(detail, anchor) {
140
+ return `leafClaimMismatch(${JSON.stringify(detail)}${originArgs(anchor)})`;
141
+ }
142
+ /** Same, for a generated detail expression (the strict list seed mismatch). */
143
+ function claimErrorFrom(detailExpr, anchor) {
144
+ return `leafClaimMismatch(${detailExpr}${originArgs(anchor)})`;
145
+ }
146
+ /** Throw the leaf mismatch. Sets the runtime import flag. */
147
+ function emitClaimMismatch(state, condition, detail, anchor) {
148
+ state.usesLeafClaimMismatch = true;
149
+ push(state, `if (${condition}) throw ${claimError(detail, anchor)};`);
150
+ }
151
+ /**
152
+ * M07a claim parent, its element ancestors, and one claimed element must be
153
+ * in the HTML namespace. Text and comment ancestors are not element checks.
154
+ * A failure here is before any claim write.
155
+ */
156
+ /**
157
+ * The own-element namespace assertion for a claimed SVG subtree (or an HTML
158
+ * element inside an SVG `foreignObject`). Kept beside the HTML ancestor walk so
159
+ * the two claim namespace rules read together.
160
+ */
161
+ function emitClaimElementNamespace(state, nodeExpr, namespace, where, anchor) {
162
+ state.usesLeafClaimMismatch = true;
163
+ push(state, `assertElementInNamespace(${nodeExpr}, ${JSON.stringify(namespace === "svg" ? SVG_NAMESPACE : HTML_NAMESPACE)}, ${JSON.stringify(where)}${originArgs(anchor)});`);
164
+ }
165
+ function emitClaimHtmlNamespace(state, nodeExpr, where, anchor) {
166
+ state.usesLeafClaimMismatch = true;
167
+ push(state, `assertElementInHtmlNamespace(${nodeExpr}, ${JSON.stringify(where)}${originArgs(anchor)});`);
168
+ }
169
+ /**
170
+ * Static attribute seed: the live attributes, with dynamic slot names removed,
171
+ * must equal the declared static attributes in value and order. Names are
172
+ * compared after HTML ASCII case folding: the claim path requires the HTML
173
+ * namespace and the DOM exposes HTML attribute names lowercased, so both the
174
+ * live and the declared names are folded before the name comparison. On a
175
+ * fully static element the skip set is empty, which is the directory rule.
176
+ * Dynamic slot values are claim writes after this check, not part of the seed.
177
+ */
178
+ /**
179
+ * Static attribute seed: emit one call into the runtime predicate. The rule
180
+ * itself (ordered exact set, HTML case-folded names, exact values) lives in
181
+ * `claim-invariants.ts` and is shared with the directory consumer; the
182
+ * generator only names the declared set and the dynamic names the claim writes
183
+ * itself. Nothing about the rule is restated here.
184
+ */
185
+ function emitClaimStaticAttributeSeed(state, elementVar, attributes, where, anchor, nestedHost = false) {
186
+ const staticAttrs = attributes.filter((attribute) => attribute.kind === "static");
187
+ const dynamicNames = attributes.filter((attribute) => attribute.kind === "dynamic" && !CONSUMED_ATTRIBUTE_CHANNELS.has(attribute.channel) && !CLIENT_ONLY_ATTRIBUTE_CHANNELS.has(attribute.channel)).map((attribute) => attribute.name);
188
+ const declared = staticAttrs.map((attribute) => {
189
+ const seedValue = BOOLEAN_ATTRIBUTES.has(attribute.name.toLowerCase()) ? "" : attribute.value;
190
+ return `{ name: ${JSON.stringify(attribute.name)}, value: ${JSON.stringify(seedValue)} }`;
191
+ }).join(", ");
192
+ const skip = `[${dynamicNames.map((name) => JSON.stringify(name)).join(", ")}]`;
193
+ const assertion = nestedHost ? "assertNestedHostStaticAttributeSeed" : "assertStaticAttributeSeed";
194
+ state.usesLeafClaimMismatch = true;
195
+ push(state, `${assertion}(${elementVar}, [${declared}], ${JSON.stringify(where)}, ${skip}${originArgs(anchor)});`);
196
+ }
197
+ function emitClaimTake(state, cursor, name, where, anchor) {
198
+ push(state, `const ${name} = ${cursor}.node;`);
199
+ emitClaimMismatch(state, `${name} == null`, `missing node at ${where}`, anchor);
200
+ push(state, `${cursor}.node = ${name}.nextSibling;`);
201
+ }
202
+ function emitClaimCursorEnd(state, cursor, where, anchor) {
203
+ emitClaimMismatch(state, `${cursor}.node !== null`, `extra node at ${where}`, anchor);
204
+ }
205
+ function prepareClaimSlot(state, expression, records) {
206
+ const record = recordFor(state, expression, records);
207
+ if (record === null || !declareReads(state, record)) return null;
208
+ const dependencies = dependencyNames(state, record);
209
+ if (dependencies === null) return null;
210
+ return {
211
+ record,
212
+ dependencies
213
+ };
214
+ }
215
+ /**
216
+ * M08-2 B2: emit pending phase-2 steps at their current lexical position.
217
+ *
218
+ * The shared-cursor path wraps each emission in a closure pushed onto the
219
+ * module-level activation queue, so block-scoped node bindings stay visible
220
+ * while no subscription/write runs before the cursor owner has validated the
221
+ * whole enclosing structure. That owner captures the queue in `try`, clears the
222
+ * module global in `finally`, and drains the captured local afterwards. The
223
+ * non-shared path keeps inline emission: its root structure check already runs
224
+ * first (and its bindings are function scoped, so deferring would add no
225
+ * safety).
226
+ */
227
+ function emitPhase2Steps(state, steps) {
228
+ if (steps.length === 0) return;
229
+ const activation = state.claimActivationVar;
230
+ if (activation === null) {
231
+ for (const step of steps) step();
232
+ return;
233
+ }
234
+ for (const step of steps) {
235
+ push(state, `${activation}.push(() => {`);
236
+ state.indent += 1;
237
+ step();
238
+ state.indent -= 1;
239
+ push(state, "});");
240
+ }
241
+ }
242
+ /**
243
+ * Emit the shared-cursor owner check plus queue initialization. A nested claim
244
+ * finds the module cursor non-null, appends to the owner's queue and never
245
+ * initializes, captures, clears or drains it. The returned local is the
246
+ * owner-only handoff slot: the success-path capture lands here and the
247
+ * `finally` clears the module global on both exits.
248
+ */
249
+ function emitClaimQueueInit(state, parentExpr) {
250
+ const stepsVar = nextName(state, "phase2Steps");
251
+ push(state, `let ${stepsVar} = null;`);
252
+ push(state, `const ${INTERNAL_PREFIX}cursorOwned = ${INTERNAL_PREFIX}claimCursor === null;`);
253
+ push(state, `if (${INTERNAL_PREFIX}cursorOwned) { ${INTERNAL_PREFIX}claimCursor = { node: ${parentExpr}.firstChild }; ${CLAIM_ACTIVATION} = []; }`);
254
+ return stepsVar;
255
+ }
256
+ /**
257
+ * Success-only handoff. Emitted after the final structure check and every
258
+ * owner-level phase-2 push, immediately before the `finally`: a verify throw
259
+ * therefore never reaches it, while a successful owner detaches the queue from
260
+ * the module global before the first step runs.
261
+ */
262
+ function emitClaimActivationCapture(state, stepsVar) {
263
+ if (state.claimActivationVar !== CLAIM_ACTIVATION) return;
264
+ push(state, `if (${INTERNAL_PREFIX}cursorOwned) ${stepsVar} = ${CLAIM_ACTIVATION};`);
265
+ }
266
+ /**
267
+ * Owner-only release. Runs on success and on every pre-drain throw: cursor and
268
+ * module queue both become null. A nested claim (`cursorOwned` false) is a
269
+ * no-op, so it never detaches the enclosing owner's queue.
270
+ */
271
+ function emitClaimOwnerFinally(state) {
272
+ push(state, `} finally { if (${INTERNAL_PREFIX}cursorOwned) { ${INTERNAL_PREFIX}claimCursor = null; ${CLAIM_ACTIVATION} = null; } }`);
273
+ }
274
+ /**
275
+ * Drain the queue the owner captured in its `try`. Owner-only and success-only
276
+ * by construction: the local array is already detached from the module global,
277
+ * so an activation reentry started by a step owns a different queue and cannot
278
+ * overwrite or extend this drain.
279
+ */
280
+ function emitClaimActivationDrain(state, stepsVar) {
281
+ if (state.claimActivationVar !== CLAIM_ACTIVATION) return;
282
+ const stepVar = nextName(state, "phase2Step");
283
+ push(state, `if (${INTERNAL_PREFIX}cursorOwned) {`);
284
+ state.indent += 1;
285
+ push(state, `for (const ${stepVar} of ${stepsVar}) ${stepVar}();`);
286
+ state.indent -= 1;
287
+ push(state, "}");
288
+ }
289
+ /**
290
+ * Emit the initial write plus its refresh subscription. A zero-dependency slot
291
+ * writes once and registers nothing. The write callback is the claim-period
292
+ * helper: an equal value skips the DOM API, and a dependency still subscribes.
293
+ */
294
+ function emitClaimSlot(state, dependencies, anchor, write, adoptsInputValue = false) {
295
+ const entry = state.claimEntry;
296
+ if (dependencies.length === 0 && entry === null && !adoptsInputValue) {
297
+ write();
298
+ return;
299
+ }
300
+ const refresh = nextName(state, "refresh");
301
+ const inputValueClaim = adoptsInputValue ? {
302
+ first: nextName(state, "firstValueWrite"),
303
+ previous: nextName(state, "previousValue")
304
+ } : void 0;
305
+ if (inputValueClaim !== void 0) {
306
+ push(state, `let ${inputValueClaim.first} = true;`, anchor);
307
+ push(state, `let ${inputValueClaim.previous};`, anchor);
308
+ }
309
+ push(state, `function ${refresh}() {`, anchor);
310
+ state.indent += 1;
311
+ write(inputValueClaim);
312
+ state.indent -= 1;
313
+ push(state, `}`);
314
+ if (entry !== null) {
315
+ entry.refreshes.push(refresh);
316
+ entry.activate.push(() => {
317
+ push(state, `${refresh}();`);
318
+ if (dependencies.length > 0) emitDependencySubscriptions(state, dependencies, refresh, anchor);
319
+ });
320
+ return;
321
+ }
322
+ push(state, `${refresh}();`);
323
+ emitDependencySubscriptions(state, dependencies, refresh, anchor);
324
+ }
325
+ /**
326
+ * One condition-branch claim chunk. The emitted function is the read-only half
327
+ * of the condition claim: it walks the client branch template against the
328
+ * shared `{node}` cursor, adopts its nodes, and returns an `activate` closure
329
+ * whose body is emitted only from the caller's phase-2 steps. Calling the
330
+ * function therefore performs no subscription and no DOM write; the claim walk
331
+ * for the enclosing tree stays read-only until the root flush.
332
+ *
333
+ * The function is a chunk: its text-slot ordinals restart at 0 and its static
334
+ * top-level runs use the same normalized view as mount/SSR. Its internal cursor
335
+ * is the explicit parameter, so the shared-cursor mode is disabled while its
336
+ * body is emitted; the caller passes either a local cursor object or the
337
+ * module-level shared cursor object.
338
+ */
339
+ function emitClaimConditionBranchBuilder(state, functionName, scopeParam, cursorParam, nodes, records, path, anchor) {
340
+ push(state, `function ${functionName}(${scopeParam}, ${cursorParam}) {`, anchor);
341
+ state.indent += 1;
342
+ const outerScope = state.scopeVar;
343
+ const outerOrdinals = state.textOrdinals;
344
+ const outerShared = state.claimCursorShared;
345
+ const outerActivation = state.claimActivationVar;
346
+ state.scopeVar = scopeParam;
347
+ state.claimCursorShared = false;
348
+ state.claimActivationVar = null;
349
+ const prepared = emissionNodes(state, nodes);
350
+ state.textOrdinals = textSlotOrdinals(prepared);
351
+ const nodesVar = nextName(state, "branchNodes");
352
+ push(state, `const ${nodesVar} = [];`);
353
+ const phase2 = [];
354
+ emitClaimInto(state, prepared, cursorParam, path, records, phase2, (name) => {
355
+ push(state, `${nodesVar}.push(${name});`);
356
+ }, (name, condition) => {
357
+ push(state, `if (${condition}) ${nodesVar}.push(${name});`);
358
+ }, "null", false);
359
+ push(state, "function activate() {");
360
+ state.indent += 1;
361
+ emitPhase2Steps(state, phase2);
362
+ state.indent -= 1;
363
+ push(state, "}");
364
+ push(state, `return { nodes: ${nodesVar}, activate };`);
365
+ state.textOrdinals = outerOrdinals;
366
+ state.claimCursorShared = outerShared;
367
+ state.claimActivationVar = outerActivation;
368
+ state.scopeVar = outerScope;
369
+ state.indent -= 1;
370
+ push(state, "}");
371
+ }
372
+ /**
373
+ * Claim one condition. Verify is read-only: the anchor/end are asserted, the
374
+ * test is evaluated once, the selected client branch is adopted through its
375
+ * read-only claim chunk (or a server-empty branch is marked for insert), and
376
+ * the owner/nodes are registered. Subscription and writes are queued on
377
+ * `phase2`; the caller flushes them only after the whole claim walk succeeded.
378
+ *
379
+ * There is no branch id. A branch is identified by the client template's own
380
+ * structure, static attribute seed, text values and slot ordinals, which the
381
+ * ordinary claim walk already checks. A server branch that does not match the
382
+ * client branch is a mismatch; a server-empty branch is the only insertion
383
+ * path, and it is explicitly non-transactional activation work.
384
+ */
385
+ function emitConditionClaim(state, node, cursor, path, records, phase2, adopt) {
386
+ const slot = prepareClaimSlot(state, node.test, records);
387
+ if (slot === null) return;
388
+ const here = path;
389
+ const anchorVar = nextName(state, "whenAnchor");
390
+ push(state, `const ${anchorVar} = ${cursor}.node;`, node.span);
391
+ push(state, `assertWhenAnchor(${anchorVar}, ${JSON.stringify(`${here}/anchor`)}${originArgs(node.span)});`, node.span);
392
+ push(state, `${cursor}.node = ${anchorVar}.nextSibling;`);
393
+ const thenCreate = node.consequent.length > 0 ? nextName(state, "whenThen") : null;
394
+ if (thenCreate !== null) emitNodesBuilder(state, thenCreate, nextName(state, "whenThenScope"), node.consequent, records, node.span);
395
+ const elseCreate = node.alternate !== null && node.alternate.length > 0 ? nextName(state, "whenElse") : null;
396
+ if (elseCreate !== null) emitNodesBuilder(state, elseCreate, nextName(state, "whenElseScope"), node.alternate, records, node.span);
397
+ const thenClaim = node.consequent.length > 0 ? nextName(state, "whenThenClaim") : null;
398
+ if (thenClaim !== null) emitClaimConditionBranchBuilder(state, thenClaim, nextName(state, "whenThenClaimScope"), cursor, node.consequent, records, `${here}/then`, node.span);
399
+ const elseClaim = node.alternate !== null && node.alternate.length > 0 ? nextName(state, "whenElseClaim") : null;
400
+ if (elseClaim !== null) emitClaimConditionBranchBuilder(state, elseClaim, nextName(state, "whenElseClaimScope"), cursor, node.alternate, records, `${here}/else`, node.span);
401
+ const testVar = nextName(state, "whenTest");
402
+ pushParts(state, [
403
+ `const ${testVar} = (`,
404
+ { record: slot.record },
405
+ ");"
406
+ ], node.span);
407
+ const activeVar = nextName(state, "whenActive");
408
+ const emptyActive = elseCreate === null ? 0 : 2;
409
+ push(state, `let ${activeVar} = ${testVar} ? 1 : ${emptyActive};`);
410
+ const ownerVar = nextName(state, "whenOwner");
411
+ const nodesVar = nextName(state, "whenNodes");
412
+ const adoptedVar = nextName(state, "whenAdopted");
413
+ const insertVar = nextName(state, "whenInsert");
414
+ push(state, `let ${ownerVar} = null;`);
415
+ push(state, `let ${nodesVar} = [];`);
416
+ push(state, `let ${adoptedVar} = null;`);
417
+ push(state, `let ${insertVar} = false;`);
418
+ const verifyBranch = (activeValue, claimFn) => {
419
+ push(state, `if (${activeVar} === ${activeValue}) {`);
420
+ state.indent += 1;
421
+ if (claimFn !== null) {
422
+ push(state, `if (isWhenEndMarker(${cursor}.node)) {`);
423
+ state.indent += 1;
424
+ push(state, `${insertVar} = true;`);
425
+ state.indent -= 1;
426
+ push(state, `} else {`);
427
+ state.indent += 1;
428
+ push(state, `${ownerVar} = ${state.scopeVar}.child();`);
429
+ push(state, "try {");
430
+ state.indent += 1;
431
+ push(state, `${adoptedVar} = ${claimFn}(${ownerVar}, ${cursor});`, node.span);
432
+ state.indent -= 1;
433
+ push(state, `} catch (error) { ${ownerVar}.dispose(false); throw error; }`);
434
+ push(state, `${nodesVar} = ${adoptedVar}.nodes;`);
435
+ state.indent -= 1;
436
+ push(state, "}");
437
+ }
438
+ state.indent -= 1;
439
+ push(state, "}");
440
+ };
441
+ verifyBranch(1, thenClaim);
442
+ verifyBranch(2, elseClaim);
443
+ push(state, `assertWhenEndMarker(${cursor}.node, ${JSON.stringify(`${here}/end`)}${originArgs(node.span)});`, node.span);
444
+ const endVar = nextName(state, "whenEnd");
445
+ push(state, `const ${endVar} = ${cursor}.node;`);
446
+ push(state, `${cursor}.node = ${endVar}.nextSibling;`);
447
+ push(state, `if (${ownerVar} === null) ${ownerVar} = ${state.scopeVar}.child();`);
448
+ push(state, `${ownerVar}.addRangeCleanup(() => removeNodes(${nodesVar}));`, node.span);
449
+ adopt(anchorVar);
450
+ const childVar = nextName(state, "whenChild");
451
+ push(state, `for (const ${childVar} of ${nodesVar}) {`);
452
+ adopt(childVar);
453
+ push(state, "}");
454
+ adopt(endVar);
455
+ const refreshVar = nextName(state, "whenRefresh");
456
+ const nextVar = nextName(state, "whenNext");
457
+ const branchOwnerVar = nextName(state, "whenBranchOwner");
458
+ const branchNodesVar = nextName(state, "whenBranchNodes");
459
+ const refreshParentVar = nextName(state, "whenParent");
460
+ push(state, `function ${refreshVar}(force) {`, node.span);
461
+ state.indent += 1;
462
+ pushParts(state, [
463
+ `const ${nextVar} = (`,
464
+ { record: slot.record },
465
+ `) ? 1 : ${emptyActive};`
466
+ ], node.span);
467
+ push(state, `if (!force && ${nextVar} === ${activeVar}) return;`);
468
+ push(state, `${activeVar} = -1;`);
469
+ if (emitsRetentionReleaseText(state)) emitBranchRelease(state, ownerVar);
470
+ else push(state, `if (${ownerVar} !== null) ${ownerVar}.dispose(true);`);
471
+ push(state, `${ownerVar} = null;`);
472
+ push(state, `const ${branchOwnerVar} = ${state.scopeVar}.child();`);
473
+ push(state, `let ${branchNodesVar};`);
474
+ push(state, "try {");
475
+ state.indent += 1;
476
+ const thenCall = thenCreate === null ? "[]" : `${thenCreate}(${branchOwnerVar})`;
477
+ const elseCall = elseCreate === null ? "[]" : `${elseCreate}(${branchOwnerVar})`;
478
+ push(state, `${branchNodesVar} = runUntracked(() => ${nextVar} === 1 ? ${thenCall} : ${elseCall});`);
479
+ state.indent -= 1;
480
+ if (emitsRetentionReleaseText(state)) emitBranchRollback(state, branchOwnerVar, activeVar);
481
+ else push(state, `} catch (error) { ${activeVar} = -1; ${branchOwnerVar}.dispose(true); throw error; }`);
482
+ push(state, `${branchOwnerVar}.addRangeCleanup(() => removeNodes(${branchNodesVar}));`);
483
+ push(state, `const ${refreshParentVar} = ${endVar}.parentNode;`);
484
+ push(state, `if (${refreshParentVar} !== null) { for (const ${childVar} of ${branchNodesVar}) ${refreshParentVar}.insertBefore(${childVar}, ${endVar}); }`);
485
+ push(state, `${nodesVar} = ${branchNodesVar}; ${ownerVar} = ${branchOwnerVar}; ${activeVar} = ${nextVar};`);
486
+ state.indent -= 1;
487
+ push(state, "}");
488
+ phase2.push(() => {
489
+ push(state, `if (${adoptedVar} !== null) ${adoptedVar}.activate();`);
490
+ });
491
+ if (slot.dependencies.length > 0) phase2.push(() => {
492
+ emitDependencySubscriptions(state, slot.dependencies, refreshVar, node.span, { ignoreSignalValue: true });
493
+ });
494
+ if (thenCreate !== null || elseCreate !== null) phase2.push(() => {
495
+ push(state, `if (${insertVar}) {`);
496
+ state.indent += 1;
497
+ const insertNodesVar = nextName(state, "whenInsertNodes");
498
+ const insertParentVar = nextName(state, "whenInsertParent");
499
+ push(state, `let ${insertNodesVar};`);
500
+ push(state, "try {");
501
+ state.indent += 1;
502
+ const insertThen = thenCreate === null ? "[]" : `${thenCreate}(${ownerVar})`;
503
+ const insertElse = elseCreate === null ? "[]" : `${elseCreate}(${ownerVar})`;
504
+ push(state, `${insertNodesVar} = ${activeVar} === 1 ? ${insertThen} : ${insertElse};`);
505
+ state.indent -= 1;
506
+ push(state, `} catch (error) { ${ownerVar}.dispose(true); throw error; }`);
507
+ push(state, `const ${insertParentVar} = ${endVar}.parentNode;`);
508
+ push(state, `if (${insertParentVar} !== null) { for (const ${childVar} of ${insertNodesVar}) ${insertParentVar}.insertBefore(${childVar}, ${endVar}); }`);
509
+ push(state, `${nodesVar} = ${insertNodesVar};`);
510
+ state.indent -= 1;
511
+ push(state, "}");
512
+ });
513
+ }
514
+ /**
515
+ * One list-entry claim chunk. The walk is read-only: it adopts the entry's
516
+ * existing marker/content through the shared cursor and creates no DOM node,
517
+ * opens no subscription and writes no value. Every dynamic slot becomes a
518
+ * named refresh at this function's scope (zero-dependency slots included), so
519
+ * `update(next)` can rebind the mapper parameter and re-render the same nodes
520
+ * (the M06b2c entry-local rule). `activate(next)` rebinds the item, runs the
521
+ * compare-write refresh once and opens the entry-local subscriptions; the
522
+ * enclosing claim calls it only from the activation phase.
523
+ */
524
+ function emitClaimEntryBuilder(state, functionName, scopeParam, cursorParam, itemParam, itemName, nodes, records, path, anchor) {
525
+ push(state, `function ${functionName}(${scopeParam}, ${cursorParam}, ${itemParam}) {`, anchor);
526
+ state.indent += 1;
527
+ const outerScope = state.scopeVar;
528
+ const outerOrdinals = state.textOrdinals;
529
+ const outerShared = state.claimCursorShared;
530
+ const outerActivation = state.claimActivationVar;
531
+ const outerEntry = state.claimEntry;
532
+ state.scopeVar = scopeParam;
533
+ state.claimCursorShared = false;
534
+ state.claimActivationVar = null;
535
+ const entry = {
536
+ refreshes: [],
537
+ activate: []
538
+ };
539
+ state.claimEntry = entry;
540
+ const outerEntryName = state.entryNames.has(itemName);
541
+ state.entryNames.add(itemName);
542
+ const prepared = emissionNodes(state, nodes);
543
+ state.textOrdinals = textSlotOrdinals(prepared);
544
+ const nodesVar = nextName(state, "entryNodes");
545
+ push(state, `const ${nodesVar} = [];`);
546
+ push(state, `let ${itemName} = ${itemParam};`);
547
+ const phase2 = [];
548
+ emitClaimInto(state, prepared, cursorParam, path, records, phase2, (name) => push(state, `${nodesVar}.push(${name});`), (name, condition) => push(state, `if (${condition}) ${nodesVar}.push(${name});`), "null", false);
549
+ emitPhase2Steps(state, phase2);
550
+ push(state, "function activate(next) {");
551
+ state.indent += 1;
552
+ push(state, `${itemName} = next;`);
553
+ for (const step of entry.activate) step();
554
+ state.indent -= 1;
555
+ push(state, "}");
556
+ const update = [`${itemName} = next;`, ...entry.refreshes.map((name) => `${name}(true);`)].join(" ");
557
+ push(state, `return { nodes: ${nodesVar}, activate, update(next) { ${update} } };`);
558
+ if (!outerEntryName) state.entryNames.delete(itemName);
559
+ state.textOrdinals = outerOrdinals;
560
+ state.claimCursorShared = outerShared;
561
+ state.claimActivationVar = outerActivation;
562
+ state.claimEntry = outerEntry;
563
+ state.scopeVar = outerScope;
564
+ state.indent -= 1;
565
+ push(state, "}");
566
+ }
567
+ /**
568
+ * One claim-time keyed sync. `previous` is the seeded list on the strict first
569
+ * call and the live entry list afterwards. Matching keeps mount's
570
+ * `entry.key === key` identity plus the mount used-set rule, so duplicate
571
+ * client keys adopt the wire entry once per occurrence and insert the
572
+ * remainder. The strict call is the seed assignment's defense: an unmatched
573
+ * seeded entry is a mismatch, never a delete. The non-strict refresh disposes
574
+ * removed entries exactly like mount.
575
+ *
576
+ * Every key is preflighted with `encodeListKey` before any mutation, and an
577
+ * inserted entry writes its marker from `encodeListKey`, never the mount-only
578
+ * `u` payload. An unsupported update therefore fails closed with the old DOM,
579
+ * owners and entries intact; the caller's refresh assignment keeps the previous
580
+ * entry list, so a later legal signal value recovers.
581
+ */
582
+ function emitClaimListSync(state, functionName, entryCreateFn, endVar, path, anchor) {
583
+ push(state, `function ${functionName}(items, keys, previous, strict) {`, anchor);
584
+ state.indent += 1;
585
+ push(state, "for (const key of keys) encodeListKey(key);");
586
+ push(state, "const next = [];");
587
+ push(state, "const used = new Set();");
588
+ push(state, "for (let index = 0; index < items.length; index++) {");
589
+ state.indent += 1;
590
+ push(state, "const item = items[index];");
591
+ push(state, "const key = keys[index];");
592
+ push(state, "let found = null;");
593
+ push(state, "for (const entry of previous) { if (entry.key === key && !used.has(entry)) { found = entry; break; } }");
594
+ push(state, "if (found !== null) {");
595
+ state.indent += 1;
596
+ push(state, "used.add(found); found.item = item; found.update(item); next.push(found);");
597
+ state.indent -= 1;
598
+ push(state, "} else {");
599
+ state.indent += 1;
600
+ push(state, `const owner = ${state.scopeVar}.child();`);
601
+ push(state, "let built;");
602
+ push(state, "try {");
603
+ state.indent += 1;
604
+ push(state, `built = ${entryCreateFn}(owner, item);`);
605
+ state.indent -= 1;
606
+ push(state, "} catch (error) { owner.dispose(true); throw error; }");
607
+ push(state, "const token = encodeListKey(key);");
608
+ push(state, "built.nodes.unshift(emitComment(entryKeyMarker(token)));");
609
+ push(state, "owner.addRangeCleanup(() => removeNodes(built.nodes));");
610
+ push(state, "next.push({ key, item, owner, nodes: built.nodes, update: built.update });");
611
+ state.indent -= 1;
612
+ push(state, "}");
613
+ state.indent -= 1;
614
+ push(state, "}");
615
+ push(state, "for (const entry of previous) if (!used.has(entry)) {");
616
+ state.indent += 1;
617
+ push(state, `if (strict) throw ${claimError(`server entry key has no client item at ${path}/each`, anchor)};`);
618
+ push(state, "entry.owner.dispose(true);");
619
+ state.indent -= 1;
620
+ push(state, "}");
621
+ push(state, `const parent = ${endVar}.parentNode;`);
622
+ push(state, "if (parent !== null) {");
623
+ state.indent += 1;
624
+ push(state, `let reference = ${endVar};`);
625
+ push(state, "for (let entryIndex = next.length - 1; entryIndex >= 0; entryIndex--) {");
626
+ state.indent += 1;
627
+ push(state, "const nodes = next[entryIndex].nodes;");
628
+ push(state, "for (let nodeIndex = nodes.length - 1; nodeIndex >= 0; nodeIndex--) {");
629
+ state.indent += 1;
630
+ push(state, "const node = nodes[nodeIndex];");
631
+ push(state, "if (node.parentNode !== parent || node.nextSibling !== reference) parent.insertBefore(node, reference);");
632
+ push(state, "reference = node;");
633
+ state.indent -= 1;
634
+ push(state, "}");
635
+ state.indent -= 1;
636
+ push(state, "}");
637
+ state.indent -= 1;
638
+ push(state, "}");
639
+ push(state, "return next;");
640
+ state.indent -= 1;
641
+ push(state, "}");
642
+ }
643
+ /**
644
+ * Claim one keyed (or unkeyed positional) list.
645
+ *
646
+ * Verify order is deliberate: anchor, every `oe:k:` entry and its read-only
647
+ * template adoption, the `oe:/each` end, then one items evaluation and one key
648
+ * evaluation per item. The seed predicate runs before any assignment write or
649
+ * activation; a wire token with more occurrences than the client list, an extra
650
+ * wire token or an unsupported wire key leaves the borrowed DOM untouched and
651
+ * opens no subscription. The seed predicate's client-key failure is also the
652
+ * only place an unsupported client key can stop the claim. Each wire occurrence
653
+ * is assigned the next client occurrence of the same token, so duplicates are
654
+ * distinct identities and reorder is grouped per token.
655
+ *
656
+ * Activation is queued on the shared phase-2 path: every seeded entry activates
657
+ * (compare-write refresh + subscriptions), then the list/key outer
658
+ * subscriptions, then one strict sync. A client-more seed inserts after that;
659
+ * reorder only moves existing nodes. No seeded node is ever deleted. The strict
660
+ * sync preflights every key with `encodeListKey`, so an unsupported key throws
661
+ * before any DOM write (the claimed `u`-free contract).
662
+ */
663
+ function emitClaimList(state, node, cursor, path, records, phase2, adopt) {
664
+ const slot = prepareClaimSlot(state, node.items, records);
665
+ if (slot === null) return;
666
+ const here = path;
667
+ const anchorVar = nextName(state, "eachAnchor");
668
+ push(state, `const ${anchorVar} = ${cursor}.node;`, node.span);
669
+ push(state, `assertEachAnchor(${anchorVar}, ${JSON.stringify(`${here}/each/anchor`)}${originArgs(node.span)});`, node.span);
670
+ push(state, `${cursor}.node = ${anchorVar}.nextSibling;`);
671
+ adopt(anchorVar);
672
+ const entryClaimFn = nextName(state, "eachEntryClaim");
673
+ emitClaimEntryBuilder(state, entryClaimFn, nextName(state, "eachEntryClaimScope"), cursor, nextName(state, "eachEntryItem"), node.parameter, node.template, records, `${here}/each/entry`, node.span);
674
+ const entryCreateFn = nextName(state, "eachEntryCreate");
675
+ state.listDepth += 1;
676
+ try {
677
+ emitEntryBuilder(state, entryCreateFn, nextName(state, "eachCreateScope"), nextName(state, "eachCreateItem"), node.parameter, node.template, records, node.span);
678
+ } finally {
679
+ state.listDepth -= 1;
680
+ }
681
+ const keyFn = nextName(state, "eachKey");
682
+ const keyInfo = emitListKeyFunction(state, keyFn, node, records);
683
+ if (keyInfo === null) return;
684
+ const keyDependencies = keyInfo.dependencies;
685
+ const wireTokensVar = nextName(state, "eachWireTokens");
686
+ const seededVar = nextName(state, "eachSeeded");
687
+ push(state, `const ${wireTokensVar} = [];`);
688
+ push(state, `const ${seededVar} = [];`);
689
+ push(state, "for (;;) {");
690
+ state.indent += 1;
691
+ const markerVar = nextName(state, "entryMarker");
692
+ push(state, `const ${markerVar} = ${cursor}.node;`);
693
+ const parsedVar = nextName(state, "entryParsed");
694
+ push(state, `const ${parsedVar} = ${markerVar} !== null && ${markerVar}.nodeType === 8 ? parseEntryKeyMarker(${markerVar}.nodeValue) : null;`);
695
+ push(state, `if (${parsedVar} === null) break;`);
696
+ const tokenVar = nextName(state, "entryToken");
697
+ push(state, `const ${tokenVar} = readEntryKeyMarker(${markerVar}, ${JSON.stringify(`${here}/each/entry`)}${originArgs(node.span)});`);
698
+ push(state, `${cursor}.node = ${markerVar}.nextSibling;`);
699
+ const ownerVar = nextName(state, "entryOwner");
700
+ push(state, `const ${ownerVar} = ${state.scopeVar}.child();`);
701
+ const builtVar = nextName(state, "entryBuilt");
702
+ push(state, `let ${builtVar};`);
703
+ push(state, "try {");
704
+ state.indent += 1;
705
+ push(state, `${builtVar} = ${entryClaimFn}(${ownerVar}, ${cursor}, null);`);
706
+ state.indent -= 1;
707
+ push(state, `} catch (error) { ${ownerVar}.dispose(false); throw error; }`);
708
+ push(state, `${ownerVar}.addRangeCleanup(() => removeNodes([${markerVar}, ...${builtVar}.nodes]));`);
709
+ const seededEntryVar = nextName(state, "entry");
710
+ push(state, `const ${seededEntryVar} = { token: ${tokenVar}, key: null, item: null, assigned: false, owner: ${ownerVar}, nodes: [${markerVar}, ...${builtVar}.nodes], activate: ${builtVar}.activate, update: ${builtVar}.update };`);
711
+ push(state, `${seededVar}.push(${seededEntryVar}); ${wireTokensVar}.push(${tokenVar});`);
712
+ adopt(markerVar);
713
+ const adoptedChildVar = nextName(state, "entryChild");
714
+ push(state, `for (const ${adoptedChildVar} of ${builtVar}.nodes) {`);
715
+ adopt(adoptedChildVar);
716
+ push(state, "}");
717
+ state.indent -= 1;
718
+ push(state, "}");
719
+ push(state, `assertEachEndMarker(${cursor}.node, ${JSON.stringify(`${here}/each/end`)}${originArgs(node.span)});`, node.span);
720
+ const endVar = nextName(state, "eachEnd");
721
+ push(state, `const ${endVar} = ${cursor}.node;`);
722
+ push(state, `${cursor}.node = ${endVar}.nextSibling;`);
723
+ adopt(endVar);
724
+ const itemsVar = nextName(state, "eachItems");
725
+ pushParts(state, [
726
+ `const ${itemsVar} = (`,
727
+ { record: slot.record },
728
+ ");"
729
+ ], node.span);
730
+ const keysVar = nextName(state, "eachKeys");
731
+ const tokensVar = nextName(state, "eachTokens");
732
+ push(state, `const ${keysVar} = [];`);
733
+ push(state, `const ${tokensVar} = [];`);
734
+ push(state, `for (let index = 0; index < ${itemsVar}.length; index++) {`);
735
+ state.indent += 1;
736
+ push(state, `const key = ${keyFn}(${itemsVar}[index], index);`);
737
+ push(state, `${keysVar}.push(key); ${tokensVar}.push(tryEncodeListKey(key));`);
738
+ state.indent -= 1;
739
+ push(state, "}");
740
+ const mismatchVar = nextName(state, "seedMismatch");
741
+ push(state, `const ${mismatchVar} = entrySeedMismatch(${wireTokensVar}, ${tokensVar});`);
742
+ const seedDetail = `${mismatchVar} + ${JSON.stringify(` at ${here}/each`)}`;
743
+ push(state, `if (${mismatchVar} !== null) throw ${claimErrorFrom(seedDetail, node.span)};`);
744
+ push(state, `for (let index = 0; index < ${itemsVar}.length; index++) {`);
745
+ state.indent += 1;
746
+ push(state, `const token = ${tokensVar}[index];`);
747
+ push(state, "if (token === null) continue;");
748
+ push(state, `for (const entry of ${seededVar}) {`);
749
+ state.indent += 1;
750
+ push(state, `if (!entry.assigned && entry.token === token) { entry.assigned = true; entry.key = ${keysVar}[index]; entry.item = ${itemsVar}[index]; break; }`);
751
+ state.indent -= 1;
752
+ push(state, "}");
753
+ state.indent -= 1;
754
+ push(state, "}");
755
+ push(state, `for (const entry of ${seededVar}) if (!entry.assigned) throw ${claimError(`server entry key has no client item at ${here}/each`, node.span)};`);
756
+ const entriesVar = nextName(state, "eachEntries");
757
+ push(state, `let ${entriesVar} = [];`);
758
+ const syncFn = nextName(state, "eachSync");
759
+ emitClaimListSync(state, syncFn, entryCreateFn, endVar, here, node.span);
760
+ const refreshVar = nextName(state, "eachRefresh");
761
+ push(state, `function ${refreshVar}() {`, node.span);
762
+ state.indent += 1;
763
+ const refreshItemsVar = nextName(state, "eachItems");
764
+ pushParts(state, [
765
+ `const ${refreshItemsVar} = (`,
766
+ { record: slot.record },
767
+ ");"
768
+ ], node.span);
769
+ const refreshKeysVar = nextName(state, "eachKeys");
770
+ push(state, `const ${refreshKeysVar} = [];`);
771
+ push(state, `for (let index = 0; index < ${refreshItemsVar}.length; index++) {`);
772
+ state.indent += 1;
773
+ push(state, `${refreshKeysVar}.push(${keyFn}(${refreshItemsVar}[index], index));`);
774
+ state.indent -= 1;
775
+ push(state, "}");
776
+ push(state, `${entriesVar} = ${syncFn}(${refreshItemsVar}, ${refreshKeysVar}, ${entriesVar}, false);`);
777
+ state.indent -= 1;
778
+ push(state, "}");
779
+ phase2.push(() => {
780
+ push(state, `for (const entry of ${seededVar}) entry.activate(entry.item);`);
781
+ });
782
+ const subscribed = /* @__PURE__ */ new Set();
783
+ const uniqueDependencies = [];
784
+ for (const dependency of [...slot.dependencies, ...keyDependencies]) {
785
+ if (subscribed.has(dependency.name)) continue;
786
+ subscribed.add(dependency.name);
787
+ uniqueDependencies.push(dependency);
788
+ }
789
+ if (uniqueDependencies.length > 0) phase2.push(() => {
790
+ emitDependencySubscriptions(state, uniqueDependencies, refreshVar, node.span);
791
+ });
792
+ phase2.push(() => {
793
+ push(state, `${entriesVar} = ${syncFn}(${itemsVar}, ${keysVar}, ${seededVar}, true);`);
794
+ });
795
+ registerRefresh(state, refreshVar);
796
+ }
797
+ function emitClaimInto(state, nodes, cursor, path, records, phase2, adopt, adoptIf, parentExpr, collect, namespace = "html") {
798
+ (state.emitTextBoundaries ? normalizeTextRuns(nodes) : nodes).forEach((node, index) => {
799
+ if (state.diagnostics.length > 0) return;
800
+ const here = `${path}/${index}`;
801
+ if (node.kind === "condition") {
802
+ emitConditionClaim(state, node, cursor, here, records, phase2, adopt);
803
+ return;
804
+ }
805
+ if (node.kind === "list") {
806
+ emitClaimList(state, node, cursor, here, records, phase2, adopt);
807
+ return;
808
+ }
809
+ if (node.kind === "fragment") {
810
+ emitClaimInto(state, node.children, cursor, here, records, phase2, adopt, adoptIf, parentExpr, collect, namespace);
811
+ return;
812
+ }
813
+ if (node.kind === "insertion-site") {
814
+ emitClaimInsertion(state, node, parentExpr, collect);
815
+ return;
816
+ }
817
+ if (node.kind === "children-projection") {
818
+ emitClaimChildrenProjection(state, node, parentExpr, collect);
819
+ return;
820
+ }
821
+ if (node.kind === "component-ref") {
822
+ emitClaimComponentRef(state, node, records, parentExpr, collect);
823
+ return;
824
+ }
825
+ if (node.kind === "text") {
826
+ const name = nextName(state, "text");
827
+ emitClaimTake(state, cursor, name, here, node.span);
828
+ emitClaimMismatch(state, `${name}.nodeType !== 3 || ${name}.nodeValue !== ${JSON.stringify(node.value)}`, `static text at ${here}`, node.span);
829
+ adopt(name);
830
+ return;
831
+ }
832
+ if (node.kind === "dynamic-text") {
833
+ const slot = prepareClaimSlot(state, node.expression, records);
834
+ if (slot === null) return;
835
+ const ordinal = textOrdinal(state, node);
836
+ if (ordinal === null) return;
837
+ const start = nextName(state, "textStart");
838
+ emitClaimTake(state, cursor, start, `${here}/text-start`, node.span);
839
+ push(state, `assertTextSlotMarker(${start}, ${ordinal}, false, ${JSON.stringify(`${here}/text-start`)}${originArgs(node.span)});`, node.span);
840
+ const slotText = nextName(state, "slotText");
841
+ push(state, `let ${slotText} = null;`);
842
+ const maybeText = nextName(state, "maybeText");
843
+ push(state, `const ${maybeText} = ${cursor}.node;`);
844
+ push(state, `if (${maybeText} !== null && ${maybeText}.nodeType === 3) {`);
845
+ push(state, ` ${slotText} = ${maybeText};`);
846
+ push(state, ` ${cursor}.node = ${maybeText}.nextSibling;`);
847
+ push(state, `}`);
848
+ const end = nextName(state, "textEnd");
849
+ emitClaimTake(state, cursor, end, `${here}/text-end`, node.span);
850
+ push(state, `assertTextSlotMarker(${end}, ${ordinal}, true, ${JSON.stringify(`${here}/text-end`)}${originArgs(node.span)});`, node.span);
851
+ adopt(start);
852
+ adoptIf(slotText, `${slotText} !== null`);
853
+ adopt(end);
854
+ phase2.push(() => emitClaimSlot(state, slot.dependencies, node.span, () => emitClaimTextSlotWrite(state, slotText, end, slot.record)));
855
+ return;
856
+ }
857
+ if (node.kind === "element") {
858
+ const name = nextName(state, "el");
859
+ const isNestedHost = node.tag.includes("-");
860
+ emitClaimTake(state, cursor, name, here, node.span);
861
+ emitClaimMismatch(state, `${name}.nodeType !== 1 || String(${name}.localName || ${name}.tagName || "").toLowerCase() !== ${JSON.stringify(node.tag)}`, `expected element '${node.tag}' at ${here}`, node.span);
862
+ const elementNamespace = node.tag === "svg" ? "svg" : namespace;
863
+ if (elementNamespace === "svg") emitClaimElementNamespace(state, name, "svg", here, node.span);
864
+ else if (namespace === "svg") emitClaimElementNamespace(state, name, "html", here, node.span);
865
+ else emitClaimHtmlNamespace(state, name, here, node.span);
866
+ emitClaimStaticAttributeSeed(state, name, node.attributes, here, node.span, isNestedHost);
867
+ for (const attribute of node.attributes) {
868
+ if (attribute.kind === "static") continue;
869
+ if (attribute.kind === "dynamic" && CONSUMED_ATTRIBUTE_CHANNELS.has(attribute.channel)) continue;
870
+ if (attribute.kind === "dynamic" && CLIENT_ONLY_ATTRIBUTE_CHANNELS.has(attribute.channel)) {
871
+ if (!clientOnlyAttributeAdmitted(state, node.tag, attribute.name, attribute.span)) return;
872
+ const record = recordFor(state, attribute.expression, records);
873
+ if (record === null || !declareReads(state, record)) return;
874
+ const elementName = name;
875
+ const clientAttribute = attribute;
876
+ phase2.push(() => emitClientOnlyInstall(state, elementName, clientAttribute, record));
877
+ continue;
878
+ }
879
+ const slot = prepareClaimSlot(state, attribute.expression, records);
880
+ if (slot === null) return;
881
+ const attributeName = attribute.name;
882
+ const channel = attribute.channel;
883
+ const span = attribute.span;
884
+ const adoptsInputValue = elementNamespace === "html" && node.tag === "input" && channel === "property" && attributeName === "value";
885
+ phase2.push(() => emitClaimSlot(state, slot.dependencies, span, (inputValueClaim) => emitClaimAttributeWrite(state, name, attributeName, channel, slot.record, span, inputValueClaim), adoptsInputValue));
886
+ }
887
+ const ranges = directoryParentAllowed(node.tag) ? staticElementDirectory(node.children) : null;
888
+ const emitClaimChildren = () => {
889
+ if (ranges !== null) {
890
+ emitClaimedDirectory(state, name, ranges);
891
+ return;
892
+ }
893
+ const childCursor = nextName(state, "cursor");
894
+ push(state, `const ${childCursor} = { node: ${name}.firstChild };`);
895
+ const saved = state.claimCursorShared ? nextName(state, "savedCursor") : null;
896
+ const childPhase2 = [];
897
+ if (saved !== null) {
898
+ push(state, `const ${saved} = __oe_claimCursor;`);
899
+ push(state, `__oe_claimCursor = ${childCursor};`);
900
+ push(state, "try {");
901
+ state.indent += 1;
902
+ }
903
+ emitClaimInto(state, node.children, childCursor, here, records, saved !== null ? childPhase2 : phase2, () => {}, () => {}, name, false, elementNamespace);
904
+ emitClaimCursorEnd(state, childCursor, here, node.span);
905
+ if (saved !== null) {
906
+ emitPhase2Steps(state, childPhase2);
907
+ state.indent -= 1;
908
+ push(state, `} finally { __oe_claimCursor = ${saved}; }`);
909
+ }
910
+ };
911
+ if (isNestedHost && node.children.length === 0) emitClaimMismatch(state, `!isExpandedLightRootHost(${name}) && ${name}.firstChild !== null`, `extra node at ${here}`, node.span);
912
+ else if (isNestedHost) {
913
+ push(state, `if (isExpandedLightRootHost(${name})) { /* child-owned fallback */ } else {`);
914
+ state.indent += 1;
915
+ emitClaimChildren();
916
+ state.indent -= 1;
917
+ push(state, "}");
918
+ } else if (ranges !== null) emitClaimedDirectory(state, name, ranges);
919
+ else emitClaimChildren();
920
+ adopt(name);
921
+ }
922
+ });
923
+ }
924
+ function emitClaimCollectedList(state, listExpr, collect) {
925
+ if (!collect || state.claimAdoptedVar === null) return;
926
+ const child = nextName(state, "child");
927
+ push(state, `for (const ${child} of ${listExpr}) ${state.claimAdoptedVar}.push(${child});`);
928
+ }
929
+ /**
930
+ * One reusable-JSX insertion during claim. The recipe claim adopts its own
931
+ * nodes from the active cursor; this call only opens an independent projection.
932
+ */
933
+ function emitClaimInsertion(state, node, parentExpr, collect) {
934
+ const recipeVar = state.recipeVars.get(node.recipeId);
935
+ if (recipeVar === void 0) {
936
+ diag(state, "OEIR_LEAF_MISSING_RECIPE", `insertion site '${node.recipeId}' has no claim-time recipe`, node.span);
937
+ return;
938
+ }
939
+ state.usesClaimRecipe = true;
940
+ const projection = nextName(state, "projection");
941
+ push(state, `const ${projection} = claimRecipe(${state.scopeVar}, ${recipeVar}, ${parentExpr});`, node.span);
942
+ emitClaimCollectedList(state, `${projection}.nodes`, collect);
943
+ }
944
+ /** One `{props.children}` site. The caller-supplied recipe owns the node shape. */
945
+ function emitClaimChildrenProjection(state, node, parentExpr, collect) {
946
+ const recipeVar = state.childrenRecipeVar;
947
+ if (recipeVar === null) {
948
+ diag(state, "OEIR_LEAF_MISSING_CHILDREN", "children projection has no claim-level `props.children` recipe read", node.span);
949
+ return;
950
+ }
951
+ state.usesClaimRecipe = true;
952
+ const projection = nextName(state, "childrenProjection");
953
+ push(state, `const ${projection} = claimRecipe(${state.scopeVar}, ${recipeVar}, ${parentExpr});`, node.span);
954
+ emitClaimCollectedList(state, `${projection}.nodes`, collect);
955
+ }
956
+ /**
957
+ * Claim one component reference in authored position. Mirrors the mount's
958
+ * child scope and per-read props, but adopts existing nodes and rolls a
959
+ * throwing claim back with `dispose(false)` so borrowed DOM stays.
960
+ */
961
+ function emitClaimComponentRef(state, node, records, parentExpr, collect) {
962
+ const span = node.span;
963
+ const childrenRecipeVar = node.childrenRecipeId === null ? null : state.recipeVars.get(node.childrenRecipeId) ?? null;
964
+ if (node.childrenRecipeId !== null && childrenRecipeVar === null) {
965
+ diag(state, "OEIR_LEAF_MISSING_RECIPE", `children recipe '${node.childrenRecipeId}' of '<${node.name}>' has no claim-time recipe`, span);
966
+ return;
967
+ }
968
+ const admitted = [];
969
+ for (const attribute of node.props) {
970
+ if (attribute.name === "key" || attribute.name === "children") continue;
971
+ admitted.push(attribute);
972
+ }
973
+ const id = state.counter.value++;
974
+ const propsVar = `${INTERNAL_PREFIX}childProps${id}`;
975
+ const retained = state.retention !== null && state.retention.retainedRefs.has(node);
976
+ const hostVar = `${INTERNAL_PREFIX}childHost${id}`;
977
+ const scopeVar = `${INTERNAL_PREFIX}childScope${id}`;
978
+ const nodesVar = `${INTERNAL_PREFIX}childNodes${id}`;
979
+ const setupHostVar = `${INTERNAL_PREFIX}childSetupHost${id}`;
980
+ const instanceVar = `${INTERNAL_PREFIX}childInstance${id}`;
981
+ const failureVar = `${INTERNAL_PREFIX}childFailure${id}`;
982
+ const propDeps = /* @__PURE__ */ new Set();
983
+ let needsParentProps = false;
984
+ const resolved = [];
985
+ for (const prop of admitted) {
986
+ if (prop.kind === "static") {
987
+ resolved.push(prop);
988
+ continue;
989
+ }
990
+ const record = recordFor(state, prop.expression, records);
991
+ if (record === null || !declareReads(state, record)) return;
992
+ const dependencies = dependencyNames(state, record);
993
+ if (dependencies === null) return;
994
+ for (const dependency of dependencies) if (dependency.fromProps) needsParentProps = true;
995
+ else propDeps.add(dependency.name);
996
+ resolved.push({
997
+ kind: "dynamic",
998
+ name: prop.name,
999
+ record,
1000
+ span: prop.span
1001
+ });
1002
+ }
1003
+ if (resolved.length > 0 || childrenRecipeVar !== null) {
1004
+ push(state, `const ${propsVar} = {`, span);
1005
+ state.indent += 1;
1006
+ if (childrenRecipeVar !== null) push(state, `children: ${childrenRecipeVar},`, span);
1007
+ for (const prop of resolved) {
1008
+ if (prop.kind === "static") {
1009
+ const key = IDENTIFIER_PATTERN.test(prop.name) ? prop.name : JSON.stringify(prop.name);
1010
+ push(state, `${key}: ${JSON.stringify(prop.value)},`);
1011
+ continue;
1012
+ }
1013
+ const key = IDENTIFIER_PATTERN.test(prop.name) ? prop.name : JSON.stringify(prop.name);
1014
+ pushParts(state, [
1015
+ `get ${key}() { return (`,
1016
+ { record: prop.record },
1017
+ "); },"
1018
+ ], prop.span);
1019
+ }
1020
+ state.indent -= 1;
1021
+ push(state, "};");
1022
+ }
1023
+ const depParts = [...propDeps];
1024
+ if (needsParentProps) depParts.push(`...${state.hostVar}.propDeps`);
1025
+ const propsExpr = resolved.length > 0 || childrenRecipeVar !== null ? propsVar : "{}";
1026
+ const depList = `[${depParts.join(", ")}]`;
1027
+ if (!retained) {
1028
+ push(state, `const ${hostVar} = { bindings: ${state.hostVar}.bindings, propDeps: ${depList} };`, span);
1029
+ push(state, `const ${scopeVar} = ${state.scopeVar}.child();`, span);
1030
+ push(state, `let ${nodesVar};`);
1031
+ push(state, "try {");
1032
+ state.indent += 1;
1033
+ push(state, `${nodesVar} = ${node.name}${CLAIM_SUFFIX}(${scopeVar}, ${propsExpr}, ${hostVar}, ${parentExpr});`, span);
1034
+ state.indent -= 1;
1035
+ push(state, `} catch (error) { ${scopeVar}.dispose(false); throw error; }`);
1036
+ push(state, `${scopeVar}.addRangeCleanup(() => removeNodes(${nodesVar}));`);
1037
+ emitClaimCollectedList(state, nodesVar, collect);
1038
+ return;
1039
+ }
1040
+ const siteKey = siteKeyLiteral(span);
1041
+ const setupScopeVar = `${INTERNAL_PREFIX}setupScope${id}`;
1042
+ const setupCall = state.retention.setupBodies.has(node.name) ? `(${setupScopeVar}) => ${node.name}${LEAF_SETUP_SUFFIX}(${setupScopeVar}, ${propsExpr}, ${setupHostVar})` : `() => ({})`;
1043
+ push(state, `const ${setupHostVar} = { bindings: ${state.hostVar}.bindings, propDeps: ${depList}${childHostElementField(state, node)}${childPropertyChangeField(state, node)}${childErrorBoundaryField(state, node)}${childContextField(state, node)} };`, span);
1044
+ push(state, `const ${instanceVar} = retainChildInstance(${state.hostVar}.instance, ${siteKey}, ${state.scopeVar}, ${setupCall});`, span);
1045
+ push(state, `const ${scopeVar} = ${state.scopeVar}.child();`, span);
1046
+ push(state, `const ${hostVar} = { bindings: ${setupHostVar}.bindings, propDeps: ${setupHostVar}.propDeps, instance: ${instanceVar}.scope, setup: ${instanceVar}.record${childHostElementField(state, node)}${childErrorReportField(state, node)}${childContextField(state, node)}${retainedTransactionField(state, node.name)} };`, span);
1047
+ push(state, `let ${nodesVar};`);
1048
+ push(state, "try {");
1049
+ state.indent += 1;
1050
+ push(state, `${nodesVar} = ${node.name}${CLAIM_SUFFIX}(${scopeVar}, ${propsExpr}, ${hostVar}, ${parentExpr});`, span);
1051
+ state.indent -= 1;
1052
+ push(state, `} catch (error) {`);
1053
+ state.indent += 1;
1054
+ push(state, `let ${failureVar} = null;`);
1055
+ push(state, `try { ${scopeVar}.dispose(false); } catch (failure) { ${failureVar} = failure; }`);
1056
+ push(state, `try { releaseChildInstance(${state.hostVar}.instance, ${siteKey}); } catch (failure) { ${failureVar} ??= failure; }`);
1057
+ push(state, `throw ${failureVar} ?? error;`);
1058
+ state.indent -= 1;
1059
+ push(state, `}`);
1060
+ push(state, `${scopeVar}.addRangeCleanup(() => removeNodes(${nodesVar}));`);
1061
+ emitClaimCollectedList(state, nodesVar, collect);
1062
+ }
1063
+ /**
1064
+ * Claim-time recipes. The mount-time recipe's definition owner is the mount
1065
+ * scope, which claim disposes before adoption, so lineage would reject it.
1066
+ * These objects exist only so `claimRecipe` can open an independent projection;
1067
+ * calling `mount` on them is a coded mismatch, not a second mount.
1068
+ */
1069
+ function emitClaimTimeRecipes(state, file, records) {
1070
+ const referenced = referencedRecipeIds(state.component);
1071
+ if (referenced.size === 0) return;
1072
+ const ctx = {
1073
+ componentByName: state.componentByName,
1074
+ stack: /* @__PURE__ */ new Set()
1075
+ };
1076
+ for (const recipe of state.component.recipes) {
1077
+ if (state.diagnostics.length > 0) return;
1078
+ if (!referenced.has(recipe.id)) continue;
1079
+ if (!nodeClaimable(recipe.target, state.component, ctx)) {
1080
+ diag(state, "OEIR_LEAF_UNSUPPORTED_NODE", `recipe '${recipe.id}' is outside the M07-1 claim slice`, recipe.span);
1081
+ return;
1082
+ }
1083
+ const outerOrdinals = state.textOrdinals;
1084
+ const preparedTarget = normalizeTextRuns([recipe.target]);
1085
+ state.textOrdinals = textSlotOrdinals(preparedTarget);
1086
+ if (!assertTextBoundaryContext(state, preparedTarget)) {
1087
+ state.textOrdinals = outerOrdinals;
1088
+ return;
1089
+ }
1090
+ const recipeVar = nextName(state, "claimRecipe");
1091
+ state.recipeVars.set(recipe.id, recipeVar);
1092
+ const scopeParam = nextName(state, "recipeScope");
1093
+ const propsParam = nextName(state, "recipeProps");
1094
+ const parentParam = nextName(state, "recipeParent");
1095
+ const adoptedVar = nextName(state, "adopted");
1096
+ push(state, `const ${recipeVar} = createRecipe({`, recipe.span);
1097
+ state.indent += 1;
1098
+ push(state, `definitionOwner: ${MOUNT_SCOPE},`);
1099
+ push(state, `source: ${JSON.stringify(`${file}#${state.component.name}:${recipe.id.replace(/^#/, "")}`)},`);
1100
+ state.usesLeafClaimMismatch = true;
1101
+ push(state, `mount() { throw ${claimError("claim-time recipe has no mount", recipe.span)}; },`);
1102
+ push(state, `claim(${scopeParam}, ${propsParam}, ${parentParam}) {`, recipe.span);
1103
+ state.indent += 1;
1104
+ const outerScope = state.scopeVar;
1105
+ const outerAdopted = state.claimAdoptedVar;
1106
+ const outerActivation = state.claimActivationVar;
1107
+ state.scopeVar = scopeParam;
1108
+ state.claimAdoptedVar = adoptedVar;
1109
+ state.claimActivationVar = CLAIM_ACTIVATION;
1110
+ const phase2 = [];
1111
+ const activationSteps = emitClaimQueueInit(state, parentParam);
1112
+ push(state, `const ${adoptedVar} = [];`);
1113
+ push(state, "try {");
1114
+ state.indent += 1;
1115
+ state.claimTimeRecipeDepth += 1;
1116
+ emitClaimHtmlNamespace(state, parentParam, "/", recipe.span);
1117
+ emitClaimInto(state, [recipe.target], "__oe_claimCursor", "", records, phase2, (name) => {
1118
+ push(state, `${adoptedVar}.push(${name});`);
1119
+ }, (name, condition) => {
1120
+ push(state, `if (${condition}) ${adoptedVar}.push(${name});`);
1121
+ }, parentParam, true);
1122
+ state.usesLeafClaimMismatch = true;
1123
+ push(state, `if (__oe_cursorOwned && __oe_claimCursor.node !== null) throw ${claimError("extra node at /", recipe.span)};`);
1124
+ emitPhase2Steps(state, phase2);
1125
+ emitClaimActivationCapture(state, activationSteps);
1126
+ state.indent -= 1;
1127
+ emitClaimOwnerFinally(state);
1128
+ emitClaimActivationDrain(state, activationSteps);
1129
+ state.claimTimeRecipeDepth -= 1;
1130
+ push(state, `return ${adoptedVar};`);
1131
+ state.scopeVar = outerScope;
1132
+ state.claimAdoptedVar = outerAdopted;
1133
+ state.claimActivationVar = outerActivation;
1134
+ state.indent -= 1;
1135
+ push(state, "},");
1136
+ state.indent -= 1;
1137
+ push(state, "});");
1138
+ state.textOrdinals = outerOrdinals;
1139
+ }
1140
+ }
1141
+ function emitClaimFunction(file, component, records, componentByName, sharedClaimCursor, rootSetup, aliasesSetupRecord, rootComponent, connectReplaySource, connectEnvReplaySource, retention, claimStyleLinkPrefix) {
1142
+ if (!componentClaimable(component, {
1143
+ componentByName,
1144
+ stack: /* @__PURE__ */ new Set()
1145
+ })) return null;
1146
+ const useShared = sharedClaimCursor && !isDirectoryRootComponent(component);
1147
+ const projectsChildren = componentProjectsChildren(component);
1148
+ const propsName = component.propsParam;
1149
+ const state = {
1150
+ component,
1151
+ lines: [],
1152
+ physicalLine: 0,
1153
+ indent: 1,
1154
+ diagnostics: [],
1155
+ requiredBindings: /* @__PURE__ */ new Set(),
1156
+ requiredProps: /* @__PURE__ */ new Set(),
1157
+ hostBindings: /* @__PURE__ */ new Set(),
1158
+ localResources: /* @__PURE__ */ new Set(),
1159
+ counter: { value: 0 },
1160
+ propsName,
1161
+ requiresPropsChanged: false,
1162
+ segments: [],
1163
+ placements: [],
1164
+ segmentKeys: /* @__PURE__ */ new Set(),
1165
+ scopeVar: MOUNT_SCOPE,
1166
+ hostVar: MOUNT_HOST,
1167
+ componentByName,
1168
+ declaredRecipeIds: declaredRecipeIdSet(component),
1169
+ recipeNames: /* @__PURE__ */ new Set(),
1170
+ recipeVars: /* @__PURE__ */ new Map(),
1171
+ entryNames: /* @__PURE__ */ new Set(),
1172
+ refreshStack: [],
1173
+ listDepth: 0,
1174
+ recipeDepth: 0,
1175
+ childrenRecipeVar: projectsChildren ? `${INTERNAL_PREFIX}childrenRecipe` : null,
1176
+ ssrRecipeVars: /* @__PURE__ */ new Map(),
1177
+ ssrChildrenRenderVar: null,
1178
+ directorySource: `${file}#${component.name}`,
1179
+ usesStaticSiblingDirectoryConsumer: false,
1180
+ claimCursorShared: useShared,
1181
+ claimStyleLinkPrefix: claimStyleLinkPrefix && rootComponent,
1182
+ claimAdoptedVar: null,
1183
+ claimActivationVar: null,
1184
+ usesClaimRecipe: false,
1185
+ emitDirectoryMarkers: false,
1186
+ emitTextBoundaries: true,
1187
+ textOrdinals: textSlotOrdinals(component.roots),
1188
+ claimEntry: null,
1189
+ usesLeafClaimMismatch: false,
1190
+ retention,
1191
+ retainBody: retention !== null && retention.rootName === component.name,
1192
+ leafBody: retention?.leafBodies.has(component.name) === true,
1193
+ retainsChildren: retention?.retainingBodies.has(component.name) === true,
1194
+ claimTimeRecipeDepth: 0
1195
+ };
1196
+ if (!assertTextBoundaryContext(state, component.roots)) return {
1197
+ lines: [],
1198
+ diagnostics: state.diagnostics,
1199
+ segments: [],
1200
+ placements: []
1201
+ };
1202
+ const localLines = [];
1203
+ for (const resource of component.resources) {
1204
+ if (!IDENTIFIER_PATTERN.test(resource.name) || resource.name.startsWith("__oe_")) continue;
1205
+ if (resource.kind === "ref") {
1206
+ if (resource.expression === null) {
1207
+ localLines.push({
1208
+ name: resource.name,
1209
+ kind: "ref",
1210
+ record: null,
1211
+ span: resource.span
1212
+ });
1213
+ continue;
1214
+ }
1215
+ const record = recordFor(state, resource.expression, records);
1216
+ if (record === null || !declareReads(state, record)) continue;
1217
+ state.localResources.add(resource.name);
1218
+ localLines.push({
1219
+ name: resource.name,
1220
+ kind: "ref",
1221
+ record,
1222
+ span: resource.span
1223
+ });
1224
+ continue;
1225
+ }
1226
+ if (resource.kind === "host") {
1227
+ state.localResources.add(resource.name);
1228
+ localLines.push({
1229
+ name: resource.name,
1230
+ kind: "host",
1231
+ record: null,
1232
+ span: resource.span
1233
+ });
1234
+ continue;
1235
+ }
1236
+ if (resource.kind === "context") {
1237
+ if (resource.expression === null) continue;
1238
+ const record = recordFor(state, resource.expression, records);
1239
+ if (record === null || !declareReads(state, record)) continue;
1240
+ state.localResources.add(resource.name);
1241
+ localLines.push({
1242
+ name: resource.name,
1243
+ kind: "context",
1244
+ record,
1245
+ span: resource.span
1246
+ });
1247
+ continue;
1248
+ }
1249
+ if (resource.kind === "local") {
1250
+ if (resource.recipeId !== null || resource.expression === null) continue;
1251
+ const record = recordFor(state, resource.expression, records);
1252
+ if (record === null || !declareReads(state, record)) continue;
1253
+ state.localResources.add(resource.name);
1254
+ localLines.push({
1255
+ name: resource.name,
1256
+ kind: "local",
1257
+ record,
1258
+ span: resource.span
1259
+ });
1260
+ continue;
1261
+ }
1262
+ state.hostBindings.add(resource.name);
1263
+ state.requiredBindings.add(resource.name);
1264
+ }
1265
+ const leafSetup = state.leafBody && localLines.length > 0;
1266
+ if (state.retainBody) {
1267
+ const beginCall = `beginInstancePass(${MOUNT_HOST}.instance)`;
1268
+ push(state, state.retention?.transaction === true ? `const ${TRANSACTION_VAR} = ${beginCall};` : `${beginCall};`);
1269
+ }
1270
+ const phase2 = [];
1271
+ state.claimActivationVar = useShared ? CLAIM_ACTIVATION : null;
1272
+ const rootAdoptedVar = useShared ? null : nextName(state, "adopted");
1273
+ if (!useShared) {
1274
+ if (rootSetup && aliasesSetupRecord) emitSetupAlias(state, localLines, ROOT_SETUP_HOST_PROPERTY);
1275
+ else if (leafSetup && (localLines.length > 0 || componentUsesContextIntrinsic(component))) emitSetupAlias(state, localLines, LEAF_SETUP_HOST_PROPERTY);
1276
+ else for (const line of localLines) emitSetupBinding(state, line);
1277
+ emitJoinTransaction(state);
1278
+ push(state, `const ${rootAdoptedVar} = [];`);
1279
+ }
1280
+ const rootDirectory = staticElementDirectory(component.roots);
1281
+ if (!useShared && rootDirectory !== null) for (const interior of emitClaimedDirectory(state, CLAIM_PARENT, rootDirectory)) push(state, `${rootAdoptedVar}.push(${interior});`);
1282
+ else if (!useShared) {
1283
+ emitClaimHtmlNamespace(state, CLAIM_PARENT, "/", component.span);
1284
+ const rootCursor = nextName(state, "cursor");
1285
+ if (state.claimStyleLinkPrefix) {
1286
+ const startVar = nextName(state, "claimStart");
1287
+ push(state, `let ${startVar} = ${CLAIM_PARENT}.firstChild;`);
1288
+ push(state, `while (${startVar} !== null && ${startVar}.nodeType === 1 && ${startVar}.nodeName === "LINK" && ${startVar}.hasAttribute(${JSON.stringify(STATIC_STYLES_MARKER)})) ${startVar} = ${startVar}.nextSibling;`);
1289
+ push(state, `const ${rootCursor} = { node: ${startVar} };`);
1290
+ } else push(state, `const ${rootCursor} = { node: ${CLAIM_PARENT}.firstChild };`);
1291
+ emitClaimInto(state, component.roots, rootCursor, "", records, phase2, (name) => {
1292
+ push(state, `${rootAdoptedVar}.push(${name});`);
1293
+ }, (name, condition) => {
1294
+ push(state, `if (${condition}) ${rootAdoptedVar}.push(${name});`);
1295
+ }, CLAIM_PARENT, true);
1296
+ emitClaimCursorEnd(state, rootCursor, "/", component.span);
1297
+ } else {
1298
+ if (rootSetup && aliasesSetupRecord) emitSetupAlias(state, localLines, ROOT_SETUP_HOST_PROPERTY);
1299
+ else if (leafSetup && (localLines.length > 0 || componentUsesContextIntrinsic(component))) emitSetupAlias(state, localLines, LEAF_SETUP_HOST_PROPERTY);
1300
+ else for (const line of localLines) emitSetupBinding(state, line);
1301
+ emitJoinTransaction(state);
1302
+ if (state.childrenRecipeVar !== null) {
1303
+ push(state, `const ${state.childrenRecipeVar} = ${MOUNT_PROPS}.children;`);
1304
+ push(state, `if (${state.childrenRecipeVar} == null || typeof ${state.childrenRecipeVar} !== "object" || typeof ${state.childrenRecipeVar}.mount !== "function" || ${state.childrenRecipeVar}.definitionOwner == null) throw new Error("OEIR_LEAF_MISSING_CHILDREN: component '<${component.name}>' projects props.children but the mounted instance was given no children recipe");`);
1305
+ }
1306
+ emitClaimHtmlNamespace(state, CLAIM_PARENT, "/", component.span);
1307
+ emitClaimTimeRecipes(state, file, records);
1308
+ const adoptedVar = nextName(state, "adopted");
1309
+ state.claimAdoptedVar = adoptedVar;
1310
+ push(state, `const ${adoptedVar} = [];`);
1311
+ const activationSteps = emitClaimQueueInit(state, CLAIM_PARENT);
1312
+ if (state.claimStyleLinkPrefix) push(state, `while (__oe_claimCursor.node !== null && __oe_claimCursor.node.nodeType === 1 && __oe_claimCursor.node.nodeName === "LINK" && __oe_claimCursor.node.hasAttribute(${JSON.stringify(STATIC_STYLES_MARKER)})) __oe_claimCursor.node = __oe_claimCursor.node.nextSibling;`);
1313
+ push(state, "try {");
1314
+ state.indent += 1;
1315
+ emitClaimInto(state, component.roots, "__oe_claimCursor", "", records, phase2, (name) => {
1316
+ push(state, `${adoptedVar}.push(${name});`);
1317
+ }, (name, condition) => {
1318
+ push(state, `if (${condition}) ${adoptedVar}.push(${name});`);
1319
+ }, CLAIM_PARENT, true);
1320
+ state.usesLeafClaimMismatch = true;
1321
+ push(state, `if (__oe_cursorOwned && __oe_claimCursor.node !== null) throw ${claimError("extra node at /", component.span)};`);
1322
+ emitPhase2Steps(state, phase2);
1323
+ emitClaimActivationCapture(state, activationSteps);
1324
+ state.indent -= 1;
1325
+ emitClaimOwnerFinally(state);
1326
+ emitClaimActivationDrain(state, activationSteps);
1327
+ if (state.retainBody) push(state, `endInstancePass(${MOUNT_HOST}.instance);`);
1328
+ push(state, `return ${adoptedVar};`);
1329
+ }
1330
+ if (state.diagnostics.length > 0) return {
1331
+ lines: [],
1332
+ diagnostics: state.diagnostics,
1333
+ segments: [],
1334
+ placements: []
1335
+ };
1336
+ if (!useShared) {
1337
+ emitPhase2Steps(state, phase2);
1338
+ if (state.retainBody) push(state, `endInstancePass(${MOUNT_HOST}.instance);`);
1339
+ push(state, `return ${rootAdoptedVar};`);
1340
+ }
1341
+ const prologue = [`function ${component.name}${CLAIM_SUFFIX}(${MOUNT_SCOPE}, ${MOUNT_PROPS}, ${MOUNT_HOST}, ${CLAIM_PARENT}) {`];
1342
+ if (propsName !== null && IDENTIFIER_PATTERN.test(propsName) && !propsName.startsWith("__oe_")) prologue.push(` const ${propsName} = ${MOUNT_PROPS};`);
1343
+ if (state.requiredBindings.size > 0) {
1344
+ prologue.push(` const ${INTERNAL_PREFIX}requireBinding = (name) => { const value = ${MOUNT_HOST}.bindings[name]; if (value === undefined) throw new Error("OEIR_LEAF_MISSING_VALUE: " + name); return value; };`);
1345
+ for (const binding of [...state.requiredBindings].sort()) prologue.push(` const ${binding} = ${INTERNAL_PREFIX}requireBinding(${JSON.stringify(binding)});`);
1346
+ }
1347
+ if (connectReplaySource !== null) for (const line of emitLifecycleReplay(connectReplaySource)) prologue.push(line);
1348
+ if (connectEnvReplaySource !== null) for (const line of emitLifecycleEnvReplay(connectEnvReplaySource)) prologue.push(line);
1349
+ const shift = fragmentLineCount(prologue);
1350
+ return {
1351
+ lines: [
1352
+ ...prologue,
1353
+ ...state.lines,
1354
+ "}",
1355
+ ""
1356
+ ],
1357
+ diagnostics: [],
1358
+ usesStaticSiblingDirectoryConsumer: state.usesStaticSiblingDirectoryConsumer,
1359
+ usesClaimRecipe: state.usesClaimRecipe,
1360
+ usesLeafClaimMismatch: state.usesLeafClaimMismatch,
1361
+ segments: state.segments.map((segment) => ({
1362
+ ...segment,
1363
+ generatedLine: segment.generatedLine + shift
1364
+ })),
1365
+ placements: state.placements.map((placement) => ({
1366
+ ...placement,
1367
+ generatedLine: placement.generatedLine + shift
1368
+ }))
1369
+ };
1370
+ }
1371
+ //#endregion
1372
+ export { CLAIM_ACTIVATION, emitClaimFunction };