@openelement/compiler 0.0.0-stage → 1.0.0-alpha.11

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 (29) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/package.json +45 -4
  4. package/src/compiler.d.ts +8 -0
  5. package/src/compiler.js +8 -0
  6. package/src/internal/compiler/plugin.d.ts +95 -0
  7. package/src/internal/compiler/plugin.js +133 -0
  8. package/src/internal/compiler/semantic-core/analyze-module.js +479 -0
  9. package/src/internal/compiler/semantic-core/compile.d.ts +39 -0
  10. package/src/internal/compiler/semantic-core/compile.js +98 -0
  11. package/src/internal/compiler/semantic-core/compiler-diagnostics.d.ts +31 -0
  12. package/src/internal/compiler/semantic-core/compiler-diagnostics.js +50 -0
  13. package/src/internal/compiler/semantic-core/diagnostics/index.d.ts +54 -0
  14. package/src/internal/compiler/semantic-core/diagnostics/index.js +97 -0
  15. package/src/internal/compiler/semantic-core/emit-module.js +259 -0
  16. package/src/internal/compiler/semantic-core/emit-program.js +121 -0
  17. package/src/internal/compiler/semantic-core/lower-program.js +815 -0
  18. package/src/internal/compiler/semantic-core/module-analysis.d.ts +115 -0
  19. package/src/internal/compiler/semantic-core/module-analysis.js +263 -0
  20. package/src/internal/compiler/semantic-core/parse-module.js +37 -0
  21. package/src/internal/compiler/semantic-core/source-map.d.ts +53 -0
  22. package/src/internal/compiler/semantic-core/source-map.js +93 -0
  23. package/src/internal/compiler/semantic-core/style-imports.js +87 -0
  24. package/src/internal/compiler/semantic-core/type-check.d.ts +50 -0
  25. package/src/internal/compiler/semantic-core/type-check.js +106 -0
  26. package/src/internal/compiler/style-requests.d.ts +53 -0
  27. package/src/internal/compiler/style-requests.js +50 -0
  28. package/src/vite.d.ts +2 -0
  29. package/src/vite.js +2 -0
