@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,147 @@
1
+ //#region src/internal/compiler/semantic-ir/generated-element/contract.ts
2
+ /**
3
+ * The internal shell specifier the emitted CE module imports.
4
+ *
5
+ * Deliberately NOT a package `exports` subpath in M09-1a: the directory is
6
+ * still excluded from `@openelement/element`'s packed `files` set, and the
7
+ * compiler lane has no production caller. M09-1b deletes the exclusion, adds
8
+ * the export subpath, and points the emitted module at the exported spelling.
9
+ * Source-level M09-1a tests alias this specifier to the workspace source; the
10
+ * unresolved spelling cannot reach a real build because no production host
11
+ * passes a site fact yet.
12
+ */
13
+ const GENERATED_ELEMENT_SHELL_SPECIFIER = "@openelement/element/internal/compiled/generated-element/shell";
14
+ /**
15
+ * The internal diagnostic codes this lane can raise. They follow the shell's
16
+ * `OEIR_*` convention and are deliberately absent from the public error
17
+ * catalogue and the interface snapshot.
18
+ */
19
+ const GENERATED_ELEMENT_DIAGNOSTIC = {
20
+ /** A site module default-exports a function that is not an admitted component. */
21
+ NOT_A_COMPONENT: "OEIR_GENERATED_ELEMENT_NOT_A_COMPONENT",
22
+ /** The root component takes a props parameter; M09-1a cannot declare attributes. */
23
+ UNDECLARED_PROPS: "OEIR_GENERATED_ELEMENT_UNDECLARED_PROPS",
24
+ /** The generated body reads `host.bindings[*]` and no binding source exists. */
25
+ UNBOUND_BINDING: "OEIR_GENERATED_ELEMENT_UNBOUND_BINDING",
26
+ /** A fixed CE-tail identifier already occurs in the leaf text. */
27
+ NAME_COLLISION: "OEIR_GENERATED_ELEMENT_NAME_COLLISION",
28
+ /** The host admitted the module but the island sidecar is absent. */
29
+ MISSING_SITE_MARKER: "OEIR_GENERATED_ELEMENT_MISSING_SITE_MARKER",
30
+ /**
31
+ * The sidecar's `root` cannot be read as one of `'light' | 'shadow'`
32
+ * (a dynamic value, another literal, a duplicate key, or a config object
33
+ * whose key set is not static). The router scanner's `ISLAND_METADATA_ERROR`
34
+ * remains the author-facing authority; this code is the lane's own
35
+ * fail-closed verdict inside the compiler.
36
+ */
37
+ ROOT_INVALID: "OEIR_GENERATED_ELEMENT_ROOT_INVALID",
38
+ /**
39
+ * The sidecar's `delegatesFocus` cannot be read as one boolean literal (a
40
+ * dynamic value, a duplicate key, or a config object whose key set is not
41
+ * static). Like `ROOT_INVALID`, this is the lane's fail-closed verdict; the
42
+ * router scanner's `ISLAND_METADATA_ERROR` remains the author-facing
43
+ * authority and the two readers are held together by the seam drift guard.
44
+ */
45
+ DELEGATES_FOCUS_INVALID: "OEIR_GENERATED_ELEMENT_DELEGATES_FOCUS_INVALID",
46
+ /**
47
+ * The sidecar declares `delegatesFocus: true` without `root: 'shadow'`. A
48
+ * light root has no shadow boundary to delegate focus through; the shell's
49
+ * descriptor validation refuses the pair too, so the lane refuses before a
50
+ * module exists instead of shipping a class that throws on evaluation.
51
+ */
52
+ DELEGATES_FOCUS_WITHOUT_SHADOW: "OEIR_GENERATED_ELEMENT_DELEGATES_FOCUS_WITHOUT_SHADOW",
53
+ /**
54
+ * The root component's props parameter cannot be read as a typed primitive
55
+ * member list: no annotation, a destructured/rest parameter, an imported or
56
+ * generic type, a non-property member, an optional member or a non-primitive
57
+ * member type. The generated element's props record is a fixed
58
+ * string/number/boolean table; anything it cannot express fails closed
59
+ * instead of being silently dropped from the attribute channel.
60
+ */
61
+ PROPS_TYPE_UNSUPPORTED: "OEIR_GENERATED_ELEMENT_PROPS_TYPE_UNSUPPORTED",
62
+ /**
63
+ * The sidecar `properties` table and the typed props member list disagree
64
+ * (a declared key with no typed member or a typed member with no entry, or a
65
+ * declaration without a props parameter). The two declarations are
66
+ * cross-checked, never inferred one from the other.
67
+ */
68
+ PROPERTY_MISMATCH: "OEIR_GENERATED_ELEMENT_PROPERTY_MISMATCH",
69
+ /**
70
+ * One sidecar property entry is not representable: an unknown option, a
71
+ * non-literal default, an unsafe attribute name, a duplicate attribute, a
72
+ * reflected property with no attribute channel, a reserved lifecycle name, or
73
+ * a default whose literal type does not match the typed member.
74
+ */
75
+ PROPERTY_INVALID: "OEIR_GENERATED_ELEMENT_PROPERTY_INVALID",
76
+ /** The sidecar's `formAssociated` is not one boolean literal. */
77
+ FORM_ASSOCIATED_INVALID: "OEIR_GENERATED_ELEMENT_FORM_ASSOCIATED_INVALID",
78
+ /**
79
+ * The sidecar's `tag` is not one static string literal, or it is not a valid
80
+ * custom-element name. The lane refuses rather than admitting a module whose
81
+ * identity it cannot prove: the tag is the one host fact the compiler cannot
82
+ * derive, so a dynamic or malformed spelling would either admit the wrong
83
+ * module or register a name the platform rejects.
84
+ */
85
+ TAG_INVALID: "OEIR_GENERATED_ELEMENT_TAG_INVALID",
86
+ /**
87
+ * The form-associated declaration cannot be mapped to the bounded mechanics:
88
+ * no declared string `value` property, a non-boolean `required`/`disabled`,
89
+ * or a reflected `disabled` row (the fieldset state must stay reversible).
90
+ */
91
+ FORM_VALUE_UNSUPPORTED: "OEIR_GENERATED_ELEMENT_FORM_VALUE_UNSUPPORTED",
92
+ /**
93
+ * The sidecar's `ssr` cannot be read as one boolean literal (a dynamic value
94
+ * or a duplicate key). Only the EXPLICIT literal `false` is the client-only
95
+ * fact; `true` and an absent key are the same case, so a value this reader
96
+ * cannot prove must refuse instead of guessing the delivery phase.
97
+ */
98
+ SSR_INVALID: "OEIR_GENERATED_ELEMENT_SSR_INVALID",
99
+ /**
100
+ * A client-only island declares `styles`, but no static `.css` specifier
101
+ * reached the emitter. A client-only island has no DSD template to carry the
102
+ * marked `<link>`, so the sheet can only arrive through a real module-graph
103
+ * import; emitting the descriptor without one would render unstyled. This is
104
+ * the build-time half of the shim #24 failure closure, kept by the client
105
+ * style slice.
106
+ */
107
+ CLIENT_STYLES_UNWIRED: "OEIR_GENERATED_ELEMENT_CLIENT_STYLES_UNWIRED",
108
+ /** The appended tail did not parse (an emitter invariant, not author input). */
109
+ INVALID_ARTIFACT: "OEIR_GENERATED_ELEMENT_INVALID_ARTIFACT"
110
+ };
111
+ /**
112
+ * The function lane's import classifier: the canonical core factories the
113
+ * function grammar knows. The class lane's `CORE_VOCABULARY` has no `signal`
114
+ * entry, and the function frontend had no production caller before this lane
115
+ * (R12), so an omitted classifier would turn known factories into incidental
116
+ * refusals. Only the two factory names the function grammar admits are named;
117
+ * every other import stays host-classified by the caller.
118
+ */
119
+ /**
120
+ * The two specifiers that name the same factory/intrinsic symbols. The
121
+ * tree-shakeable `/lifecycle` subpath re-exports the identical functions, so it
122
+ * classifies identically — a consumer imported from either spelling is a real
123
+ * signal, and the tracked-slot dependency rule must not depend on which one the
124
+ * author happened to use.
125
+ */
126
+ const FACTORY_SPECIFIERS = /* @__PURE__ */ new Set(["@openelement/element", "@openelement/element/lifecycle"]);
127
+ const GENERATED_ELEMENT_IMPORT_CLASSIFIER = {
128
+ classifySymbol: (specifier, importedName) => {
129
+ if (!FACTORY_SPECIFIERS.has(specifier)) return void 0;
130
+ if (importedName === "signal" || importedName === "computed") return "factory";
131
+ if (importedName === "useContext") return "factory";
132
+ return "value";
133
+ },
134
+ classifyValue: (specifier, importedName) => {
135
+ if (importedName === null) return void 0;
136
+ if (FACTORY_SPECIFIERS.has(specifier)) return void 0;
137
+ return "plain";
138
+ },
139
+ classifyCall: (specifier, importedName) => {
140
+ if (!FACTORY_SPECIFIERS.has(specifier)) return void 0;
141
+ if (importedName === "signal") return { call: "signal" };
142
+ if (importedName === "computed") return { call: "computed" };
143
+ if (importedName === "useContext") return { call: "signal" };
144
+ }
145
+ };
146
+ //#endregion
147
+ export { GENERATED_ELEMENT_DIAGNOSTIC, GENERATED_ELEMENT_IMPORT_CLASSIFIER, GENERATED_ELEMENT_SHELL_SPECIFIER };
@@ -0,0 +1,452 @@
1
+ import { GENERATED_ELEMENT_DIAGNOSTIC, GENERATED_ELEMENT_SHELL_SPECIFIER } from "./contract.js";
2
+ import { CLAIM_SUFFIX, MOUNT_SUFFIX } from "../generated-leaf/emission.js";
3
+ import { collectStaticClassCandidates } from "../generated-leaf/structure.js";
4
+ import { quoteGeneratedJavaScriptValue } from "../generated-leaf/codegen-literals.js";
5
+ import { generateLeafModule } from "../generated-leaf/generate.js";
6
+ import ts from "typescript";
7
+ import { NESTED_HOST_EXPANDER } from "@openelement/protocol/style-sheet";
8
+ //#region src/internal/compiler/semantic-ir/generated-element/emit.ts
9
+ /**
10
+ * M09-1a — the generated native element emitter.
11
+ *
12
+ * `generateElementModule` is APPEND-ONLY over the landed M07a leaf generator:
13
+ * it calls `generateLeafModule`, keeps its text, source map and placements
14
+ * byte-identical, and appends one CE tail. It renames no leaf symbol and
15
+ * rewrites no leaf line, so the leaf source map and every placement stay
16
+ * valid; the appended lines carry no authored source and no map segments
17
+ * (their absence is stated on the result as `tail`, not implied).
18
+ *
19
+ * The tail:
20
+ *
21
+ * - imports the internal M09-0/M09-shadow shell by its compiler-private
22
+ * specifier;
23
+ * - for a CLIENT-ONLY island (`ssr: false` / `hydrate: 'only'`), imports each
24
+ * declared `.css` specifier as a REAL module edge and carries the bindings on
25
+ * the descriptor's `styles` row (2026-11-20): no server render exists to
26
+ * deliver the sheet, so the shell adopts these objects into the root it
27
+ * creates. A client-only declaration with no static specifier refuses at build
28
+ * time instead of rendering unstyled;
29
+ * - builds a descriptor with `tag`, the resolved `properties` rows (or `[]`),
30
+ * the leaf's exported `create<Name>Recipe` factory, `createInstance` only
31
+ * when the leaf generator reported a root setup factory (T3 / 16b-LC-1 —
32
+ * the row is driven by `rootInstanceFactory`, the generator's own emission
33
+ * decision, never by scanning the emitted text), `root` only when the
34
+ * authored sidecar pinned one (D-root-source: the lane reads it, the shell
35
+ * owns the `light` default), and `delegatesFocus: true` only when the
36
+ * sidecar declares it (the shell owns the `false` default);
37
+ * - constructs the class and default-exports it, with one named alias and the
38
+ * tag constant, so the existing island entry (`mod[exportName] ?? mod.default`)
39
+ * receives a constructor without any entry-selection change;
40
+ * - executes NO `customElements.define` and never mentions the registry;
41
+ * - appends `<Name>__ssrHost(props, lightChildren?)` (M09-2a) ONLY when the
42
+ * descriptor root is a shadow mode AND the leaf emitted `<Name>__ssr`. The
43
+ * wrapper composes the content-only `<Name>__ssr` bytes with the canonical
44
+ * DSD template through the `generated-element/dsd-ssr.ts` leaf, so the host
45
+ * artifact the browser parser adopts and the root the descriptor pins come
46
+ * from ONE declaration. A `delegatesFocus: true` descriptor threads the typed
47
+ * DSD option into the same template (`shadowrootdelegatesfocus`), so the
48
+ * claimed root reports the same fact the descriptor does; without it the
49
+ * shell's root-option check would refuse the claim. A light root appends
50
+ * nothing: its tail keeps the exact M09-1a bytes.
51
+ *
52
+ * Fixed identifier collisions fail closed instead of producing a module that
53
+ * cannot parse: the tail's module-scope names, the alias and the import
54
+ * binding are checked against the leaf text before the tail is appended.
55
+ * A hostless module (site null) returns the leaf result unchanged.
56
+ *
57
+ * The result also reports the emitted host-wrapper export name
58
+ * (`ssrHostExport`) as build metadata, produced by the SAME `hostWrapper`
59
+ * decision that appends the wrapper. It is return-only: the field never
60
+ * changes the module text, and callers must read it instead of re-deriving the
61
+ * name from the emitted artifact (M11 review §3/§4.1). The inherited
62
+ * `rootInstanceFactory` field is the same kind of return-only metadata for the
63
+ * T3 root setup factory: non-null exactly when the leaf wrote the declaration.
64
+ */
65
+ /**
66
+ * Compiler-private record key + local name of the generated host producer's
67
+ * canonical host-attribute projection (M11-2). The shell's seed helper attaches
68
+ * the merged caller+computed pairs under this ONE literal key; the emitted
69
+ * wrapper reads it with the same literal (like the other `__oe_` compiler-owned
70
+ * names, authored identifiers cannot carry the prefix).
71
+ */
72
+ const HOST_ATTRIBUTES_KEY = "__oeHostAttributes";
73
+ const HOST_ATTRIBUTES_VAR = "__oeHostAttrs";
74
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
75
+ function moduleDiagnostic(file, code, message) {
76
+ return {
77
+ severity: "error",
78
+ code,
79
+ message,
80
+ span: {
81
+ file,
82
+ start: 0,
83
+ end: 0,
84
+ line: 1,
85
+ column: 1
86
+ },
87
+ origin: "module"
88
+ };
89
+ }
90
+ /**
91
+ * A conservative whole-token occurrence test: `ProfileElement` must not hide
92
+ * inside `ProfileElementExtra`, but a same-token occurrence in a string or
93
+ * comment is still a fail-closed collision. JavaScript module scope is the
94
+ * only question; text conservatism is the safe direction.
95
+ */
96
+ function identifierOccurs(text, name) {
97
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
98
+ return new RegExp(`(?<![A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`).test(text);
99
+ }
100
+ /**
101
+ * Does the leaf artifact export `<Name>__ssr`?
102
+ *
103
+ * The leaf generator emits `export function <Name>__ssr(…)` for every component
104
+ * inside its producer slice and no `__ssr` export at all for a shape outside it
105
+ * (its documented "no partial producer" rule: a condition, list, component
106
+ * reference or insertion site yields no producer). The M09-2a host wrapper
107
+ * calls that export, so it must be appended only when the declaration is there;
108
+ * referencing an absent symbol would turn a compile-time fact into a runtime
109
+ * `ReferenceError`. The check reads the leaf text this emitter itself produced,
110
+ * not author input.
111
+ */
112
+ function exportsSsrFunction(leafText, componentName) {
113
+ const escaped = componentName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
114
+ return new RegExp(`export function ${escaped}__ssr\\s*\\(`).test(leafText);
115
+ }
116
+ /**
117
+ * The descriptor root's DSD wire spelling, or null for a root that has no host
118
+ * template. `light` (and an absent root, which the shell defaults to `light`)
119
+ * produces no template, so no host wrapper is appended and the light tail stays
120
+ * byte-identical. `D-closed` keeps `shadow-closed` unauthorable, but the
121
+ * mapping is total so a future closed spelling cannot silently fall through to
122
+ * an open template.
123
+ */
124
+ function hostTemplateRoot(root) {
125
+ switch (root) {
126
+ case "shadow-open": return "open";
127
+ case "shadow-closed": return "closed";
128
+ case "light":
129
+ case void 0: return null;
130
+ }
131
+ }
132
+ /** The parser check the leaf generator applies to its own artifact. */
133
+ function parsesAsModule(text) {
134
+ return (ts.createSourceFile("generated-element.js", text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS).parseDiagnostics ?? []).length === 0;
135
+ }
136
+ function emptyResult(leaf, diagnostics) {
137
+ return {
138
+ module: null,
139
+ sourceMap: leaf.sourceMap,
140
+ placements: leaf.placements,
141
+ rootInstanceFactory: null,
142
+ hostFeatures: null,
143
+ requiredBindings: leaf.requiredBindings,
144
+ requiredProps: leaf.requiredProps,
145
+ requiresPropsChanged: leaf.requiresPropsChanged,
146
+ classCandidates: [],
147
+ diagnostics,
148
+ leaf: null,
149
+ tail: null,
150
+ ssrHostExport: null,
151
+ lightSsr: false
152
+ };
153
+ }
154
+ /** Render one admitted literal default graph as JavaScript source. */
155
+ function renderDefaultGraph(graph) {
156
+ if (graph === null) return "null";
157
+ if (typeof graph === "string") return quoteGeneratedJavaScriptValue(graph);
158
+ if (typeof graph === "number" || typeof graph === "boolean") return String(graph);
159
+ if (Array.isArray(graph)) return `[${graph.map((entry) => renderDefaultGraph(entry)).join(", ")}]`;
160
+ return `{ ${Object.entries(graph).map(([key, value]) => `${quoteGeneratedJavaScriptValue(key)}: ${renderDefaultGraph(value)}`).join(", ")} }`;
161
+ }
162
+ /**
163
+ * The descriptor's `properties` rows, byte-for-byte.
164
+ *
165
+ * Primitive and trustedHtml rows spell the value directly (trustedHtml carries
166
+ * the literal HTML string; the shell brands it per materialisation). Array and
167
+ * object rows emit ONE module-level fresh-literal factory each and the row
168
+ * references that factory name, so the descriptor never holds a mutable shared
169
+ * default graph: the shell calls it once per element instance and the SSR
170
+ * resolver once per render. A module with no table keeps `properties: []`
171
+ * exactly as M09-1a.
172
+ */
173
+ function buildPropertyEmission(properties) {
174
+ if (properties.length === 0) return {
175
+ factoryLines: [],
176
+ rowLines: [" properties: [],"],
177
+ identifiers: [],
178
+ usesPropsResolver: false,
179
+ hasAttributeRows: false,
180
+ emitsHostAttributeSeed: false
181
+ };
182
+ const factoryLines = [];
183
+ const identifiers = [];
184
+ let usesPropsResolver = false;
185
+ return {
186
+ factoryLines,
187
+ rowLines: [
188
+ " properties: [",
189
+ ...properties.map((property, index) => {
190
+ const attribute = property.attribute === null ? "null" : JSON.stringify(property.attribute);
191
+ let defaultValue = "";
192
+ if (property.type === "array" || property.type === "object") {
193
+ const factoryName = `__oePropertyDefault${index}`;
194
+ identifiers.push(factoryName);
195
+ factoryLines.push(`const ${factoryName} = () => (${renderDefaultGraph(property.defaultGraph)});`);
196
+ defaultValue = factoryName;
197
+ usesPropsResolver = true;
198
+ } else if (property.type === "trustedHtml") {
199
+ defaultValue = quoteGeneratedJavaScriptValue(property.default);
200
+ usesPropsResolver = true;
201
+ } else defaultValue = quoteGeneratedJavaScriptValue(property.default);
202
+ return ` { name: ${JSON.stringify(property.name)}, attribute: ${attribute}, type: ${JSON.stringify(property.type)}, reflect: ${String(property.reflect)}, default: ${defaultValue} },`;
203
+ }),
204
+ " ],"
205
+ ],
206
+ identifiers,
207
+ usesPropsResolver,
208
+ hasAttributeRows: properties.some((property) => property.attribute !== null),
209
+ emitsHostAttributeSeed: properties.some((property) => property.attribute !== null || property.type !== "trustedHtml")
210
+ };
211
+ }
212
+ /**
213
+ * Append the M09-1a CE tail to one generated leaf module./**
214
+ * Append the M09-1a CE tail to one generated leaf module.
215
+ *
216
+ * `site` null is the hostless case: the result is byte-identical to
217
+ * `generateLeafModule`'s (the proof in `generated-element.emitter.test.ts`).
218
+ * The admission gates that read the authored AST live in `site.ts`; this
219
+ * function is the text stage and refuses only emitter invariants.
220
+ */
221
+ /**
222
+ * The host record a shadow host producer hands its leaf's `__ssr`.
223
+ *
224
+ * The leaf already routes every custom-element tag through the ONE `nestedHost`
225
+ * helper, which reads the expander off this record (`nestedHost.ts`'s
226
+ * `NESTED_HOST_PROPERTY`). The LIGHT root's producer has always supplied it; the
227
+ * SHADOW wrapper did not, which is why a shadow page's inner components rendered
228
+ * as bare tags. This is the record's spelling, kept in one place so the emitted
229
+ * bytes and the runtime helper can never drift about the field name.
230
+ */
231
+ const NESTED_HOST_RECORD_ARG = `nestedHost === undefined ? undefined : { "${NESTED_HOST_EXPANDER}": nestedHost }`;
232
+ function isDirectShadowNode(node) {
233
+ switch (node.kind) {
234
+ case "text":
235
+ case "dynamic-text": return true;
236
+ case "fragment": return node.children.every(isDirectShadowNode);
237
+ case "element": return !node.tag.includes("-") && node.tag !== "slot" && node.attributes.every((attribute) => attribute.kind === "static" || attribute.channel !== "ref" && attribute.channel !== "html") && node.children.every(isDirectShadowNode);
238
+ default: return false;
239
+ }
240
+ }
241
+ function admitsDirectShadowDriver(module, leaf, options) {
242
+ if (options.allowDirectShadowDriver !== true || options.root !== "shadow-open" || options.formAssociated === true || (options.properties?.length ?? 0) !== 0 || module.components.length !== 1 || leaf.hostFeatures?.rootClaim !== true || leaf.hostFeatures.context || leaf.hostFeatures.ledger || leaf.requiresPropsChanged || leaf.requiredProps.length !== 0) return false;
243
+ const component = module.components[0];
244
+ return component.propsParam === null && component.recipes.length === 0 && component.contextProviders.length === 0 && component.resources.every(({ kind }) => kind === "signal" || kind === "local") && component.lifecycle.every((hook) => hook.kind === "connect" && !hook.receivesEnv) && component.roots.every(isDirectShadowNode);
245
+ }
246
+ function generateElementModule(module, site, options = {}) {
247
+ const rootCandidate = site === null ? void 0 : options.rootComponent ?? (module.components.length === 1 ? module.components[0].name : void 0);
248
+ const rootInstanceName = rootCandidate !== void 0 && IDENTIFIER.test(rootCandidate) && module.components.some((component) => component.name === rootCandidate) ? rootCandidate : void 0;
249
+ const templateRoot = hostTemplateRoot(options.root);
250
+ const declaredStyles = options.styleLinkPrefix === true;
251
+ const utilityChannel = (options.root === "shadow-open" || options.root === "shadow-closed") && collectStaticClassCandidates(module).length > 0;
252
+ const styleLinkPrefix = declaredStyles || utilityChannel;
253
+ const clientOnly = options.clientOnly === true;
254
+ const clientStyles = clientOnly ? options.styles ?? [] : [];
255
+ const leaf = generateLeafModule(module, {
256
+ ...options.authoredSource === void 0 ? {} : { authoredSource: options.authoredSource },
257
+ ...rootInstanceName === void 0 ? {} : { rootInstance: rootInstanceName },
258
+ ...templateRoot === null ? {} : { claimStyleLinkPrefix: true },
259
+ ...templateRoot === null ? { lightRoot: true } : {}
260
+ });
261
+ const leafText = leaf.module;
262
+ if (leafText === null) return {
263
+ ...emptyResult(leaf, leaf.diagnostics),
264
+ leaf: null,
265
+ tail: null
266
+ };
267
+ if (site === null) return {
268
+ module: leafText,
269
+ sourceMap: leaf.sourceMap,
270
+ placements: leaf.placements,
271
+ rootInstanceFactory: leaf.rootInstanceFactory,
272
+ hostFeatures: leaf.hostFeatures,
273
+ requiredBindings: leaf.requiredBindings,
274
+ requiredProps: leaf.requiredProps,
275
+ requiresPropsChanged: leaf.requiresPropsChanged,
276
+ classCandidates: leaf.classCandidates,
277
+ diagnostics: leaf.diagnostics,
278
+ leaf: leafText,
279
+ tail: null,
280
+ ssrHostExport: null,
281
+ lightSsr: false
282
+ };
283
+ const rootName = rootCandidate;
284
+ if (rootName === void 0 || !IDENTIFIER.test(rootName)) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.NOT_A_COMPONENT, "the generated element emitter needs one named default-exported component to append a CE tail")]);
285
+ if (clientOnly && options.styles !== void 0 && clientStyles.length === 0) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.CLIENT_STYLES_UNWIRED, "this island declares openElement.styles and is client-only (ssr: false), but no static .css specifier reached the emitter. A client-only island has no DSD template to carry the stylesheet link, so the sheet can only arrive through a module-graph import: refusing instead of rendering the element unstyled")]);
286
+ if (!module.components.some((component) => component.name === rootName)) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.NOT_A_COMPONENT, `the default export "${rootName}" is not a component of this module`)]);
287
+ const names = {
288
+ descriptor: "__oeElementDescriptor",
289
+ element: `__oe${rootName}Element`,
290
+ alias: `${rootName}Element`,
291
+ tag: "__oeElementTag",
292
+ shellImport: "__oe_createElementClass",
293
+ ssrHostImport: "serializeGeneratedElementHtml",
294
+ hostPropsSeed: "seedGeneratedElementHostProperties",
295
+ hostPropsVar: "__oeHostProps",
296
+ propsResolver: "resolveGeneratedElementProps",
297
+ ssrHost: `${rootName}__ssrHost`,
298
+ ssrProducer: `${rootName}__ssr`,
299
+ styleImport: (index) => `__oeStyle${index}`
300
+ };
301
+ const root = options.root;
302
+ const delegatesFocus = options.delegatesFocus === true;
303
+ const formAssociated = options.formAssociated === true;
304
+ const supports = leaf.hostFeatures;
305
+ const direct = admitsDirectShadowDriver(module, leaf, options);
306
+ const hasDeclaredProperties = (options.properties?.length ?? 0) !== 0;
307
+ const rowless = supports !== null && !hasDeclaredProperties;
308
+ const hostPropsSeedImport = rowless ? `seedGeneratedElementHostPropertiesWithoutRows as ${names.hostPropsSeed}` : names.hostPropsSeed;
309
+ const hostPropsSeedArguments = rowless ? "props, attributes" : `${names.descriptor}.properties, props, attributes`;
310
+ const hostFeatures = supports === null ? [] : [
311
+ ...formAssociated ? [[
312
+ "form",
313
+ "GeneratedElementForm",
314
+ "__oe_formFeature"
315
+ ]] : [],
316
+ ...supports.context ? [[
317
+ "context",
318
+ "createGeneratedElementContext",
319
+ "__oe_contextFeature"
320
+ ]] : [],
321
+ ...supports.ledger ? [[
322
+ "ledger",
323
+ "generatedElementLedger",
324
+ "__oe_ledgerFeature"
325
+ ]] : [],
326
+ ...hasDeclaredProperties ? [[
327
+ "properties",
328
+ "generatedElementProperties",
329
+ "__oe_propertiesFeature"
330
+ ]] : []
331
+ ];
332
+ const fields = hostFeatures.map(([key, , local]) => `${key}: ${local}`).join(", ");
333
+ const featureArgument = supports === null || direct ? "" : fields === "" ? ", {}" : `, { ${fields} }`;
334
+ const shellFactory = direct ? "createDirectShadowElementClassWithProjection" : supports === null ? "createGeneratedElementClass" : "createGeneratedElementClassWithFeatures";
335
+ if (delegatesFocus && templateRoot === null) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.DELEGATES_FOCUS_WITHOUT_SHADOW, "delegatesFocus requires a shadow descriptor root; the shell refuses the pair at class creation time")]);
336
+ const producerlessClientOnly = options.clientOnly === true && clientStyles.length === 0;
337
+ const hasSsrContent = exportsSsrFunction(leafText, rootName);
338
+ const lightSsr = templateRoot === null && hasSsrContent;
339
+ const hostWrapper = !producerlessClientOnly && templateRoot !== null && hasSsrContent ? {
340
+ root: templateRoot,
341
+ name: names.ssrHost
342
+ } : null;
343
+ const propertyEmission = buildPropertyEmission(options.properties ?? []);
344
+ const collisions = [
345
+ names.descriptor,
346
+ names.element,
347
+ names.alias,
348
+ names.tag,
349
+ names.shellImport,
350
+ ...hostFeatures.map(([, , local]) => local),
351
+ ...clientStyles.map((_, index) => names.styleImport(index)),
352
+ ...propertyEmission.identifiers,
353
+ ...propertyEmission.usesPropsResolver && hostWrapper !== null ? [names.propsResolver] : [],
354
+ ...hostWrapper === null ? [] : [
355
+ names.ssrHostImport,
356
+ names.hostPropsSeed,
357
+ names.hostPropsVar,
358
+ names.ssrHost,
359
+ ...styleLinkPrefix ? ["styleLinks"] : []
360
+ ]
361
+ ].filter((name) => identifierOccurs(leafText, name));
362
+ if (collisions.length > 0) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.NAME_COLLISION, `the generated element tail identifiers already occur in the leaf module: ${collisions.map((name) => `"${name}"`).join(", ")}`)]);
363
+ const rootInstanceFactory = leaf.rootInstanceFactory;
364
+ const tail = [
365
+ "",
366
+ "// ---- generated native element (M09-1) ----",
367
+ `import { ${[
368
+ `${shellFactory} as ${names.shellImport}`,
369
+ ...hostFeatures.map(([, exported, local]) => `${exported} as ${local}`),
370
+ ...propertyEmission.usesPropsResolver && hostWrapper !== null ? [names.propsResolver] : [],
371
+ ...hostWrapper === null ? [] : [names.ssrHostImport, hostPropsSeedImport]
372
+ ].join(", ")} } from ${JSON.stringify(GENERATED_ELEMENT_SHELL_SPECIFIER)};`,
373
+ ...clientStyles.map((specifier, index) => `import ${names.styleImport(index)} from ${JSON.stringify(specifier)};`),
374
+ "",
375
+ ...propertyEmission.factoryLines,
376
+ ...propertyEmission.factoryLines.length === 0 ? [] : [""],
377
+ `const ${names.descriptor} = {`,
378
+ ` tag: ${JSON.stringify(site.tag)},`,
379
+ ...root === void 0 || direct ? [] : [` root: ${JSON.stringify(root)},`],
380
+ ...delegatesFocus ? [" delegatesFocus: true,"] : [],
381
+ ...formAssociated ? [" formAssociated: true,"] : [],
382
+ ...direct ? [] : propertyEmission.rowLines,
383
+ ...clientStyles.length === 0 ? [] : [` styles: [${clientStyles.map((_, index) => names.styleImport(index)).join(", ")}],`],
384
+ ...direct ? [
385
+ ` source: ${JSON.stringify(`${module.file}#${rootName}`)},`,
386
+ ` mount: ${rootName}${MOUNT_SUFFIX},`,
387
+ ` claim: ${rootName}${CLAIM_SUFFIX},`
388
+ ] : [` createRecipe: create${rootName}Recipe,`],
389
+ ...rootInstanceFactory === null ? [] : [` createInstance: ${rootInstanceFactory},`],
390
+ ...lightSsr ? [` ssrProducer: ${names.ssrProducer},`] : [],
391
+ "};",
392
+ "",
393
+ `const ${names.element} = ${names.shellImport}(${names.descriptor}${featureArgument});`,
394
+ "",
395
+ `export default ${names.element};`,
396
+ `export { ${names.element} as ${names.alias} };`,
397
+ `export const ${names.tag} = ${JSON.stringify(site.tag)};`,
398
+ ...hostWrapper === null ? [] : [
399
+ "",
400
+ "// ---- generated shadow host SSR (M09-2a) ----",
401
+ `export function ${hostWrapper.name}(props, lightChildren, attributes, styleLinks, nestedHost) {`,
402
+ ...declaredStyles ? [" if (!Array.isArray(styleLinks) || styleLinks.length === 0) throw new Error(\"OEIR_LEAF_MISSING_VALUE: styleLinks (the styled generated element received no declared stylesheet URLs; mixed generated-element/entry artifacts or a missing style-link carrier)\");"] : [],
403
+ ...propertyEmission.emitsHostAttributeSeed ? [
404
+ ` const ${names.hostPropsVar} = ${names.hostPropsSeed}(${hostPropsSeedArguments});`,
405
+ ` const ${HOST_ATTRIBUTES_VAR} = ${names.hostPropsVar}.${HOST_ATTRIBUTES_KEY};`,
406
+ ` return ${names.ssrHostImport}({`,
407
+ ` tag: ${JSON.stringify(site.tag)},`,
408
+ ` root: ${JSON.stringify(hostWrapper.root)},`,
409
+ ...delegatesFocus ? [" dsd: { delegatesFocus: true },"] : [],
410
+ ` content: ${rootName}__ssr(${propertyEmission.usesPropsResolver ? `${names.propsResolver}(${names.descriptor}, ${names.hostPropsVar})` : names.hostPropsVar}, ${NESTED_HOST_RECORD_ARG}),`,
411
+ " ...(lightChildren === undefined ? {} : { lightChildren }),",
412
+ ` ...(attributes === undefined && ${HOST_ATTRIBUTES_VAR} === undefined ? {} : { attributes: ${HOST_ATTRIBUTES_VAR} === undefined ? attributes : ${HOST_ATTRIBUTES_VAR} }),`,
413
+ " ...(styleLinks === undefined ? {} : { styleLinks }),",
414
+ " });",
415
+ "}"
416
+ ] : [
417
+ ` const ${names.hostPropsVar} = ${names.hostPropsSeed}(${hostPropsSeedArguments});`,
418
+ ` return ${names.ssrHostImport}({`,
419
+ ` tag: ${JSON.stringify(site.tag)},`,
420
+ ` root: ${JSON.stringify(hostWrapper.root)},`,
421
+ ...delegatesFocus ? [" dsd: { delegatesFocus: true },"] : [],
422
+ ` content: ${rootName}__ssr(${propertyEmission.usesPropsResolver ? `${names.propsResolver}(${names.descriptor}, ${names.hostPropsVar})` : names.hostPropsVar}, ${NESTED_HOST_RECORD_ARG}),`,
423
+ " ...(lightChildren === undefined ? {} : { lightChildren }),",
424
+ " ...(attributes === undefined ? {} : { attributes }),",
425
+ " ...(styleLinks === undefined ? {} : { styleLinks }),",
426
+ " });",
427
+ "}"
428
+ ]
429
+ ],
430
+ ""
431
+ ].join("\n");
432
+ const emitted = `${leafText}${tail}`;
433
+ if (!parsesAsModule(emitted)) return emptyResult(leaf, [moduleDiagnostic(module.file, GENERATED_ELEMENT_DIAGNOSTIC.INVALID_ARTIFACT, "the emitted module with the generated element tail does not parse as JavaScript")]);
434
+ return {
435
+ module: emitted,
436
+ sourceMap: leaf.sourceMap,
437
+ placements: leaf.placements,
438
+ rootInstanceFactory: leaf.rootInstanceFactory,
439
+ hostFeatures: leaf.hostFeatures,
440
+ requiredBindings: leaf.requiredBindings,
441
+ requiredProps: leaf.requiredProps,
442
+ requiresPropsChanged: leaf.requiresPropsChanged,
443
+ classCandidates: leaf.classCandidates,
444
+ diagnostics: [],
445
+ leaf: leafText,
446
+ tail,
447
+ ssrHostExport: hostWrapper === null ? null : hostWrapper.name,
448
+ lightSsr
449
+ };
450
+ }
451
+ //#endregion
452
+ export { generateElementModule };