@openelement/compiler 1.0.0-alpha.15 → 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 (51) hide show
  1. package/package.json +3 -2
  2. package/src/compiler.d.ts +8 -6
  3. package/src/compiler.js +7 -6
  4. package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +5 -30
  5. package/src/internal/compiler/compiled-artifact-class-candidates.js +18 -32
  6. package/src/internal/compiler/compiled-artifact-style-requests.d.ts +9 -7
  7. package/src/internal/compiler/compiled-artifact-style-requests.js +9 -7
  8. package/src/internal/compiler/plugin.d.ts +31 -50
  9. package/src/internal/compiler/plugin.js +41 -108
  10. package/src/internal/compiler/semantic-core/analyze-module.d.ts +1 -45
  11. package/src/internal/compiler/semantic-core/analyze-module.js +10 -405
  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/expression-lowering.js +469 -0
  15. package/src/internal/compiler/semantic-core/expression-registry.js +165 -0
  16. package/src/internal/compiler/semantic-core/function-frontend.js +1229 -0
  17. package/src/internal/compiler/semantic-core/island-policy-statement.js +52 -0
  18. package/src/internal/compiler/semantic-core/jsx-module-id.d.ts +4 -0
  19. package/src/internal/compiler/semantic-core/jsx-module-id.js +7 -0
  20. package/src/internal/compiler/semantic-core/lower-program.d.ts +51 -0
  21. package/src/internal/compiler/semantic-core/lower-program.js +186 -90
  22. package/src/internal/compiler/semantic-core/module-analysis.d.ts +28 -5
  23. package/src/internal/compiler/semantic-core/module-analysis.js +16 -17
  24. package/src/internal/compiler/semantic-core/parse-module.js +16 -16
  25. package/src/internal/compiler/semantic-core/scope-resolution.d.ts +208 -0
  26. package/src/internal/compiler/semantic-core/scope-resolution.js +1121 -0
  27. package/src/internal/compiler/semantic-core/server-component.d.ts +22 -7
  28. package/src/internal/compiler/semantic-core/server-component.js +163 -57
  29. package/src/internal/compiler/semantic-core/type-erasure.js +156 -0
  30. package/src/internal/compiler/semantic-ir/generated-element/compile.d.ts +61 -0
  31. package/src/internal/compiler/semantic-ir/generated-element/compile.js +137 -0
  32. package/src/internal/compiler/semantic-ir/generated-element/contract.d.ts +201 -0
  33. package/src/internal/compiler/semantic-ir/generated-element/contract.js +147 -0
  34. package/src/internal/compiler/semantic-ir/generated-element/emit.js +452 -0
  35. package/src/internal/compiler/semantic-ir/generated-element/site.js +1195 -0
  36. package/src/internal/compiler/semantic-ir/generated-leaf/claim-emission.js +1372 -0
  37. package/src/internal/compiler/semantic-ir/generated-leaf/codegen-literals.js +31 -0
  38. package/src/internal/compiler/semantic-ir/generated-leaf/component-emission.js +647 -0
  39. package/src/internal/compiler/semantic-ir/generated-leaf/emission.js +388 -0
  40. package/src/internal/compiler/semantic-ir/generated-leaf/generate.js +395 -0
  41. package/src/internal/compiler/semantic-ir/generated-leaf/instance-emission.js +865 -0
  42. package/src/internal/compiler/semantic-ir/generated-leaf/mount-emission.js +960 -0
  43. package/src/internal/compiler/semantic-ir/generated-leaf/server-emission.js +1011 -0
  44. package/src/internal/compiler/semantic-ir/generated-leaf/structure.js +714 -0
  45. package/src/internal/compiler/style-requests.d.ts +0 -8
  46. package/src/internal/compiler/style-requests.js +1 -14
  47. package/src/internal/compiler/semantic-core/compile.d.ts +0 -47
  48. package/src/internal/compiler/semantic-core/compile.js +0 -100
  49. package/src/internal/compiler/semantic-core/emit-module.js +0 -317
  50. package/src/internal/compiler/semantic-core/emit-program.js +0 -141
  51. package/src/internal/compiler/semantic-core/style-imports.js +0 -87