@@ -0,0 +1,50 @@
1
+ import { CompilerDiagnosticError, diagnosticAt, diagnosticMessage } from "./diagnostics/index.js";
2
+ //#region src/internal/compiler/semantic-core/compiler-diagnostics.ts
3
+ /** Error shape consumed by the Vite plugin and compiler tests. */
4
+ var CompiledElementError = class extends CompilerDiagnosticError {
5
+ constructor(diagnostics) {
6
+ super(diagnostics);
7
+ this.name = "CompiledElementError";
8
+ }
9
+ };
10
+ /** Build the fail closure for one parsed module source file. */
11
+ function failAt(sf) {
12
+ return (node, code, message) => {
13
+ throw new CompiledElementError([diagnosticAt(sf, node, code, message)]);
14
+ };
15
+ }
16
+ function sourceRange(sf, node) {
17
+ const start = node.getStart(sf);
18
+ const end = node.getEnd();
19
+ const startPosition = sf.getLineAndCharacterOfPosition(start);
20
+ const endPosition = sf.getLineAndCharacterOfPosition(end);
21
+ return {
22
+ file: sf.fileName,
23
+ start: {
24
+ offset: start,
25
+ line: startPosition.line + 1,
26
+ column: startPosition.character + 1
27
+ },
28
+ end: {
29
+ offset: end,
30
+ line: endPosition.line + 1,
31
+ column: endPosition.character + 1
32
+ }
33
+ };
34
+ }
35
+ function parseDiagnostic(sf, diagnostic) {
36
+ const start = diagnostic.start ?? 0;
37
+ const end = diagnostic.start === void 0 ? start : start + (diagnostic.length ?? 0);
38
+ const position = sf.getLineAndCharacterOfPosition(start);
39
+ return {
40
+ code: "OEC9000",
41
+ message: diagnosticMessage(diagnostic),
42
+ file: sf.fileName,
43
+ line: position.line + 1,
44
+ character: position.character + 1,
45
+ start,
46
+ end
47
+ };
48
+ }
49
+ //#endregion
50
+ export { CompiledElementError, failAt, parseDiagnostic, sourceRange };
@@ -0,0 +1,54 @@
1
+ import ts from "typescript";
2
+ import { OpenElementError } from "@openelement/protocol/errors";
3
+ //#region src/internal/compiler/semantic-core/diagnostics/index.d.ts
4
+ export interface CompilerDiagnostic {
5
+ code: string;
6
+ message: string;
7
+ file: string;
8
+ line: number;
9
+ character: number;
10
+ start: number;
11
+ end: number;
12
+ }
13
+ /**
14
+ * One compile step refused the module it was handed. Part of the single error
15
+ * dialect (#1386 item 3): an `OpenElementError` carrying
16
+ * {@linkcode CompilerErrorCode.DIAGNOSTICS}, so a build adapter catches a
17
+ * failed compile by code. The per-diagnostic `OEC####` codes stay on each
18
+ * record in `diagnostics` — those locate a source range, this classifies the
19
+ * failure.
20
+ */
21
+ export declare class CompilerDiagnosticError extends OpenElementError {
22
+ readonly diagnostics: CompilerDiagnostic[];
23
+ constructor(diagnostics: CompilerDiagnostic[]);
24
+ }
25
+ /** Create one stable source range from a TypeScript AST node. */
26
+ declare function diagnosticAt(sourceFile: ts.SourceFile, node: ts.Node, code: string, message: string): CompilerDiagnostic;
27
+ /** Flatten a TypeScript parse diagnostic without leaking compiler internals. */
28
+ declare function diagnosticMessage(diagnostic: ts.Diagnostic): string;
29
+ /** Rollup-compatible error shape emitted by the Vite adapter boundary. */
30
+ export interface PluginDiagnosticError {
31
+ id: string;
32
+ loc: {
33
+ file: string;
34
+ line: number;
35
+ column: number;
36
+ };
37
+ frame: string;
38
+ message: string;
39
+ diagnostics: CompilerDiagnostic[];
40
+ }
41
+ /**
42
+ * Render the authored line and its neighbours with a caret under the recorded
43
+ * range — the frame field a build overlay consumes. Multi-line ranges caret
44
+ * only the first line (Rollup's own frames do the same); an empty or
45
+ * out-of-range location degrades to the nearest real line instead of failing.
46
+ */
47
+ declare function formatDiagnosticFrame(source: string, diagnostic: CompilerDiagnostic, context?: number): string;
48
+ /**
49
+ * Project compiler diagnostics onto the adapter's error shape. Returns null
50
+ * for an empty diagnostics list: there is nothing to locate or render, and
51
+ * the caller keeps its own fallback rather than inventing a location.
52
+ */
53
+ declare function diagnosticPluginError(diagnostics: CompilerDiagnostic[], source: string, id: string): PluginDiagnosticError | null;
54
+ //#endregion
@@ -0,0 +1,97 @@
1
+ import ts from "typescript";
2
+ import { CompilerErrorCode, OpenElementError } from "@openelement/protocol/errors";
3
+ //#region src/internal/compiler/semantic-core/diagnostics/index.ts
4
+ /**
5
+ * Source-aware diagnostics for the compiler boundary.
6
+ *
7
+ * Diagnostics are deliberately small and serializable. The Vite adapter turns
8
+ * the formatted error into its build error, while compiler tests can inspect
9
+ * the structured record without parsing a display string.
10
+ */
11
+ /**
12
+ * One compile step refused the module it was handed. Part of the single error
13
+ * dialect (#1386 item 3): an `OpenElementError` carrying
14
+ * {@linkcode CompilerErrorCode.DIAGNOSTICS}, so a build adapter catches a
15
+ * failed compile by code. The per-diagnostic `OEC####` codes stay on each
16
+ * record in `diagnostics` — those locate a source range, this classifies the
17
+ * failure.
18
+ */
19
+ var CompilerDiagnosticError = class extends OpenElementError {
20
+ diagnostics;
21
+ constructor(diagnostics) {
22
+ super(diagnostics.map((diagnostic) => `${diagnostic.file}:${diagnostic.line}:${diagnostic.character} - error ${diagnostic.code}: ${diagnostic.message}`).join("\n"), {
23
+ code: CompilerErrorCode.DIAGNOSTICS,
24
+ severity: "error",
25
+ phase: "build",
26
+ recoverable: false
27
+ });
28
+ this.name = "CompilerDiagnosticError";
29
+ this.diagnostics = diagnostics;
30
+ }
31
+ };
32
+ /** Create one stable source range from a TypeScript AST node. */
33
+ function diagnosticAt(sourceFile, node, code, message) {
34
+ const start = node.getStart(sourceFile);
35
+ const end = node.getEnd();
36
+ const position = sourceFile.getLineAndCharacterOfPosition(start);
37
+ return {
38
+ code,
39
+ message,
40
+ file: sourceFile.fileName,
41
+ line: position.line + 1,
42
+ character: position.character + 1,
43
+ start,
44
+ end
45
+ };
46
+ }
47
+ /** Flatten a TypeScript parse diagnostic without leaking compiler internals. */
48
+ function diagnosticMessage(diagnostic) {
49
+ return ts.flattenDiagnosticMessageText(diagnostic.messageText, " ");
50
+ }
51
+ /**
52
+ * Render the authored line and its neighbours with a caret under the recorded
53
+ * range — the frame field a build overlay consumes. Multi-line ranges caret
54
+ * only the first line (Rollup's own frames do the same); an empty or
55
+ * out-of-range location degrades to the nearest real line instead of failing.
56
+ */
57
+ function formatDiagnosticFrame(source, diagnostic, context = 2) {
58
+ const lines = source.split("\n");
59
+ const lineIndex = Math.min(Math.max(diagnostic.line - 1, 0), lines.length - 1);
60
+ const from = Math.max(0, lineIndex - context);
61
+ const to = Math.min(lines.length - 1, lineIndex + context);
62
+ const gutter = String(to + 1).length;
63
+ const out = [];
64
+ for (let index = from; index <= to; index++) {
65
+ const text = lines[index] ?? "";
66
+ out.push(`${index === lineIndex ? ">" : " "} ${String(index + 1).padStart(gutter)} | ${text}`);
67
+ if (index !== lineIndex) continue;
68
+ const column = Math.max(diagnostic.character - 1, 0);
69
+ const span = Math.max(diagnostic.end - diagnostic.start, 1);
70
+ const width = Math.max(1, Math.min(span, Math.max(text.length - column, 1)));
71
+ out.push(` ${" ".repeat(gutter)} | ${" ".repeat(column)}${"^".repeat(width)}`);
72
+ }
73
+ return out.join("\n");
74
+ }
75
+ /**
76
+ * Project compiler diagnostics onto the adapter's error shape. Returns null
77
+ * for an empty diagnostics list: there is nothing to locate or render, and
78
+ * the caller keeps its own fallback rather than inventing a location.
79
+ */
80
+ function diagnosticPluginError(diagnostics, source, id) {
81
+ const first = diagnostics[0];
82
+ if (!first) return null;
83
+ const extra = diagnostics.length > 1 ? ` (+${diagnostics.length - 1} further diagnostic(s) in this module)` : "";
84
+ return {
85
+ id,
86
+ loc: {
87
+ file: first.file,
88
+ line: first.line,
89
+ column: first.character
90
+ },
91
+ frame: formatDiagnosticFrame(source, first),
92
+ message: `${first.file}:${first.line}:${first.character} - error ${first.code}: ${first.message}${extra}`,
93
+ diagnostics
94
+ };
95
+ }
96
+ //#endregion
97
+ export { CompilerDiagnosticError, diagnosticAt, diagnosticMessage, diagnosticPluginError, formatDiagnosticFrame };
@@ -0,0 +1,259 @@
1
+ import { SYNTHESIZED_COMPUTED_LOCAL } from "./lower-program.js";
2
+ import { isCompileTimeOnlyImport } from "./module-analysis.js";
3
+ import { SourceMapSegmentBuilder } from "./source-map.js";
4
+ import ts from "typescript";
5
+ import { COMPILED_MODULE_ABI_VERSION, PART_PROGRAM_VERSION } from "@openelement/protocol/part-program";
6
+ //#region src/internal/compiler/semantic-core/emit-module.ts
7
+ /**
8
+ * Generated-module emission for the compiled grammar (#1473 split): renders
9
+ * the compiled module text with
10
+ * verbatim copies, synthesized statics and forwarding handlers, each mapped
11
+ * through a real Source Map v3 segment.
12
+ */
13
+ /**
14
+ * Copy one source import statement into the generated module. Compile-time-
15
+ * only intrinsic bindings (element/property from '@openelement/element') are
16
+ * stripped: the decorators they powered are erased by compilation and the
17
+ * runtime package exports neither, so keeping them would emit an unresolvable
18
+ * runtime import. A statement whose entire clause stripped away is dropped.
19
+ */
20
+ function rewriteImportForGeneratedModule(sf, statement) {
21
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) return statement.getText(sf);
22
+ const module = statement.moduleSpecifier.text;
23
+ const clause = statement.importClause;
24
+ if (!clause) return statement.getText(sf);
25
+ const bindings = clause.namedBindings;
26
+ if (!bindings || !ts.isNamedImports(bindings)) return statement.getText(sf);
27
+ const kept = bindings.elements.filter((element) => !isCompileTimeOnlyImport(module, element.propertyName?.text ?? element.name.text));
28
+ if (kept.length === bindings.elements.length) return statement.getText(sf);
29
+ const parts = [];
30
+ if (clause.name) parts.push(clause.name.text);
31
+ if (kept.length > 0) {
32
+ const specifiers = kept.map((element) => `${element.isTypeOnly ? "type " : ""}${element.propertyName ? `${element.propertyName.text} as ` : ""}${element.name.text}`);
33
+ parts.push(`{ ${specifiers.join(", ")} }`);
34
+ }
35
+ if (parts.length === 0) return null;
36
+ return `import ${clause.isTypeOnly ? "type " : ""}${parts.join(", ")} from '${module}';`;
37
+ }
38
+ function encodeBase64(value) {
39
+ const bytes = new TextEncoder().encode(value);
40
+ let binary = "";
41
+ for (const byte of bytes) binary += String.fromCharCode(byte);
42
+ return btoa(binary);
43
+ }
44
+ function generatedHandlerText(handler) {
45
+ const action = handler.action;
46
+ if (action.kind === "method") return ` ${handler.name}(): void { this.${action.name}(); }`;
47
+ if (action.kind === "call") return ` ${handler.name}(): void { this.${action.name}(); }`;
48
+ if (action.kind === "increment") return ` ${handler.name}(): void { this.${action.signal}++; }`;
49
+ if (action.kind === "decrement") return ` ${handler.name}(): void { this.${action.signal}--; }`;
50
+ if (action.kind === "add") return ` ${handler.name}(): void { this.${action.signal} += ${action.value}; }`;
51
+ if (action.kind === "subtract") return ` ${handler.name}(): void { this.${action.signal} -= ${action.value}; }`;
52
+ if (action.kind === "assign") return ` ${handler.name}(): void { this.${action.signal} = ${JSON.stringify(action.value)}; }`;
53
+ return ` ${handler.name}(): void {}`;
54
+ }
55
+ /** Render the compiled module text and its inline Source Map v3. */
56
+ function emitCompiledModule(input) {
57
+ const { sf, source, fileName, analyzed, lowering, program, programJson, propertiesJson, metadataJson, observedJson } = input;
58
+ const { fields, methods, render, stylesText, stylesNode, stylesTypeText, passthroughStatements, decorator, classNode, tag, className, isDefaultExport, openElementLocalName, delegatesFocus, formAssociated } = analyzed;
59
+ const segments = new SourceMapSegmentBuilder();
60
+ const codeLines = [];
61
+ const nodePosition = (node) => {
62
+ const position = sf.getLineAndCharacterOfPosition(node.getStart(sf));
63
+ return {
64
+ line: position.line + 1,
65
+ column: position.character
66
+ };
67
+ };
68
+ const mapLineAt = (generatedLine, generatedColumn, node, name) => {
69
+ const position = nodePosition(node);
70
+ segments.add({
71
+ generatedLine,
72
+ generatedColumn,
73
+ sourceLine: position.line,
74
+ sourceColumn: position.column,
75
+ ...name === void 0 ? {} : { name }
76
+ });
77
+ };
78
+ /**
79
+ * Continuation lines of a verbatim-copied block: text line i is authored
80
+ * line (start + i) verbatim, so generated column (prefix + whitespace) maps
81
+ * to authored column (whitespace) — the first non-whitespace character.
82
+ */
83
+ const mapContinuationLines = (text, firstGeneratedLine, node, prefix) => {
84
+ const position = nodePosition(node);
85
+ const lines = text.split("\n");
86
+ for (let index = 1; index < lines.length; index++) {
87
+ const whitespace = /^\s*/.exec(lines[index])[0].length;
88
+ segments.add({
89
+ generatedLine: firstGeneratedLine + index,
90
+ generatedColumn: prefix + whitespace,
91
+ sourceLine: position.line + index,
92
+ sourceColumn: whitespace
93
+ });
94
+ }
95
+ };
96
+ /** Push a line or block: multiline text always splits so codeLines.length tracks emitted lines. */
97
+ const push = (text) => {
98
+ for (const line of text.split("\n")) codeLines.push(line);
99
+ };
100
+ /** Push a verbatim copy of a node's text (optionally line-prefixed). */
101
+ const pushVerbatim = (text, node, prefix = "", name) => {
102
+ const firstGeneratedLine = codeLines.length + 1;
103
+ push(text.split("\n").map((line) => prefix + line).join("\n"));
104
+ mapLineAt(firstGeneratedLine, prefix.length, node, name);
105
+ mapContinuationLines(text, firstGeneratedLine, node, prefix.length);
106
+ };
107
+ /** Push one synthesized line embedding a verbatim value, mapping both. */
108
+ const pushDerivedLine = (head, valueText, tail, nameNode, nameColumn, name, valueNode) => {
109
+ const generatedLine = codeLines.length + 1;
110
+ push(`${head}${valueText}${tail}`);
111
+ mapLineAt(generatedLine, nameColumn, nameNode, name);
112
+ if (valueNode !== void 0) {
113
+ mapLineAt(generatedLine, head.length, valueNode);
114
+ mapContinuationLines(valueText, generatedLine, valueNode, 0);
115
+ }
116
+ };
117
+ /** Push a synthesized block whose first line traces to `node`. */
118
+ const pushDerivedBlock = (text, node, name) => {
119
+ const firstGeneratedLine = codeLines.length + 1;
120
+ push(text);
121
+ mapLineAt(firstGeneratedLine, 0, node, name);
122
+ };
123
+ push(`// <auto-generated by open:compiled-element; part-program format ${PART_PROGRAM_VERSION} / module ABI ${COMPILED_MODULE_ABI_VERSION} - do not edit>`);
124
+ for (const statement of sf.statements) {
125
+ if (!ts.isImportDeclaration(statement)) continue;
126
+ const rewritten = rewriteImportForGeneratedModule(sf, statement);
127
+ if (rewritten !== null) pushVerbatim(rewritten, statement);
128
+ }
129
+ let readonlySignalLocal = null;
130
+ for (const statement of sf.statements) {
131
+ if (!ts.isImportDeclaration(statement)) continue;
132
+ if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "@openelement/element") continue;
133
+ const bindings = statement.importClause?.namedBindings;
134
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
135
+ for (const element of bindings.elements) if ((element.propertyName?.text ?? element.name.text) === "ReadonlySignal") readonlySignalLocal = element.name.text;
136
+ }
137
+ const needsComputedTypes = fields.some((field) => field.computed);
138
+ const signalType = readonlySignalLocal ?? "ReadonlySignal";
139
+ if (needsComputedTypes && readonlySignalLocal === null) push(`import type { ReadonlySignal } from '@openelement/element';`);
140
+ if (lowering.synthesizedFields.length > 0 && !lowering.sourceBindsComputed) push(`import { computed as ${SYNTHESIZED_COMPUTED_LOCAL} } from '@openelement/element';`);
141
+ push("");
142
+ for (const statement of passthroughStatements) pushVerbatim(statement.getText(sf), statement);
143
+ if (passthroughStatements.length > 0) push("");
144
+ const programStartLine = codeLines.length + 1;
145
+ pushDerivedBlock(`const __partProgram = ${programJson};`, render);
146
+ const programJsonPosition = (offset) => {
147
+ const before = programJson.slice(0, offset);
148
+ return {
149
+ line: programStartLine + before.split("\n").length - 1,
150
+ column: offset - (before.lastIndexOf("\n") + 1)
151
+ };
152
+ };
153
+ const tagOffset = programJson.indexOf(`"tag": ${JSON.stringify(tag)}`);
154
+ if (tagOffset >= 0) {
155
+ const at = programJsonPosition(tagOffset);
156
+ mapLineAt(at.line, at.column, decorator);
157
+ }
158
+ push("");
159
+ pushDerivedBlock(`const __compiledProperties = ${propertiesJson};`, classNode.name);
160
+ push("");
161
+ pushDerivedBlock(`const __elementMetadata = ${metadataJson};`, classNode.name);
162
+ push("");
163
+ pushDerivedBlock(`const __observedAttributes: string[] = ${observedJson};`, classNode.name);
164
+ push("");
165
+ pushDerivedBlock("const __compiledProps = {", classNode.name);
166
+ for (const field of fields) {
167
+ if (field.computed) {
168
+ const computedLine = codeLines.length + 1;
169
+ push(` ${field.name}: { type: Object, default: undefined, reflect: false, attribute: false },`);
170
+ mapLineAt(computedLine, 2, field.node.name, field.name);
171
+ continue;
172
+ }
173
+ const attribute = field.attribute === null ? "false" : JSON.stringify(field.attribute);
174
+ pushDerivedLine(` ${field.name}: { type: ${field.typeConstructor}, default: `, field.initializerText, `, reflect: ${field.reflect}, attribute: ${attribute} },`, field.node.name, 2, field.name, field.node.initializer);
175
+ }
176
+ push("};");
177
+ push("");
178
+ const classLine = `export ${isDefaultExport ? "default " : ""}class ${className} extends ${openElementLocalName} {`;
179
+ push(classLine);
180
+ mapLineAt(codeLines.length, classLine.indexOf(className), classNode.name, className);
181
+ push([
182
+ " static __partProgram: typeof __partProgram = __partProgram;",
183
+ " static __compiledProperties: typeof __compiledProperties = __compiledProperties;",
184
+ " static __elementMetadata: typeof __elementMetadata = __elementMetadata;",
185
+ " static props: typeof __compiledProps = __compiledProps;",
186
+ " static observedAttributes: typeof __observedAttributes = __observedAttributes;"
187
+ ].join("\n"));
188
+ if (delegatesFocus) push(" static override delegatesFocus: boolean = true;");
189
+ if (formAssociated) push(" static override formAssociated: boolean = true;");
190
+ const computedFields = fields.filter((field) => field.computed);
191
+ if (computedFields.length > 0) {
192
+ const plainFieldByName = new Map(fields.filter((field) => !field.computed).map((field) => [field.name, field]));
193
+ const signalValueType = (name) => {
194
+ const plain = plainFieldByName.get(name);
195
+ const annotated = plain?.typeText.replace(/^:\s*/, "").trim() ?? "";
196
+ if (annotated) return annotated;
197
+ switch (plain?.typeConstructor) {
198
+ case "String": return "string";
199
+ case "Number": return "number";
200
+ case "Boolean": return "boolean";
201
+ case "Array": return "unknown[]";
202
+ case "Object": return "Record<string, unknown>";
203
+ default: return "unknown";
204
+ }
205
+ };
206
+ const computedReturnType = (field) => {
207
+ return field.typeText.replace(/^:\s*/, "").trim() || `${signalType}<unknown>`;
208
+ };
209
+ push(" static __computedFields: {");
210
+ for (const field of computedFields) {
211
+ const params = field.computed.deps.map((dep) => `${dep}: ${signalType}<${signalValueType(dep)}>`).join(", ");
212
+ push(` ${field.name}: (__s: { ${params} }) => ${computedReturnType(field)};`);
213
+ }
214
+ push(" } = {");
215
+ for (const field of computedFields) {
216
+ const factoryLine = codeLines.length + 1;
217
+ push(` ${field.name}: ${field.computed.factoryText},`);
218
+ mapLineAt(factoryLine, 4, field.node.name, field.name);
219
+ mapLineAt(factoryLine, 4 + field.name.length + 2, field.node.initializer);
220
+ mapContinuationLines(field.computed.factoryText, factoryLine, field.computed.body, 0);
221
+ }
222
+ push(" };");
223
+ }
224
+ if (stylesText !== void 0 && stylesNode !== void 0) {
225
+ const stylesHead = ` static override styles${stylesTypeText ?? ""} = `;
226
+ const stylesLine = codeLines.length + 1;
227
+ push(`${stylesHead}${stylesText};`);
228
+ mapLineAt(stylesLine, stylesHead.length, stylesNode);
229
+ mapContinuationLines(stylesText, stylesLine, stylesNode, 0);
230
+ }
231
+ for (const field of fields) {
232
+ if (field.computed) continue;
233
+ const accessibility = field.accessibility ? `${field.accessibility} ` : "";
234
+ pushDerivedLine(` ${accessibility}${field.name}${field.typeText} = `, field.initializerText, ";", field.node.name, 2 + accessibility.length, field.name, field.node.initializer);
235
+ }
236
+ for (const method of methods) pushVerbatim(method.getText(sf), method, " ", method.name.text);
237
+ for (const handler of lowering.generatedHandlers) {
238
+ const handlerLine = codeLines.length + 1;
239
+ push(generatedHandlerText(handler));
240
+ mapLineAt(handlerLine, 2, handler.node);
241
+ }
242
+ push(" render(): never {");
243
+ mapLineAt(codeLines.length, 2, render, "render");
244
+ push(` throw new Error(
245
+ '[open:compiled-element] ${tag} is compiled to a Part Program; the runtime JSX render path is not available.',
246
+ );
247
+ }`);
248
+ push("}");
249
+ push("");
250
+ push("export { __partProgram, __elementMetadata };");
251
+ const map = segments.build(fileName, source, program.sourceMap);
252
+ push(`//# sourceMappingURL=data:application/json;base64,${encodeBase64(JSON.stringify(map))}`);
253
+ return {
254
+ code: codeLines.join("\n") + "\n",
255
+ map
256
+ };
257
+ }
258
+ //#endregion
259
+ export { emitCompiledModule };
@@ -0,0 +1,121 @@
1
+ import { CompiledElementError, sourceRange } from "./compiler-diagnostics.js";
2
+ import { validatePartProgram } from "@openelement/protocol/part-program";
3
+ //#region src/internal/compiler/semantic-core/emit-program.ts
4
+ /**
5
+ * Path-addressed fixed Parts can use DOM child indexes only before any dynamic
6
+ * anchor. An anchor expands to multiple DOM nodes, so accepting a fixed sink
7
+ * after one would make server output, fresh creation and claim address
8
+ * different nodes. The v1 location id remains the identity; this guard keeps
9
+ * the path retained for seed consumers safe until they consume that id.
10
+ */
11
+ function assertPathSafety(program) {
12
+ for (const part of program.parts) {
13
+ if (part.k === "text" || part.k === "when" || part.k === "each") continue;
14
+ let nodes = program.template;
15
+ for (const target of part.path) {
16
+ for (let sibling = 0; sibling < target; sibling++) if (nodes[sibling]?.k === "part") {
17
+ const source = program.sourceMap.records.find((record) => record.id === `p${part.index}`)?.source;
18
+ throw new CompiledElementError([{
19
+ code: "OEC9015",
20
+ message: `${part.k} part path [${part.path.join(",")}] is preceded by a dynamic anchor; path-addressed fixed sinks must appear before any dynamic anchor sibling`,
21
+ file: source?.file ?? program.sourceMap.file,
22
+ line: source?.start.line ?? 1,
23
+ character: source?.start.column ?? 1,
24
+ start: source?.start.offset ?? 0,
25
+ end: source?.end.offset ?? 0
26
+ }]);
27
+ }
28
+ const next = nodes[target];
29
+ nodes = next?.k === "el" ? next.children : [];
30
+ }
31
+ }
32
+ }
33
+ /** Assemble, path-check and validate the Part Program; derive the serialized payloads. */
34
+ function buildPartProgram(input) {
35
+ const { sf, fileName, analyzed, root, lowering } = input;
36
+ const { tag, className, fields, render, rootKind } = analyzed;
37
+ const metadata = {
38
+ tag,
39
+ className,
40
+ sourceFile: fileName,
41
+ properties: fields.map((field) => ({
42
+ name: field.name,
43
+ attribute: field.attribute,
44
+ type: field.type,
45
+ converter: field.converter,
46
+ reflect: field.reflect,
47
+ default: field.defaultValue,
48
+ ...field.computed ? {
49
+ computed: true,
50
+ deps: field.computed.deps
51
+ } : {}
52
+ })),
53
+ observedAttributes: fields.flatMap((field) => field.attribute === null ? [] : [field.attribute]),
54
+ cem: {
55
+ tagName: tag,
56
+ className,
57
+ declaration: {
58
+ name: className,
59
+ module: fileName
60
+ },
61
+ attributes: fields.flatMap((field) => field.attribute === null ? [] : [{
62
+ name: field.attribute,
63
+ fieldName: field.name,
64
+ type: field.type,
65
+ reflect: field.reflect
66
+ }]),
67
+ members: fields.map((field) => ({
68
+ name: field.name,
69
+ fieldName: field.name,
70
+ type: field.type,
71
+ attribute: field.attribute,
72
+ reflect: field.reflect
73
+ }))
74
+ }
75
+ };
76
+ const sourceRecords = [
77
+ {
78
+ id: "root",
79
+ kind: "root",
80
+ source: sourceRange(sf, render)
81
+ },
82
+ ...fields.map((field) => ({
83
+ id: `property:${field.name}`,
84
+ kind: "property",
85
+ source: sourceRange(sf, field.node)
86
+ })),
87
+ ...lowering.sourceRecords
88
+ ];
89
+ const program = {
90
+ version: 1,
91
+ tag,
92
+ root: {
93
+ id: "root",
94
+ kind: rootKind,
95
+ nodes: [root.id]
96
+ },
97
+ template: [root],
98
+ parts: lowering.parts,
99
+ regions: lowering.regions,
100
+ dependencies: lowering.dependencies,
101
+ locations: lowering.locations,
102
+ sourceMap: {
103
+ version: 1,
104
+ file: fileName,
105
+ records: sourceRecords
106
+ },
107
+ metadata
108
+ };
109
+ assertPathSafety(program);
110
+ validatePartProgram(program);
111
+ const { sourceMap: _provenance, ...wireProgram } = program;
112
+ return {
113
+ program,
114
+ programJson: JSON.stringify(wireProgram, null, 2),
115
+ propertiesJson: JSON.stringify(metadata.properties, null, 2),
116
+ metadataJson: JSON.stringify(metadata, null, 2),
117
+ observedJson: JSON.stringify(metadata.observedAttributes, null, 2)
118
+ };
119
+ }
120
+ //#endregion
121
+ export { buildPartProgram };