@@ -0,0 +1,1229 @@
1
+ import { diagnosticAt } from "./diagnostics/index.js";
2
+ import { isSafeAttributeName as isSafeAttributeName$1 } from "./analyze-module.js";
3
+ import { classifyIntrinsicAttribute } from "./attribute-classification.js";
4
+ import { typescriptParser } from "./parse-module.js";
5
+ import { resolveModule } from "./scope-resolution.js";
6
+ import { createExpressionRegistry } from "./expression-registry.js";
7
+ import ts from "typescript";
8
+ import { forbiddenSinkReason } from "@openelement/protocol/forbidden-sinks";
9
+ import { VOID_TAGS } from "@openelement/protocol/void-tags";
10
+ //#region src/internal/compiler/semantic-core/function-frontend.ts
11
+ /**
12
+ * M03-I-4 — production function-component frontend (Alpha16a, compiler-private).
13
+ *
14
+ * This is the **parallel entry** for the function-component authoring model: it
15
+ * does not wrap, call or modify the Alpha15 class frontend (`compile.ts` →
16
+ * `lower-program.ts` → `emit-program.ts` → `emit-module.ts`), emits **no Part
17
+ * Program v2**, no `__partProgram`, no module ABI v2 and no generated module.
18
+ * The class frontend stays the default production behaviour for Alpha16a and
19
+ * the regression baseline until the Alpha16b retirement; there is no adapter
20
+ * between the two frontends (approved P-5).
21
+ *
22
+ * The pipeline consumes the merged M03 slices:
23
+ * - A1 `resolveModule` — lexical scopes, binding identity/value kinds, reads,
24
+ * captures, dependencies and the module-level diagnostic surface;
25
+ * - A2 `createExpressionRegistry` — Route 3 marked-print lowering, recipe
26
+ * references, node-start anchors and expression source-map segments;
27
+ * - A3 `type-erasure` (inside A2) — TypeScript-only syntax stripping.
28
+ *
29
+ * What this module produces is a compiler-private component model plus the
30
+ * per-compilation `ExpressionRegistry` sidecar; M05/M06 consume the model for
31
+ * codegen, M04 consumes captures/owners. Nothing here is serialized, exported
32
+ * from the package entry, or written to disk.
33
+ *
34
+ * Diagnostics dialect: the frontend speaks the compiler's OEC dialect
35
+ * (`CompilerDiagnostic`: code, message, file, line, character, start, end) so
36
+ * the Alpha15 parity harness can compare it field-for-field with the class
37
+ * frontend. Shared admission/security rules reuse the canonical predicates
38
+ * instead of a second table: `forbiddenSinkReason` from
39
+ * `@openelement/protocol/forbidden-sinks`, `isSafeAttributeName` from
40
+ * `analyze-module.ts`, and `classifyIntrinsicAttribute` from
41
+ * `attribute-classification.ts`.
42
+ *
43
+ * The five A1-A3 provisional `OEIR_*` codes stay compiler-private: this
44
+ * frontend wraps any resolver/lowering refusal in `OEC9043` and keeps the
45
+ * original code in the message for traceability. A4a is the diagnostics half
46
+ * of the M03 exit evidence; source-map/security parity matrices and the M03
47
+ * ledger flip are M03-I-4b.
48
+ */
49
+ /**
50
+ * Function-frontend diagnostics. Codes `OEC9010`/`OEC9011`/`OEC9017` are the
51
+ * EXISTING Alpha15 admission/security codes, reused verbatim by the shared
52
+ * predicates so parity holds for equivalent authored constructs. The `OEC9040`
53
+ * band is new to this slice and documented here; `OEC9043` carries a private
54
+ * `OEIR_*` refusal in its message until A4 promotes the vocabulary.
55
+ */
56
+ const CODES = {
57
+ /** No component found / component shape outside the admitted model. */
58
+ shape: "OEC9040",
59
+ /** A statement outside the admitted component body grammar. */
60
+ statement: "OEC9041",
61
+ /** A declaration or JSX form outside the admitted component grammar. */
62
+ form: "OEC9042",
63
+ /** A read/expression refused by A1/A2/A3 (original code kept in message). */
64
+ expression: "OEC9043",
65
+ /** A security sink the function model refuses on its own. */
66
+ security: "OEC9044"
67
+ };
68
+ /**
69
+ * The module specifiers the compiler-erased intrinsics may be imported from
70
+ * (A16-LANE-M, M10-P1/P4; `16b-REF` adds `ref` to the same table).
71
+ *
72
+ * Both spellings name the SAME functions: `@openelement/element/lifecycle` is a
73
+ * side-effect-free subpath that re-exports the identical fail-closed stand-ins,
74
+ * and exists only so an author module's import survives tree shaking — the root
75
+ * entry is flagged in `sideEffects` (it carries the hydration and Block install
76
+ * edges), so importing an intrinsic the compiler will ERASE from the root
77
+ * dragged the generic executor into the client graph for a binding the emitted
78
+ * module never references.
79
+ *
80
+ * Admission is otherwise IDENTICAL for both spellings: the same import form,
81
+ * the same imported names, the same placement/arity/shape rules. A subpath
82
+ * other than this one stays a foreign module (unchanged fall-through to the
83
+ * pre-existing component-body grammar), and an unrelated name imported from
84
+ * `/lifecycle` is not an intrinsic.
85
+ */
86
+ const LIFECYCLE_INTRINSIC_SPECIFIERS = /* @__PURE__ */ new Set(["@openelement/element", "@openelement/element/lifecycle"]);
87
+ /** True when `specifier` is a canonical lifecycle-intrinsic module. */
88
+ function isLifecycleIntrinsicSpecifier(specifier) {
89
+ return LIFECYCLE_INTRINSIC_SPECIFIERS.has(specifier);
90
+ }
91
+ function spanOf(sourceFile, node) {
92
+ const start = node.getStart(sourceFile);
93
+ const end = node.getEnd();
94
+ const position = sourceFile.getLineAndCharacterOfPosition(start);
95
+ return {
96
+ file: sourceFile.fileName,
97
+ start,
98
+ end,
99
+ line: position.line + 1,
100
+ column: position.character + 1
101
+ };
102
+ }
103
+ function fromRefusal(sourceFile, diagnostic) {
104
+ return {
105
+ code: CODES.expression,
106
+ message: `[${diagnostic.code}] ${diagnostic.message}`,
107
+ file: diagnostic.span.file,
108
+ line: diagnostic.span.line,
109
+ character: diagnostic.span.column,
110
+ start: diagnostic.span.start,
111
+ end: diagnostic.span.end
112
+ };
113
+ }
114
+ /** Unwrap the transparent wrappers the admitted grammar allows around JSX. */
115
+ function unwrap(node) {
116
+ let current = node;
117
+ for (;;) {
118
+ if (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isNonNullExpression(current) || ts.isTypeAssertionExpression(current)) {
119
+ current = current.expression;
120
+ continue;
121
+ }
122
+ return current;
123
+ }
124
+ }
125
+ function isJsxLike(node) {
126
+ return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node) || ts.isConditionalExpression(node) || ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken;
127
+ }
128
+ function isComponentTag(tag) {
129
+ return /^[A-Z]/.test(tag);
130
+ }
131
+ /**
132
+ * A void element has no content model. Whitespace-only JSX text and an empty
133
+ * JSX expression slot are formatting and emit no child; any real child is a
134
+ * source diagnostic rather than a child the mount appends and the SSR producer
135
+ * silently drops.
136
+ */
137
+ function hasMeaningfulVoidChild(child) {
138
+ if (ts.isJsxText(child)) return child.text.trim() !== "";
139
+ if (ts.isJsxExpression(child)) return child.expression !== void 0;
140
+ return true;
141
+ }
142
+ function discoverComponents(sourceFile) {
143
+ const candidates = [];
144
+ for (const statement of sourceFile.statements) {
145
+ if (ts.isFunctionDeclaration(statement) && statement.body !== void 0 && statement.name) {
146
+ candidates.push({
147
+ name: statement.name.text,
148
+ bindingName: statement.name,
149
+ node: statement
150
+ });
151
+ continue;
152
+ }
153
+ if (!ts.isVariableStatement(statement)) continue;
154
+ for (const declaration of statement.declarationList.declarations) {
155
+ if (!ts.isIdentifier(declaration.name)) continue;
156
+ const initializer = declaration.initializer;
157
+ if (initializer !== void 0 && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))) candidates.push({
158
+ name: declaration.name.text,
159
+ bindingName: declaration.name,
160
+ node: initializer
161
+ });
162
+ }
163
+ }
164
+ return candidates;
165
+ }
166
+ /**
167
+ * A function is a component when its body returns JSX-like output. Helpers that
168
+ * never return JSX are module-local functions, not components.
169
+ */
170
+ function isComponentShape(candidate) {
171
+ const body = candidate.node.body;
172
+ if (body === void 0) return false;
173
+ if (!ts.isBlock(body)) return isJsxLike(unwrap(body));
174
+ const returns = body.statements.filter(ts.isReturnStatement);
175
+ return returns.length === 1 && returns[0].expression !== void 0 && isJsxLike(unwrap(returns[0].expression));
176
+ }
177
+ var FunctionFrontendBuilder = class {
178
+ sourceFile;
179
+ resolved;
180
+ registry;
181
+ /** `16b-LC`: the compiler-private lifecycle admission mode for this module. */
182
+ lifecycleAdmission;
183
+ diagnostics = [];
184
+ recipeIds = /* @__PURE__ */ new Map();
185
+ componentBindings = /* @__PURE__ */ new Map();
186
+ /**
187
+ * Component-scope identifier → recipe id for a direct JSX initializer
188
+ * (M06b1a-2): the one place a `{name}` slot is known to be an insertion site
189
+ * rather than a dynamic text read. Reset per component so a name can never
190
+ * leak a recipe across components.
191
+ */
192
+ localRecipeNames = /* @__PURE__ */ new Map();
193
+ /** List-mapper parameters enclosing the slot being built (shadowing guard). */
194
+ entryParameters = [];
195
+ recipeCounter = 0;
196
+ childrenRecipeCounter = 0;
197
+ constructor(sourceFile, resolved, lifecycleAdmission) {
198
+ this.sourceFile = sourceFile;
199
+ this.resolved = resolved;
200
+ this.lifecycleAdmission = lifecycleAdmission;
201
+ this.registry = createExpressionRegistry({
202
+ module: resolved,
203
+ recipeReference: (jsx) => this.recipeReference(jsx)
204
+ });
205
+ }
206
+ fail(node, code, message) {
207
+ this.diagnostics.push(diagnosticAt(this.sourceFile, node, code, message));
208
+ }
209
+ hasErrors() {
210
+ return this.diagnostics.length > 0;
211
+ }
212
+ recipeReference(jsx) {
213
+ const id = this.ensureRecipeId(jsx);
214
+ return id === void 0 ? void 0 : {
215
+ callee: RECIPE_REFERENCE_CALLEE,
216
+ id
217
+ };
218
+ }
219
+ ensureRecipeId(jsx) {
220
+ const existing = this.recipeIds.get(jsx);
221
+ if (existing !== void 0) return existing;
222
+ const target = unwrap(jsx);
223
+ if (!ts.isJsxElement(target) && !ts.isJsxSelfClosingElement(target)) {
224
+ this.fail(jsx, CODES.form, "a JSX value in an expression must be an element or component reference");
225
+ return;
226
+ }
227
+ const id = `#recipe${this.recipeCounter}`;
228
+ this.recipeCounter += 1;
229
+ this.recipeIds.set(jsx, id);
230
+ this.pendingRecipes.push({
231
+ id,
232
+ jsx: target
233
+ });
234
+ return id;
235
+ }
236
+ /** Recipes created while lowering expressions; drained by the component walk. */
237
+ pendingRecipes = [];
238
+ /**
239
+ * `16b-REF` — the current component's declared ref-handle names.
240
+ *
241
+ * A handle's `current` field is written on attach and cleared on detach; it
242
+ * notifies nothing. A TRACKED slot reading it would therefore be a one-shot
243
+ * snapshot (the exact "silently SSR-only surface" defect the generated lane
244
+ * exists to remove), so a handle may only be READ from a `handler`-mode
245
+ * expression — a `ref` attribute or an authored callback body. This set is
246
+ * the source of that refusal; it is rebuilt per component, like
247
+ * `localRecipeNames`.
248
+ */
249
+ refHandleNames = /* @__PURE__ */ new Set();
250
+ /** Register one component-reference children fragment as a recipe (M06b2a). */
251
+ registerChildrenRecipe(fragment) {
252
+ const id = `#children${this.childrenRecipeCounter}`;
253
+ this.childrenRecipeCounter += 1;
254
+ this.pendingRecipes.push({
255
+ id,
256
+ fragment
257
+ });
258
+ return id;
259
+ }
260
+ expression(node, mode) {
261
+ if (this.containsPropsChildrenRead(node)) {
262
+ this.fail(node, CODES.form, "props.children is a recipe projection channel: it may only appear as a direct JSX child slot `{props.children}`, never inside an expression value");
263
+ return null;
264
+ }
265
+ const misplacedRef = this.misplacedRefCall(node);
266
+ if (misplacedRef !== null) {
267
+ this.fail(misplacedRef, CODES.form, "ref(...) is a COMPILED DECLARATION, not a value: write `const handle = ref(cb?)` and pass `<node ref={handle} />`. A ref(...) call in any other position would erase to nothing and throw outside the compiler pipeline");
268
+ return null;
269
+ }
270
+ if (mode !== "handler") {
271
+ const handle = this.refHandleReadIn(node);
272
+ if (handle !== null) {
273
+ this.fail(node, CODES.form, `the ref handle '${handle}' is an attach/detach-only value: 'current' is written when the node attaches and cleared when it detaches, and it notifies nothing. Read it inside a ref attribute \`ref={(el) => …}\` or a callback body (ref(...) notification, onConnect/onDispose/onPropertyChange/onError, event handler), not in a tracked slot`);
274
+ return null;
275
+ }
276
+ }
277
+ const { record, diagnostics } = this.registry.lower(node, mode);
278
+ if (record === null) {
279
+ for (const diagnostic of diagnostics) this.diagnostics.push(fromRefusal(this.sourceFile, diagnostic));
280
+ return null;
281
+ }
282
+ return {
283
+ id: record.id,
284
+ mode,
285
+ span: record.authoredSpan
286
+ };
287
+ }
288
+ /**
289
+ * `16b-REF` — the first `ref(...)` CALL in this expression that is not the
290
+ * initializer of a ref-handle declaration, or `null`.
291
+ *
292
+ * `buildDeclaration` consumes the declaration's own call before any general
293
+ * lowering, so a call reaching {@linkcode expression} is by definition in a
294
+ * value position. Matching is binding provenance (a namespace member or a
295
+ * different module's `ref` is not the intrinsic), and JSX subtrees are
296
+ * skipped: their attribute positions are lowered by the node walk, whose own
297
+ * `ref` attribute handling is the SUPPORTED way to hand a handle to a node.
298
+ */
299
+ misplacedRefCall(node) {
300
+ let found = null;
301
+ const visit = (current) => {
302
+ if (found !== null) return;
303
+ if (ts.isJsxElement(current) || ts.isJsxSelfClosingElement(current) || ts.isJsxFragment(current)) return;
304
+ if (ts.isCallExpression(current) && this.refIntrinsicImport(current) !== null) {
305
+ found = current;
306
+ return;
307
+ }
308
+ ts.forEachChild(current, visit);
309
+ };
310
+ visit(node);
311
+ return found;
312
+ }
313
+ /**
314
+ * `16b-REF` — the first ref-handle name this expression reads, or `null`.
315
+ *
316
+ * Reads are matched by RESOLVED BINDING, not by spelling: a handle name is in
317
+ * {@linkcode refHandleNames} only for this component, and a local shadow in a
318
+ * nested scope resolves to a different binding. JSX subtrees are skipped for
319
+ * the same reason as {@linkcode containsPropsChildrenRead}: they become
320
+ * recipes, and their own attribute positions are classified separately.
321
+ */
322
+ refHandleReadIn(node) {
323
+ if (this.refHandleNames.size === 0) return null;
324
+ let found = null;
325
+ const visit = (current) => {
326
+ if (found !== null) return;
327
+ if (ts.isJsxElement(current) || ts.isJsxSelfClosingElement(current) || ts.isJsxFragment(current)) return;
328
+ if (ts.isIdentifier(current) && this.refHandleNames.has(current.text)) {
329
+ const binding = this.resolved.resolveIdentifier(current);
330
+ if (binding !== void 0 && binding.origin.form === "local") {
331
+ found = current.text;
332
+ return;
333
+ }
334
+ }
335
+ ts.forEachChild(current, visit);
336
+ };
337
+ visit(node);
338
+ return found;
339
+ }
340
+ /**
341
+ * Does this expression read `props.children` outside any replaced JSX subtree?
342
+ * JSX nodes are skipped because the expression lowering replaces them with a
343
+ * recipe reference; their child slots belong to the later node walk.
344
+ */
345
+ containsPropsChildrenRead(node) {
346
+ const propsParam = this.currentPropsParam;
347
+ if (propsParam === null) return false;
348
+ let found = false;
349
+ const visit = (current) => {
350
+ if (found) return;
351
+ if (ts.isJsxElement(current) || ts.isJsxSelfClosingElement(current) || ts.isJsxFragment(current)) return;
352
+ if (ts.isPropertyAccessExpression(current) && ts.isIdentifier(current.expression) && current.expression.text === propsParam && current.name.text === "children") {
353
+ found = true;
354
+ return;
355
+ }
356
+ ts.forEachChild(current, visit);
357
+ };
358
+ visit(node);
359
+ return found;
360
+ }
361
+ buildComponent(candidate) {
362
+ this.localRecipeNames = /* @__PURE__ */ new Map();
363
+ this.refHandleNames = /* @__PURE__ */ new Set();
364
+ const node = candidate.node;
365
+ const parameters = node.parameters;
366
+ if (parameters.length > 1) {
367
+ this.fail(node, CODES.shape, "a function component takes at most one props parameter");
368
+ return null;
369
+ }
370
+ let propsParam = null;
371
+ const parameter = parameters[0];
372
+ if (parameter !== void 0) {
373
+ if (ts.isIdentifier(parameter.name)) propsParam = parameter.name.text;
374
+ else if (!ts.isObjectBindingPattern(parameter.name)) {
375
+ this.fail(parameter, CODES.shape, "the props parameter must be an identifier or an object pattern");
376
+ return null;
377
+ }
378
+ }
379
+ const resources = [];
380
+ const lifecycle = [];
381
+ const contextProviders = [];
382
+ const body = node.body;
383
+ if (body === void 0) {
384
+ this.fail(node, CODES.shape, "a function component must have a body");
385
+ return null;
386
+ }
387
+ let returnExpression = null;
388
+ if (ts.isBlock(body)) for (const statement of body.statements) {
389
+ if (ts.isExpressionStatement(statement)) {
390
+ const lifecycleHook = this.buildLifecycleHook(statement, candidate.name);
391
+ if (lifecycleHook === "refused") continue;
392
+ if (lifecycleHook !== null) {
393
+ lifecycle.push(lifecycleHook);
394
+ continue;
395
+ }
396
+ const contextProvider = this.buildContextProvider(statement, candidate.name);
397
+ if (contextProvider === "refused") continue;
398
+ if (contextProvider !== null) {
399
+ contextProviders.push(contextProvider);
400
+ continue;
401
+ }
402
+ }
403
+ if (ts.isVariableStatement(statement)) {
404
+ for (const declaration of statement.declarationList.declarations) {
405
+ const resource = this.buildDeclaration(declaration);
406
+ if (resource !== null) resources.push(resource);
407
+ }
408
+ continue;
409
+ }
410
+ if (ts.isReturnStatement(statement)) {
411
+ if (returnExpression !== null) {
412
+ this.fail(statement, CODES.statement, "a component has exactly one return");
413
+ return null;
414
+ }
415
+ if (statement.expression === void 0) {
416
+ this.fail(statement, CODES.statement, "the return must produce JSX");
417
+ return null;
418
+ }
419
+ returnExpression = statement.expression;
420
+ continue;
421
+ }
422
+ this.fail(statement, CODES.statement, `statement '${ts.SyntaxKind[statement.kind]}' is outside the admitted component grammar`);
423
+ }
424
+ else returnExpression = body;
425
+ if (returnExpression === null) {
426
+ this.fail(node, CODES.shape, "a component needs one JSX return");
427
+ return null;
428
+ }
429
+ const roots = this.buildBranch(returnExpression);
430
+ const recipes = [];
431
+ while (this.pendingRecipes.length > 0) {
432
+ const entry = this.pendingRecipes.shift();
433
+ if ("fragment" in entry) {
434
+ recipes.push({
435
+ id: entry.id,
436
+ target: entry.fragment,
437
+ span: entry.fragment.span
438
+ });
439
+ continue;
440
+ }
441
+ const target = this.buildNode(entry.jsx);
442
+ if (target === null || target.kind !== "element" && target.kind !== "component-ref") {
443
+ this.fail(entry.jsx, CODES.form, "a recipe target must be an element or a component reference");
444
+ continue;
445
+ }
446
+ recipes.push({
447
+ id: entry.id,
448
+ target,
449
+ span: spanOf(this.sourceFile, entry.jsx)
450
+ });
451
+ }
452
+ if (this.hasErrors()) return null;
453
+ return {
454
+ name: candidate.name,
455
+ propsParam,
456
+ resources,
457
+ recipes,
458
+ roots,
459
+ lifecycle,
460
+ contextProviders,
461
+ span: spanOf(this.sourceFile, node)
462
+ };
463
+ }
464
+ /**
465
+ * `16b-LC` option 1a — admit one direct top-level lifecycle intrinsic
466
+ * statement of the generated element ROOT setup.
467
+ *
468
+ * Recognition is binding provenance, exactly like the `element`/`property`
469
+ * decorator intrinsics: the callee must be a value-position identifier whose
470
+ * resolved binding is a named import of '@openelement/element' or
471
+ * '@openelement/element/lifecycle' (aliases followed) whose imported name is
472
+ * `onConnect`/`onDispose`/`onPropertyChange`. The two specifiers name the
473
+ * same intrinsics — the subpath is the tree-shakeable spelling and admits
474
+ * under exactly the same rules. A local shadow, a namespace member, a third
475
+ * subpath or a foreign module's same-named function is NOT an intrinsic and
476
+ * falls through to the pre-existing component-body grammar (its
477
+ * `ExpressionStatement` refusal is the unchanged diagnostic).
478
+ *
479
+ * The callback is lowered as an ordinary authored expression in `handler`
480
+ * mode (no tracked dependencies; type-erased). Its reads are classified by
481
+ * the generator exactly like any other expression: setup locals become
482
+ * closure captures, `props` is the live frozen props record, builtin globals
483
+ * stay direct, and anything else keeps the leaf's existing fail-closed
484
+ * binding gate. The generator emits the lowered text inside the
485
+ * compiler-owned `__oe_rootInstance` factory; this call node itself never
486
+ * reaches generated code.
487
+ *
488
+ * Slice boundary (no new diagnostic codes): placement/root/arity/shape
489
+ * problems inside the admitted root use the existing function-frontend
490
+ * `OEC9042` form code; a hook in any other component keeps the existing
491
+ * `OEC9041` statement refusal because this method returns null there. The
492
+ * callback admits exactly zero parameters (the pre-existing zero-argument
493
+ * form) or ONE `env` parameter — an identifier or an object binding pattern,
494
+ * no rest/optional/default form. The parameter is typed by the public
495
+ * `onConnect`/`onDispose` signature and erased from the emitted module; the
496
+ * generator passes the env argument only for the one-parameter form, so a
497
+ * zero-argument callback keeps its exact bytes.
498
+ */
499
+ /**
500
+ * The compiler-private admission check. Placement (root vs depth-1 retained
501
+ * hostless child vs everywhere else) is NOT decided here: the generator owns
502
+ * that verdict and fails closed with the authored span, because only the
503
+ * emitted reference graph can tell whether a component is a retained body.
504
+ */
505
+ admitsLifecycle(componentName) {
506
+ const admission = this.lifecycleAdmission;
507
+ if (admission === void 0) return false;
508
+ return admission.admission === "module" || admission.root === componentName;
509
+ }
510
+ buildLifecycleHook(statement, componentName) {
511
+ if (!this.admitsLifecycle(componentName)) return null;
512
+ const expression = statement.expression;
513
+ if (!ts.isCallExpression(expression)) return null;
514
+ const callee = unwrap(expression.expression);
515
+ if (!ts.isIdentifier(callee)) return null;
516
+ const binding = this.resolved.resolveIdentifier(callee);
517
+ if (binding === void 0 || binding.origin.form !== "import") return null;
518
+ if (!isLifecycleIntrinsicSpecifier(binding.origin.specifier)) return null;
519
+ const importedName = binding.origin.importedName;
520
+ if (importedName !== "onConnect" && importedName !== "onDispose" && importedName !== "onPropertyChange" && importedName !== "onError") return null;
521
+ const writtenName = importedName;
522
+ if (expression.typeArguments !== void 0 || expression.arguments.length !== 1) {
523
+ this.fail(statement, CODES.form, `${writtenName}(...) takes exactly one inline function-expression callback`);
524
+ return "refused";
525
+ }
526
+ const callback = unwrap(expression.arguments[0]);
527
+ if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) {
528
+ this.fail(statement, CODES.form, `${writtenName}(...) needs an inline arrow/function-expression callback; an indirect function reference is outside the admitted lifecycle slice`);
529
+ return "refused";
530
+ }
531
+ if (callback.asteriskToken !== void 0) {
532
+ this.fail(statement, CODES.form, `${writtenName}(...) cannot take a generator callback`);
533
+ return "refused";
534
+ }
535
+ if ((ts.canHaveModifiers(callback) ? ts.getModifiers(callback) : void 0)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) === true) {
536
+ this.fail(statement, CODES.form, `the ${writtenName} callback must be synchronous; async callbacks (and async cleanups) are outside the lifecycle slice`);
537
+ return "refused";
538
+ }
539
+ if (callback.parameters.length > 1) {
540
+ this.fail(statement, CODES.form, `the ${writtenName} callback takes at most one 'env' parameter (drop the extra one)`);
541
+ return "refused";
542
+ }
543
+ const parameter = callback.parameters[0];
544
+ if (parameter !== void 0) {
545
+ if (parameter.dotDotDotToken !== void 0 || parameter.questionToken !== void 0 || parameter.initializer !== void 0) {
546
+ this.fail(statement, CODES.form, `the ${writtenName} 'env' parameter is a plain identifier or object binding pattern; rest, optional and default forms are outside the lifecycle slice`);
547
+ return "refused";
548
+ }
549
+ if (!ts.isIdentifier(parameter.name) && !ts.isObjectBindingPattern(parameter.name)) {
550
+ this.fail(statement, CODES.form, `the ${writtenName} 'env' parameter must be an identifier or an object binding pattern`);
551
+ return "refused";
552
+ }
553
+ }
554
+ const lowered = this.expression(callback, "handler");
555
+ if (lowered === null) return "refused";
556
+ return {
557
+ kind: importedName === "onConnect" ? "connect" : importedName === "onDispose" ? "dispose" : importedName === "onError" ? "error" : "property-change",
558
+ callback: lowered,
559
+ receivesEnv: parameter !== void 0,
560
+ span: spanOf(this.sourceFile, statement)
561
+ };
562
+ }
563
+ /**
564
+ * `16b-CTX` — the imported name when `call` invokes a canonical context
565
+ * intrinsic (a named import of `@openelement/element` or
566
+ * `@openelement/element/lifecycle`), or `null` for anything else.
567
+ *
568
+ * Recognition is BINDING PROVENANCE only: a local shadow, a namespace member
569
+ * and a foreign module's same-named function are NOT the intrinsic and keep
570
+ * every pre-existing refusal.
571
+ */
572
+ contextIntrinsicImport(call) {
573
+ const callee = unwrap(call.expression);
574
+ if (!ts.isIdentifier(callee)) return null;
575
+ const binding = this.resolved.resolveIdentifier(callee);
576
+ if (binding === void 0 || binding.origin.form !== "import") return null;
577
+ if (!isLifecycleIntrinsicSpecifier(binding.origin.specifier)) return null;
578
+ const importedName = binding.origin.importedName;
579
+ if (importedName === "provideContext") return "provideContext";
580
+ if (importedName === "useContext") return "useContext";
581
+ return null;
582
+ }
583
+ /**
584
+ * `16b-CTX` — admit one direct top-level `provideContext(token, () => value)`
585
+ * statement of a generated component setup.
586
+ *
587
+ * The call shape is deliberately as narrow as the other intrinsics: exactly two
588
+ * arguments, no type arguments, the token lowered in `setup` mode (it is read
589
+ * once, and in practice is a static module import), and the value as an INLINE
590
+ * synchronous arrow/function expression taking no parameters — the THUNK whose
591
+ * re-read is the lane's provider-change event. Refusals use the existing
592
+ * `OEC9042` form code; no new diagnostic identity is introduced.
593
+ *
594
+ * Placement is the generator's verdict, like the lifecycle intrinsics: the
595
+ * frontend admits module-wide and the emitter decides whether the component is
596
+ * a retained setup body. Returns `null` when the statement is not this
597
+ * intrinsic at all, so the pre-existing component-body grammar keeps its
598
+ * refusal for a non-intrinsic statement.
599
+ */
600
+ buildContextProvider(statement, componentName) {
601
+ if (!this.admitsLifecycle(componentName)) return null;
602
+ const expression = statement.expression;
603
+ if (!ts.isCallExpression(expression)) return null;
604
+ if (this.contextIntrinsicImport(expression) !== "provideContext") return null;
605
+ const writtenName = "provideContext";
606
+ if (expression.typeArguments !== void 0 || expression.arguments.length !== 2) {
607
+ this.fail(statement, CODES.form, `${writtenName}(token, () => value) takes exactly a context token and one inline value thunk`);
608
+ return "refused";
609
+ }
610
+ const token = this.expression(unwrap(expression.arguments[0]), "setup");
611
+ if (token === null) return "refused";
612
+ const thunk = unwrap(expression.arguments[1]);
613
+ if (!ts.isArrowFunction(thunk) && !ts.isFunctionExpression(thunk)) {
614
+ this.fail(statement, CODES.form, `${writtenName}(...) needs an INLINE arrow/function-expression value thunk; a plain value or an indirect function reference is outside the admitted context slice`);
615
+ return "refused";
616
+ }
617
+ if (thunk.asteriskToken !== void 0) {
618
+ this.fail(statement, CODES.form, `${writtenName}(...) cannot take a generator value thunk`);
619
+ return "refused";
620
+ }
621
+ if ((ts.canHaveModifiers(thunk) ? ts.getModifiers(thunk) : void 0)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) === true) {
622
+ this.fail(statement, CODES.form, `the ${writtenName} value thunk must be synchronous; an async provider value is outside the context slice`);
623
+ return "refused";
624
+ }
625
+ if (thunk.parameters.length !== 0) {
626
+ this.fail(statement, CODES.form, `the ${writtenName} value thunk takes no parameters (it is re-read, not called with a value)`);
627
+ return "refused";
628
+ }
629
+ const value = this.expression(thunk, "handler");
630
+ if (value === null) return "refused";
631
+ return {
632
+ token,
633
+ value,
634
+ span: spanOf(this.sourceFile, statement)
635
+ };
636
+ }
637
+ /**
638
+ * `16b-CTX` — the imported name when `call` invokes a canonical `useContext`
639
+ * intrinsic, or `null`.
640
+ */
641
+ useContextIntrinsicImport(call) {
642
+ return this.contextIntrinsicImport(call) === "useContext" ? "useContext" : null;
643
+ }
644
+ /**
645
+ * `16b-CTX` — admit one `const value = useContext(token)` declaration as a
646
+ * component-scope CONSUMER.
647
+ *
648
+ * The call takes exactly one argument (the token, lowered in `setup` mode) and
649
+ * no type arguments. The declared name is bound to the compiler-owned
650
+ * consumer-local Signal, so — unlike a `ref` handle — reading `.value` in a
651
+ * tracked slot is the SUPPORTED use and needs no read-position gate.
652
+ *
653
+ * The declaration must be `const`: the retained setup record aliases it and
654
+ * the signal identity is the contract (a reconnect writes into the SAME
655
+ * object), so a reassignable binding would imply something the emitted code
656
+ * cannot honour. Refusals keep `OEC9042`.
657
+ */
658
+ buildContextConsumer(declaration, name, call) {
659
+ if (call.typeArguments !== void 0 || call.arguments.length !== 1 || this.useContextIntrinsicImport(call) === null) {
660
+ this.fail(call, CODES.form, "useContext(token) takes exactly one context token and no type arguments");
661
+ return null;
662
+ }
663
+ const list = declaration.parent;
664
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0) {
665
+ this.fail(call, CODES.form, "a useContext consumer must be declared with const: the consumer signal identity is the contract and the emitted alias is not reassignable");
666
+ return null;
667
+ }
668
+ const expression = this.expression(unwrap(call.arguments[0]), "setup");
669
+ if (expression === null) return null;
670
+ return {
671
+ name,
672
+ kind: "context",
673
+ expression,
674
+ recipeId: null,
675
+ span: spanOf(this.sourceFile, declaration)
676
+ };
677
+ }
678
+ buildDeclaration(declaration) {
679
+ if (!ts.isIdentifier(declaration.name)) {
680
+ this.fail(declaration, CODES.form, "only plain identifier declarations are admitted");
681
+ return null;
682
+ }
683
+ const name = declaration.name.text;
684
+ const initializer = declaration.initializer;
685
+ if (initializer === void 0) {
686
+ this.fail(declaration, CODES.form, "a declaration needs an initializer");
687
+ return null;
688
+ }
689
+ const value = unwrap(initializer);
690
+ if (ts.isJsxElement(value) || ts.isJsxSelfClosingElement(value)) {
691
+ const recipeId = this.ensureRecipeId(value);
692
+ if (recipeId === void 0) return null;
693
+ this.localRecipeNames.set(name, recipeId);
694
+ return {
695
+ name,
696
+ kind: "local",
697
+ expression: null,
698
+ recipeId,
699
+ span: spanOf(this.sourceFile, declaration)
700
+ };
701
+ }
702
+ if (ts.isCallExpression(value) && this.useContextIntrinsicImport(value) !== null) return this.buildContextConsumer(declaration, name, value);
703
+ const kind = this.resolved.resolveIdentifier(declaration.name)?.value;
704
+ if (ts.isCallExpression(value) && (kind === "signal" || kind === "computed")) {
705
+ const argument = value.arguments[0] ?? value;
706
+ return {
707
+ name,
708
+ kind,
709
+ expression: this.expression(argument, kind === "computed" ? "derived" : "setup"),
710
+ recipeId: null,
711
+ span: spanOf(this.sourceFile, declaration)
712
+ };
713
+ }
714
+ if (ts.isCallExpression(value) && this.refIntrinsicImport(value) !== null) return this.buildRefHandle(declaration, name, value);
715
+ if (ts.isCallExpression(value) && this.useHostIntrinsicImport(value) !== null) return this.buildHostAccess(declaration, name, value);
716
+ return {
717
+ name,
718
+ kind: "local",
719
+ expression: this.expression(value, "setup"),
720
+ recipeId: null,
721
+ span: spanOf(this.sourceFile, declaration)
722
+ };
723
+ }
724
+ /**
725
+ * `16b-REF` — the imported name when `call` invokes a canonical `useHost`
726
+ * intrinsic, or `null`.
727
+ *
728
+ * Same binding-provenance rule as `ref`: an identifier whose resolved binding
729
+ * is a named import of one of {@linkcode LIFECYCLE_INTRINSIC_SPECIFIERS} with
730
+ * the imported name `useHost`. A local shadow or a foreign same-named
731
+ * function is not the intrinsic.
732
+ */
733
+ useHostIntrinsicImport(call) {
734
+ const callee = unwrap(call.expression);
735
+ if (!ts.isIdentifier(callee)) return null;
736
+ const binding = this.resolved.resolveIdentifier(callee);
737
+ if (binding === void 0 || binding.origin.form !== "import") return null;
738
+ if (!isLifecycleIntrinsicSpecifier(binding.origin.specifier)) return null;
739
+ return binding.origin.importedName === "useHost" ? "useHost" : null;
740
+ }
741
+ /**
742
+ * `16b-REF` — admit one `const host = useHost()` declaration as this
743
+ * component's OWNING ELEMENT.
744
+ *
745
+ * The call takes no arguments and no type arguments (the element type is not
746
+ * author-chosen: a root's host is the generated element, a depth-1 retained
747
+ * hostless child's is the nearest enclosing generated element). The
748
+ * declaration must be `const` — the element identity never changes for an
749
+ * instance, so a reassignable binding would imply something the lowered read
750
+ * cannot honour.
751
+ *
752
+ * `expression` stays null: there is nothing to lower. The generator emits the
753
+ * host-record field read, which is the same value the lifecycle/change/error
754
+ * callbacks already receive as `env.host`.
755
+ */
756
+ buildHostAccess(declaration, name, call) {
757
+ if (call.typeArguments !== void 0 || call.arguments.length !== 0) {
758
+ this.fail(call, CODES.form, "useHost() takes no arguments and no type arguments");
759
+ return null;
760
+ }
761
+ const list = declaration.parent;
762
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0) {
763
+ this.fail(call, CODES.form, "a useHost() accessor must be declared with const: the element identity is the contract and the emitted alias is not reassignable");
764
+ return null;
765
+ }
766
+ return {
767
+ name,
768
+ kind: "host",
769
+ expression: null,
770
+ recipeId: null,
771
+ span: spanOf(this.sourceFile, declaration)
772
+ };
773
+ }
774
+ /**
775
+ * `16b-REF` — the imported name when `call` invokes a canonical `ref`
776
+ * intrinsic, or `null` when it invokes anything else.
777
+ *
778
+ * Recognized by BINDING PROVENANCE only: the callee must be a value-position
779
+ * identifier whose resolved binding is a named import of one of the
780
+ * {@linkcode LIFECYCLE_INTRINSIC_SPECIFIERS} whose imported name is `ref`.
781
+ * A local shadow, a namespace member, a third subpath or a foreign module's
782
+ * same-named factory is NOT the intrinsic and keeps every existing refusal.
783
+ */
784
+ refIntrinsicImport(call) {
785
+ const callee = unwrap(call.expression);
786
+ if (!ts.isIdentifier(callee)) return null;
787
+ const binding = this.resolved.resolveIdentifier(callee);
788
+ if (binding === void 0 || binding.origin.form !== "import") return null;
789
+ if (!isLifecycleIntrinsicSpecifier(binding.origin.specifier)) return null;
790
+ return binding.origin.importedName === "ref" ? "ref" : null;
791
+ }
792
+ /**
793
+ * `16b-REF` — admit one `const handle = ref<T>(callback?)` declaration as a
794
+ * component-scope NODE HANDLE.
795
+ *
796
+ * The call shape is deliberately as narrow as the other intrinsics: no type
797
+ * arguments beyond the erased handle element type, at most one argument, and
798
+ * that argument (when present) is an INLINE synchronous arrow or function
799
+ * expression — the same attach/detach notification the plain `ref` channel
800
+ * admits, so the compiler has exactly one ref contract. A non-inline
801
+ * callback, a second argument, a generator, an `async` form or a rest/
802
+ * optional/default parameter fails closed with the existing `OEC9042` form
803
+ * code; no new diagnostic identity is introduced.
804
+ */
805
+ buildRefHandle(declaration, name, call) {
806
+ const list = declaration.parent;
807
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0) {
808
+ this.fail(call, CODES.form, "a ref handle must be declared with const: the handle identity is the contract and the emitted alias is not reassignable");
809
+ return null;
810
+ }
811
+ if (call.arguments.length > 1) {
812
+ this.fail(call, CODES.form, "ref(...) takes at most one inline callback (the attach/detach notification)");
813
+ return null;
814
+ }
815
+ const span = spanOf(this.sourceFile, declaration);
816
+ const argument = call.arguments[0];
817
+ if (argument === void 0) {
818
+ this.refHandleNames.add(name);
819
+ return {
820
+ name,
821
+ kind: "ref",
822
+ expression: null,
823
+ recipeId: null,
824
+ span
825
+ };
826
+ }
827
+ const callback = unwrap(argument);
828
+ if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) {
829
+ this.fail(call, CODES.form, "ref(...) needs an INLINE arrow/function-expression callback; an indirect function reference is outside the admitted ref slice");
830
+ return null;
831
+ }
832
+ if (callback.asteriskToken !== void 0) {
833
+ this.fail(call, CODES.form, "a ref callback cannot be a generator");
834
+ return null;
835
+ }
836
+ if ((ts.canHaveModifiers(callback) ? ts.getModifiers(callback) : void 0)?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) === true) {
837
+ this.fail(call, CODES.form, "the ref callback must be synchronous; an async callback (and an async cleanup) is outside the ref slice");
838
+ return null;
839
+ }
840
+ if (callback.parameters.length > 1) {
841
+ this.fail(call, CODES.form, "a ref callback takes at most one 'element' parameter");
842
+ return null;
843
+ }
844
+ const parameter = callback.parameters[0];
845
+ if (parameter !== void 0 && (parameter.dotDotDotToken !== void 0 || parameter.questionToken !== void 0 || parameter.initializer !== void 0 || !ts.isIdentifier(parameter.name))) {
846
+ this.fail(call, CODES.form, "a ref callback parameter is a plain identifier; rest, optional, default and destructuring forms are outside the ref slice");
847
+ return null;
848
+ }
849
+ const lowered = this.expression(callback, "handler");
850
+ if (lowered === null) return null;
851
+ this.refHandleNames.add(name);
852
+ return {
853
+ name,
854
+ kind: "ref",
855
+ expression: lowered,
856
+ recipeId: null,
857
+ span
858
+ };
859
+ }
860
+ buildBranch(node) {
861
+ const value = unwrap(node);
862
+ if (value.kind === ts.SyntaxKind.NullKeyword || value.kind === ts.SyntaxKind.FalseKeyword || ts.isIdentifier(value) && value.text === "undefined") return [];
863
+ const built = this.buildNode(value);
864
+ if (built === null) {
865
+ this.fail(value, CODES.form, "a conditional branch must be JSX or null");
866
+ return [];
867
+ }
868
+ return [built];
869
+ }
870
+ buildNode(node) {
871
+ const value = unwrap(node);
872
+ if (ts.isJsxElement(value) || ts.isJsxSelfClosingElement(value)) {
873
+ const opening = ts.isJsxElement(value) ? value.openingElement : value;
874
+ if (ts.isPropertyAccessExpression(opening.tagName)) {
875
+ this.fail(opening.tagName, CODES.form, "a JSX component tag must be a plain identifier");
876
+ return null;
877
+ }
878
+ const tag = opening.tagName.getText(this.sourceFile);
879
+ return isComponentTag(tag) ? this.buildComponentRef(value, opening, tag) : this.buildElement(value, opening, tag);
880
+ }
881
+ if (ts.isJsxFragment(value)) return {
882
+ kind: "fragment",
883
+ children: this.buildChildren(value.children),
884
+ span: spanOf(this.sourceFile, value)
885
+ };
886
+ return null;
887
+ }
888
+ buildChildren(children) {
889
+ const nodes = [];
890
+ for (const child of children) {
891
+ if (ts.isJsxText(child)) {
892
+ const text = child.text.replace(/\s+/g, " ");
893
+ if (text.trim() === "") continue;
894
+ nodes.push({
895
+ kind: "text",
896
+ value: text,
897
+ span: spanOf(this.sourceFile, child)
898
+ });
899
+ continue;
900
+ }
901
+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child)) {
902
+ const nested = this.buildNode(child);
903
+ if (nested !== null) nodes.push(nested);
904
+ continue;
905
+ }
906
+ if (!ts.isJsxExpression(child) || child.expression === void 0) continue;
907
+ const built = this.buildSlot(child.expression);
908
+ if (built !== null) nodes.push(built);
909
+ }
910
+ return nodes;
911
+ }
912
+ /** One `{...}` child slot: projection, insertion, condition, list or text. */
913
+ buildSlot(expression) {
914
+ const value = unwrap(expression);
915
+ const propsParam = this.currentPropsParam;
916
+ if (propsParam !== null && ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression) && value.expression.text === propsParam && value.name.text === "children") return {
917
+ kind: "children-projection",
918
+ span: spanOf(this.sourceFile, value)
919
+ };
920
+ if (ts.isIdentifier(value)) {
921
+ const recipeId = this.entryParameters.includes(value.text) ? void 0 : this.localRecipeNames.get(value.text);
922
+ if (recipeId !== void 0) return {
923
+ kind: "insertion-site",
924
+ recipeId,
925
+ span: spanOf(this.sourceFile, value)
926
+ };
927
+ }
928
+ const list = this.tryBuildList(value);
929
+ if (list !== null) return list;
930
+ if (ts.isConditionalExpression(value) || isAndExpression(value)) {
931
+ const conditional = value;
932
+ const test = ts.isConditionalExpression(conditional) ? conditional.condition : conditional.left;
933
+ const consequent = ts.isConditionalExpression(conditional) ? conditional.whenTrue : conditional.right;
934
+ const alternate = ts.isConditionalExpression(conditional) ? conditional.whenFalse : void 0;
935
+ const testRef = this.expression(test, "inline");
936
+ if (testRef === null) return null;
937
+ return {
938
+ kind: "condition",
939
+ test: testRef,
940
+ consequent: this.buildBranch(consequent),
941
+ alternate: alternate === void 0 ? null : this.buildBranch(alternate),
942
+ span: spanOf(this.sourceFile, conditional)
943
+ };
944
+ }
945
+ const dynamic = this.expression(value, this.currentEntryMode());
946
+ if (dynamic === null) return null;
947
+ return {
948
+ kind: "dynamic-text",
949
+ expression: dynamic,
950
+ span: spanOf(this.sourceFile, value)
951
+ };
952
+ }
953
+ tryBuildList(value) {
954
+ if (!ts.isCallExpression(value)) return null;
955
+ if (!ts.isPropertyAccessExpression(value.expression)) return null;
956
+ if (value.expression.name.text !== "map") return null;
957
+ const callback = value.arguments[0];
958
+ if (callback === void 0 || !ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) {
959
+ this.fail(value, CODES.form, "a list mapper must be a single inline function");
960
+ return null;
961
+ }
962
+ const parameter = callback.parameters[0];
963
+ if (parameter === void 0 || !ts.isIdentifier(parameter.name)) {
964
+ this.fail(value, CODES.form, "a list mapper must take one plain identifier parameter");
965
+ return null;
966
+ }
967
+ const items = this.expression(value.expression.expression, "inline");
968
+ if (items === null) return null;
969
+ const previousMode = this.entryMode;
970
+ this.entryMode = "per-entry";
971
+ this.entryParameters.push(parameter.name.text);
972
+ const template = this.buildBranch(callback.body);
973
+ this.entryParameters.pop();
974
+ this.entryMode = previousMode;
975
+ const first = template[0];
976
+ let key = null;
977
+ if (first !== void 0 && (first.kind === "element" || first.kind === "component-ref")) key = (first.kind === "element" ? first.attributes : first.kind === "component-ref" ? first.props : []).find((attribute) => attribute.kind === "dynamic" && attribute.channel === "key")?.expression ?? null;
978
+ return {
979
+ kind: "list",
980
+ parameter: parameter.name.text,
981
+ items,
982
+ key,
983
+ template,
984
+ span: spanOf(this.sourceFile, value)
985
+ };
986
+ }
987
+ buildElement(node, opening, tag) {
988
+ const tagReason = forbiddenSinkReason("tag", tag);
989
+ if (tagReason !== null) {
990
+ this.fail(opening.tagName, "OEC9010", `tag <${tag}> is a ${tagReason}`);
991
+ return null;
992
+ }
993
+ const voidChild = ts.isJsxElement(node) ? node.children.find(hasMeaningfulVoidChild) : void 0;
994
+ if (VOID_TAGS.has(tag) && voidChild !== void 0) {
995
+ this.fail(voidChild, "OEC9013", `void element <${tag}> may not have children`);
996
+ return null;
997
+ }
998
+ return {
999
+ kind: "element",
1000
+ tag,
1001
+ attributes: this.buildAttributes(opening.attributes, tag, true),
1002
+ children: ts.isJsxElement(node) ? this.buildChildren(node.children) : [],
1003
+ span: spanOf(this.sourceFile, node)
1004
+ };
1005
+ }
1006
+ buildComponentRef(node, opening, tag) {
1007
+ const target = this.componentBindings.get(tag);
1008
+ if (target !== void 0 && ts.isIdentifier(opening.tagName)) {
1009
+ if (this.resolved.resolveIdentifier(opening.tagName)?.declarationSpan.start !== target) {
1010
+ this.fail(opening.tagName, CODES.form, `component '<${tag}>' refers to a local value that shadows the component declaration`);
1011
+ return null;
1012
+ }
1013
+ }
1014
+ const props = this.buildAttributes(opening.attributes, tag, false);
1015
+ let childrenRecipeId = null;
1016
+ if (ts.isJsxElement(node) && node.children.length > 0) {
1017
+ const children = this.buildChildren(node.children);
1018
+ if (children.length > 0) {
1019
+ const fragment = {
1020
+ kind: "fragment",
1021
+ children,
1022
+ span: spanOf(this.sourceFile, node)
1023
+ };
1024
+ childrenRecipeId = this.registerChildrenRecipe(fragment);
1025
+ }
1026
+ }
1027
+ return {
1028
+ kind: "component-ref",
1029
+ name: tag,
1030
+ props,
1031
+ childrenRecipeId,
1032
+ span: spanOf(this.sourceFile, node)
1033
+ };
1034
+ }
1035
+ buildAttributes(attributes, tag, intrinsic) {
1036
+ const built = [];
1037
+ for (const property of attributes.properties) {
1038
+ if (ts.isJsxSpreadAttribute(property)) {
1039
+ this.fail(property, CODES.form, "spread attributes are outside the admitted grammar");
1040
+ continue;
1041
+ }
1042
+ const name = property.name.getText(this.sourceFile);
1043
+ const initializer = property.initializer;
1044
+ if (initializer === void 0 || ts.isStringLiteral(initializer)) {
1045
+ const staticName = name;
1046
+ if (intrinsic && this.screenStaticAttribute(staticName, tag, property)) continue;
1047
+ built.push({
1048
+ kind: "static",
1049
+ name,
1050
+ value: initializer === void 0 ? "true" : initializer.text,
1051
+ span: spanOf(this.sourceFile, property)
1052
+ });
1053
+ continue;
1054
+ }
1055
+ if (!ts.isJsxExpression(initializer) || initializer.expression === void 0) continue;
1056
+ const expressionNode = initializer.expression;
1057
+ const channel = classifyIntrinsicAttribute(name, tag);
1058
+ if (intrinsic && this.screenDynamicAttribute(name, tag, channel, property)) continue;
1059
+ const mode = channel === "event" || channel === "ref" ? "handler" : channel === "key" ? "key" : this.currentEntryMode();
1060
+ const expression = this.expression(expressionNode, mode);
1061
+ if (expression === null) continue;
1062
+ built.push({
1063
+ kind: "dynamic",
1064
+ name,
1065
+ channel,
1066
+ expression,
1067
+ span: spanOf(this.sourceFile, property)
1068
+ });
1069
+ }
1070
+ return built;
1071
+ }
1072
+ /** Shared deny/name predicates for a static attribute; returns true when refused. */
1073
+ screenStaticAttribute(name, tag, node) {
1074
+ if (name === "innerHTML") {
1075
+ this.fail(node, "OEC9011", "attribute name \"innerHTML\" is unsafe as a static attribute — innerHTML opens only through the trusted-HTML sink: bind an Object-typed trustedHtml(...) property and carry the literal trustedHtml marker");
1076
+ return true;
1077
+ }
1078
+ if (!isSafeAttributeName$1(name)) {
1079
+ this.fail(node, "OEC9011", `attribute name "${name}" is unsafe — names must be valid HTML attribute names, not event handlers (on*) or forbidden sinks; use an admitted attribute name`);
1080
+ return true;
1081
+ }
1082
+ return this.screenForbiddenName(name, node);
1083
+ }
1084
+ screenDynamicAttribute(name, tag, channel, property) {
1085
+ if (channel === "html") {
1086
+ this.fail(property, CODES.security, "innerHTML sinks are not admitted by the M03 function-component model (the trusted-HTML capability contract is a class-authoring mechanism); fail closed");
1087
+ return true;
1088
+ }
1089
+ if (channel === "event") return false;
1090
+ if (!isSafeAttributeName$1(name)) {
1091
+ this.fail(property, "OEC9011", `attribute name "${name}" is unsafe — names must be valid HTML attribute names, not event handlers (on*) or forbidden sinks; use an admitted attribute name`);
1092
+ return true;
1093
+ }
1094
+ return this.screenForbiddenName(name, property);
1095
+ }
1096
+ screenForbiddenName(name, node) {
1097
+ let reason = null;
1098
+ for (const sinkKind of [
1099
+ "prop",
1100
+ "bool",
1101
+ "attr"
1102
+ ]) {
1103
+ reason = forbiddenSinkReason(sinkKind, name);
1104
+ if (reason !== null) break;
1105
+ }
1106
+ if (reason === null) return false;
1107
+ this.fail(node, "OEC9011", `${reason} — the shared deny list screens every boundary; rename the attribute`);
1108
+ return true;
1109
+ }
1110
+ entryMode = "inline";
1111
+ currentEntryMode() {
1112
+ return this.entryMode;
1113
+ }
1114
+ currentPropsParam = null;
1115
+ diagnosticsView() {
1116
+ return this.diagnostics;
1117
+ }
1118
+ build(candidates) {
1119
+ const components = [];
1120
+ for (const candidate of candidates) this.componentBindings.set(candidate.name, candidate.bindingName.getStart(this.sourceFile));
1121
+ for (const candidate of candidates) {
1122
+ this.currentPropsParam = candidate.node.parameters[0] !== void 0 && ts.isIdentifier(candidate.node.parameters[0].name) ? candidate.node.parameters[0].name.text : null;
1123
+ const component = this.buildComponent(candidate);
1124
+ if (component !== null) components.push(component);
1125
+ }
1126
+ if (this.hasErrors()) return null;
1127
+ return {
1128
+ file: this.sourceFile.fileName,
1129
+ components,
1130
+ expressions: this.registry,
1131
+ imports: this.collectModuleImports()
1132
+ };
1133
+ }
1134
+ /**
1135
+ * The module's static import table. Type-only and side-effect imports carry
1136
+ * no readable binding, so they are not part of it; a named alias keeps the
1137
+ * authored `imported as local` spelling.
1138
+ */
1139
+ collectModuleImports() {
1140
+ const imports = [];
1141
+ for (const statement of this.sourceFile.statements) {
1142
+ if (!ts.isImportDeclaration(statement)) continue;
1143
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
1144
+ const clause = statement.importClause;
1145
+ if (clause === void 0 || clause.isTypeOnly) continue;
1146
+ const specifier = statement.moduleSpecifier.text;
1147
+ if (clause.name !== void 0) imports.push({
1148
+ specifier,
1149
+ imported: "default",
1150
+ local: clause.name.text,
1151
+ form: "default"
1152
+ });
1153
+ const bindings = clause.namedBindings;
1154
+ if (bindings !== void 0 && ts.isNamespaceImport(bindings)) imports.push({
1155
+ specifier,
1156
+ imported: "*",
1157
+ local: bindings.name.text,
1158
+ form: "namespace"
1159
+ });
1160
+ else if (bindings !== void 0) for (const element of bindings.elements) {
1161
+ if (element.isTypeOnly) continue;
1162
+ imports.push({
1163
+ specifier,
1164
+ imported: (element.propertyName ?? element.name).text,
1165
+ local: element.name.text,
1166
+ form: "named"
1167
+ });
1168
+ }
1169
+ }
1170
+ return imports;
1171
+ }
1172
+ };
1173
+ const RECIPE_REFERENCE_CALLEE = "__oe_recipe_ref";
1174
+ function isAndExpression(node) {
1175
+ return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken;
1176
+ }
1177
+ /**
1178
+ * Compile one authored module with the function-component frontend.
1179
+ *
1180
+ * Parallel entry, compiler-private: returns the component model plus the
1181
+ * expression sidecar, or the source-located OEC diagnostics that failed the
1182
+ * compile closed. It never calls the class frontend and emits no Part Program.
1183
+ */
1184
+ function compileFunctionModule(source, fileName, options = {}) {
1185
+ const parsed = typescriptParser.parseModule(source, fileName);
1186
+ const sourceFile = parsed.sourceFile;
1187
+ if (parsed.syntaxDiagnostics.length > 0) return {
1188
+ module: null,
1189
+ diagnostics: parsed.syntaxDiagnostics.map((diagnostic) => {
1190
+ const start = diagnostic.start ?? 0;
1191
+ const end = start + (diagnostic.length ?? 0);
1192
+ const position = sourceFile.getLineAndCharacterOfPosition(start);
1193
+ return {
1194
+ code: "OEC9000",
1195
+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, " "),
1196
+ file: fileName,
1197
+ line: position.line + 1,
1198
+ character: position.character + 1,
1199
+ start,
1200
+ end
1201
+ };
1202
+ })
1203
+ };
1204
+ const components = discoverComponents(sourceFile).filter(isComponentShape);
1205
+ if (components.length === 0) return {
1206
+ module: null,
1207
+ diagnostics: [diagnosticAt(sourceFile, sourceFile, CODES.shape, "no function component found (a top-level function or arrow returning JSX is required)")]
1208
+ };
1209
+ const resolved = resolveModule(sourceFile, {
1210
+ components: components.map((candidate) => candidate.node),
1211
+ ...options.importClassifier === void 0 ? {} : { importClassifier: options.importClassifier }
1212
+ });
1213
+ const diagnostics = resolved.diagnostics.map((diagnostic) => fromRefusal(sourceFile, diagnostic));
1214
+ if (diagnostics.length > 0) return {
1215
+ module: null,
1216
+ diagnostics
1217
+ };
1218
+ const builder = new FunctionFrontendBuilder(sourceFile, resolved, options.lifecycleAdmission);
1219
+ const module = builder.build(components);
1220
+ return module === null ? {
1221
+ module: null,
1222
+ diagnostics: builder.diagnosticsView()
1223
+ } : {
1224
+ module,
1225
+ diagnostics: []
1226
+ };
1227
+ }
1228
+ //#endregion
1229
+ export { compileFunctionModule };