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

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 +48 -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,479 @@
1
+ import { admitStylesInitializer, collectSheetImports } from "./style-imports.js";
2
+ import ts from "typescript";
3
+ import { camelToKebab, isSafeAttributeName } from "@openelement/protocol/forbidden-sinks";
4
+ //#region src/internal/compiler/semantic-core/analyze-module.ts
5
+ /**
6
+ * Module/class-shape analysis for the compiled grammar (#1473 split): the
7
+ * admitted statement shapes,
8
+ * the one `@element` class with its decorator options and canonical heritage,
9
+ * and the `@property` field/method/render inventory the later lowering and
10
+ * emission stages consume.
11
+ */
12
+ /** The compiler face of the one canonical attribute-name predicate. */
13
+ function isSafeAttributeName$1(value) {
14
+ return isSafeAttributeName(value);
15
+ }
16
+ function unwrapExpression(expr) {
17
+ let current = expr;
18
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isTypeAssertionExpression(current)) current = current.expression;
19
+ return current;
20
+ }
21
+ /** Return a JSON-safe literal, or undefined when the expression is not literal. */
22
+ function literalValue(expr, sf) {
23
+ const value = unwrapExpression(expr);
24
+ if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) return value.text;
25
+ if (ts.isNumericLiteral(value)) {
26
+ const number = Number(value.text);
27
+ return Number.isFinite(number) ? number : void 0;
28
+ }
29
+ if (value.kind === ts.SyntaxKind.TrueKeyword) return true;
30
+ if (value.kind === ts.SyntaxKind.FalseKeyword) return false;
31
+ if (value.kind === ts.SyntaxKind.NullKeyword) return null;
32
+ if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken) {
33
+ if (!ts.isNumericLiteral(value.operand)) return void 0;
34
+ const number = -Number(value.operand.text);
35
+ return Number.isFinite(number) ? number : void 0;
36
+ }
37
+ if (ts.isArrayLiteralExpression(value)) {
38
+ const entries = [];
39
+ for (const element of value.elements) {
40
+ if (ts.isSpreadElement(element)) return void 0;
41
+ const entry = literalValue(element, sf);
42
+ if (entry === void 0) return void 0;
43
+ entries.push(entry);
44
+ }
45
+ return entries;
46
+ }
47
+ if (ts.isObjectLiteralExpression(value)) {
48
+ const object = {};
49
+ for (const property of value.properties) {
50
+ if (!ts.isPropertyAssignment(property)) return void 0;
51
+ const name = property.name;
52
+ const key = ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : void 0;
53
+ if (key === void 0 || key === "__proto__") return void 0;
54
+ const entry = literalValue(property.initializer, sf);
55
+ if (entry === void 0) return void 0;
56
+ object[key] = entry;
57
+ }
58
+ return object;
59
+ }
60
+ }
61
+ /**
62
+ * The one non-serializable field default admitted by the compiled grammar.
63
+ * The wrapper is the runtime capability; limiting the argument to a literal
64
+ * keeps compiled metadata deterministic and prevents arbitrary initializer
65
+ * execution from entering the property schema. Provenance (#1209): the callee
66
+ * must bind the canonical `trustedHtml` import; a same-name spelling bound to
67
+ * anything else fails closed (OEC9026) instead of being silently admitted.
68
+ */
69
+ function isTrustedHtmlInitializer(expr, intrinsics, fail) {
70
+ const value = unwrapExpression(expr);
71
+ if (!ts.isCallExpression(value)) return false;
72
+ const resolution = intrinsics.resolveIntrinsic(value.expression, "trustedHtml");
73
+ if (!resolution.canonical) {
74
+ if (resolution.unsupported || ts.isIdentifier(value.expression) && value.expression.text === "trustedHtml") fail(value, "OEC9026", "trustedHtml field defaults require the canonical trustedHtml import: a runtime named import of trustedHtml from '@openelement/element'" + (resolution.unsupported ? ` (${resolution.unsupported})` : ""));
75
+ return false;
76
+ }
77
+ if (value.arguments.length !== 1) return false;
78
+ const html = unwrapExpression(value.arguments[0]);
79
+ return ts.isStringLiteral(html) || ts.isNoSubstitutionTemplateLiteral(html);
80
+ }
81
+ function primitiveText(value) {
82
+ if (value === null) return "";
83
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
84
+ return null;
85
+ }
86
+ function propertyTypeFromConstructor(expr, sf, node, fail) {
87
+ const name = expr.getText(sf);
88
+ if (name !== "String" && name !== "Number" && name !== "Boolean" && name !== "Array" && name !== "Object") return fail(node, "OEC9021", "property type/converter must be one of String, Number, Boolean, Array or Object");
89
+ return {
90
+ label: name.toLowerCase(),
91
+ constructorName: name
92
+ };
93
+ }
94
+ const COMPUTED_FIELD_SUBJECTS = {
95
+ actor: "computed field arrows",
96
+ single: "computed field",
97
+ plural: "computed fields"
98
+ };
99
+ /**
100
+ * Validate one computed-body expression and derive its factory text (#1556
101
+ * split of parseComputedInitializer). The body may read `this.<field>` of any
102
+ * NON-computed declared field (rewritten to the signal-record read) and use
103
+ * any module-scope values; `this` in any other position, reads of computed
104
+ * fields, and nested non-arrow functions fail closed (OEC9024). Returns the
105
+ * source-signal dependency list (declaration order) and the body text with
106
+ * every `this.<field>` read rewritten to `__s.<field>.value`.
107
+ */
108
+ function validateComputedExpressionBody(body, sf, plainFieldNames, computedFieldNames, fail, subjects = COMPUTED_FIELD_SUBJECTS) {
109
+ const deps = [];
110
+ const replacements = [];
111
+ const visit = (node) => {
112
+ if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) fail(node, "OEC9024", `${subjects.actor} may not nest non-arrow functions`);
113
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword) {
114
+ const name = node.name.text;
115
+ if (computedFieldNames.has(name)) fail(node, "OEC9024", `${subjects.single} may not read computed field "${name}"`);
116
+ if (!plainFieldNames.has(name)) fail(node, "OEC9024", `${subjects.plural} may only read this.<declared property> (found this.${name})`);
117
+ if (!deps.includes(name)) deps.push(name);
118
+ replacements.push({
119
+ start: node.getStart(sf),
120
+ end: node.getEnd(),
121
+ name
122
+ });
123
+ return;
124
+ }
125
+ if (node.kind === ts.SyntaxKind.ThisKeyword || node.kind === ts.SyntaxKind.SuperKeyword) fail(node, "OEC9024", `${subjects.actor} may only reference this.<property>`);
126
+ ts.forEachChild(node, visit);
127
+ };
128
+ visit(body);
129
+ let bodyText = body.getText(sf);
130
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
131
+ const offset = body.getStart(sf);
132
+ bodyText = bodyText.slice(0, replacement.start - offset) + `__s.${replacement.name}.value` + bodyText.slice(replacement.end - offset);
133
+ }
134
+ return {
135
+ deps,
136
+ bodyText
137
+ };
138
+ }
139
+ /**
140
+ * Parse a computed field initializer (alpha.8): `computed(() => ...)`
141
+ * behind optional `as`-casts, where the callee binds the canonical `computed`
142
+ * import (#1209 — a same-name spelling bound to anything else fails closed
143
+ * with OEC9025). The arrow body may read `this.<field>` of any NON-computed
144
+ * declared field (rewritten to the signal-record read) and use any
145
+ * module-scope values; `this` in any other position, reads of computed
146
+ * fields, and nested non-arrow functions fail closed (OEC9024). Returns null
147
+ * for non-computed initializers.
148
+ */
149
+ function parseComputedInitializer(initializer, sf, intrinsics, plainFieldNames, computedFieldNames, fail) {
150
+ const value = unwrapExpression(initializer);
151
+ if (!ts.isCallExpression(value)) return null;
152
+ const resolution = intrinsics.resolveIntrinsic(value.expression, "computed");
153
+ if (!resolution.canonical) {
154
+ if (resolution.unsupported || ts.isIdentifier(value.expression) && value.expression.text === "computed") fail(value, "OEC9025", "computed fields require the canonical computed import: a runtime named import of computed from '@openelement/element'" + (resolution.unsupported ? ` (${resolution.unsupported})` : ""));
155
+ return null;
156
+ }
157
+ if (value.arguments.length !== 1 || !ts.isArrowFunction(value.arguments[0])) fail(value, "OEC9024", "computed fields take exactly one zero-argument arrow function");
158
+ const arrow = value.arguments[0];
159
+ if (arrow.parameters.length > 0) fail(arrow, "OEC9024", "computed field arrows may not declare parameters");
160
+ if (!ts.isBlock(arrow.body)) {} else if (arrow.body.statements.length === 1 && ts.isReturnStatement(arrow.body.statements[0]) && arrow.body.statements[0].expression) fail(arrow.body, "OEC9024", "computed field arrows use an expression body, not a block (keep derived values atomic)");
161
+ else fail(arrow.body, "OEC9024", "computed field arrows use an expression body, not a block");
162
+ const body = arrow.body;
163
+ const { deps, bodyText } = validateComputedExpressionBody(body, sf, plainFieldNames, computedFieldNames, fail);
164
+ return {
165
+ deps,
166
+ factoryText: `(__s) => ${resolution.localName}(() => ${bodyText})`,
167
+ body
168
+ };
169
+ }
170
+ function inferPropertyType(member, defaultValue, sf) {
171
+ const typeText = member.type?.getText(sf).replace(/[\s?]/g, "") ?? "";
172
+ if (typeText === "string" || typeText === "String") return {
173
+ label: "string",
174
+ constructorName: "String"
175
+ };
176
+ if (typeText === "number" || typeText === "Number") return {
177
+ label: "number",
178
+ constructorName: "Number"
179
+ };
180
+ if (typeText === "boolean" || typeText === "Boolean") return {
181
+ label: "boolean",
182
+ constructorName: "Boolean"
183
+ };
184
+ if (/^(Array|ReadonlyArray|Set)</.test(typeText) || typeText.endsWith("[]")) return {
185
+ label: "array",
186
+ constructorName: "Array"
187
+ };
188
+ if (/^(Record|Map|Object)</.test(typeText)) return {
189
+ label: "object",
190
+ constructorName: "Object"
191
+ };
192
+ if (Array.isArray(defaultValue)) return {
193
+ label: "array",
194
+ constructorName: "Array"
195
+ };
196
+ if (defaultValue !== null && typeof defaultValue === "object") return {
197
+ label: "object",
198
+ constructorName: "Object"
199
+ };
200
+ if (typeof defaultValue === "number") return {
201
+ label: "number",
202
+ constructorName: "Number"
203
+ };
204
+ if (typeof defaultValue === "boolean") return {
205
+ label: "boolean",
206
+ constructorName: "Boolean"
207
+ };
208
+ return {
209
+ label: "string",
210
+ constructorName: "String"
211
+ };
212
+ }
213
+ function propertyFields(sf, classNode, intrinsics, fail) {
214
+ const fields = [];
215
+ const methods = [];
216
+ let render = null;
217
+ let stylesText;
218
+ let stylesNode;
219
+ let stylesTypeText;
220
+ const names = /* @__PURE__ */ new Set();
221
+ const propertyAttributeNames = /* @__PURE__ */ new Set();
222
+ for (const member of classNode.members) {
223
+ if (ts.isPropertyDeclaration(member)) {
224
+ const modifiers = ts.getModifiers(member) ?? [];
225
+ if (modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword) && ts.isIdentifier(member.name) && member.name.text === "styles" && (ts.getDecorators(member) ?? []).length === 0) {
226
+ if (!member.initializer) fail(member, "OEC9005", "static styles requires an initializer");
227
+ if (stylesText !== void 0) fail(member, "OEC9005", "compiled classes may declare static styles only once");
228
+ stylesText = member.initializer.getText(sf);
229
+ stylesNode = member.initializer;
230
+ stylesTypeText = member.type ? `: ${member.type.getText(sf)}` : void 0;
231
+ continue;
232
+ }
233
+ const accessibilityModifiers = modifiers.filter((modifier) => modifier.kind === ts.SyntaxKind.PublicKeyword || modifier.kind === ts.SyntaxKind.ProtectedKeyword || modifier.kind === ts.SyntaxKind.PrivateKeyword);
234
+ if (modifiers.some((modifier) => modifier.kind !== ts.SyntaxKind.PublicKeyword && modifier.kind !== ts.SyntaxKind.ProtectedKeyword && modifier.kind !== ts.SyntaxKind.PrivateKeyword) || accessibilityModifiers.length > 1 || member.questionToken || member.exclamationToken) fail(member, "OEC9005", "compiled @property fields must be ordinary initialized instance fields");
235
+ const decorators = ts.getDecorators(member) ?? [];
236
+ if (decorators.length !== 1) fail(member, "OEC9005", "compiled fields must carry exactly one @property decorator");
237
+ const decorator = decorators[0];
238
+ const call = decorator.expression;
239
+ if (!ts.isCallExpression(call)) fail(decorator, "OEC9004", "unknown decorator on an OpenElement member; use only @property");
240
+ const decoratorResolution = intrinsics.resolveIntrinsic(call.expression, "property");
241
+ if (!decoratorResolution.canonical) {
242
+ if (decoratorResolution.unsupported) fail(decorator, "OEC9027", `unsupported @property provenance: ${decoratorResolution.unsupported}`);
243
+ fail(decorator, "OEC9004", "unknown decorator on an OpenElement member; use only @property imported from '@openelement/element'");
244
+ }
245
+ if (!ts.isIdentifier(member.name)) fail(member, "OEC9005", "property names must be identifiers");
246
+ if (names.has(member.name.text)) fail(member, "OEC9005", `duplicate property "${member.name.text}"`);
247
+ names.add(member.name.text);
248
+ if (!member.initializer) fail(member, "OEC9005", "compiled fields require a literal initializer");
249
+ const computedFieldNames = new Set(fields.filter((f) => f.computed).map((f) => f.name));
250
+ const computedInit = parseComputedInitializer(member.initializer, sf, intrinsics, new Set(fields.filter((f) => !f.computed).map((f) => f.name)), computedFieldNames, fail);
251
+ const trustedHtmlInit = !computedInit && isTrustedHtmlInitializer(member.initializer, intrinsics, fail);
252
+ const defaultValue = computedInit || trustedHtmlInit ? null : literalValue(member.initializer, sf);
253
+ if (defaultValue === void 0) fail(member.initializer, "OEC9020", "property defaults must be serializable literals");
254
+ const options = call.arguments.length === 1 ? call.arguments[0] : void 0;
255
+ if (!options || !ts.isObjectLiteralExpression(options)) fail(decorator, "OEC9005", "@property requires one options object literal");
256
+ let reflect = false;
257
+ let attribute;
258
+ let explicitType;
259
+ let explicitConverter;
260
+ const optionNames = /* @__PURE__ */ new Set();
261
+ for (const entry of options.properties) {
262
+ if (!ts.isPropertyAssignment(entry) || entry.name.getText(sf).length === 0) fail(entry, "OEC9022", "@property options must be named literal assignments");
263
+ const optionName = entry.name.getText(sf);
264
+ if (optionNames.has(optionName)) fail(entry, "OEC9022", `@property option "${optionName}" may appear only once`);
265
+ optionNames.add(optionName);
266
+ if (optionName === "reflect") {
267
+ if (entry.initializer.kind !== ts.SyntaxKind.TrueKeyword && entry.initializer.kind !== ts.SyntaxKind.FalseKeyword) fail(entry, "OEC9005", "@property reflect must be a boolean literal");
268
+ reflect = entry.initializer.kind === ts.SyntaxKind.TrueKeyword;
269
+ continue;
270
+ }
271
+ if (optionName === "attribute") {
272
+ if (entry.initializer.kind === ts.SyntaxKind.FalseKeyword) attribute = null;
273
+ else if (ts.isStringLiteral(entry.initializer)) {
274
+ attribute = camelToKebab(entry.initializer.text);
275
+ if (!isSafeAttributeName$1(attribute)) fail(entry, "OEC9023", "property attribute name is unsafe");
276
+ } else fail(entry, "OEC9023", "property attribute must be a string literal or false");
277
+ continue;
278
+ }
279
+ if (optionName === "type" || optionName === "converter") {
280
+ const type = propertyTypeFromConstructor(entry.initializer, sf, entry, fail);
281
+ if (optionName === "type") explicitType = type;
282
+ else explicitConverter = type.label;
283
+ continue;
284
+ }
285
+ fail(entry, "OEC9022", `unsupported @property option "${optionName}"`);
286
+ }
287
+ const inferred = explicitType ?? inferPropertyType(member, defaultValue, sf);
288
+ const converter = explicitConverter ?? inferred.label;
289
+ if (attribute === void 0) attribute = camelToKebab(member.name.text);
290
+ if (trustedHtmlInit) {
291
+ if (inferred.label !== "object" || attribute !== null || reflect) fail(member, "OEC9026", "trustedHtml field defaults require type: Object, reflect: false, and attribute: false");
292
+ }
293
+ if (computedInit) {
294
+ if (attribute !== null || reflect) fail(member, "OEC9025", "computed fields require @property({ reflect: false, attribute: false }) — derived signals have no attribute channel");
295
+ }
296
+ if (attribute !== null) {
297
+ const attributeKey = attribute.toLowerCase();
298
+ if (propertyAttributeNames.has(attributeKey)) fail(member, "OEC9023", `duplicate property attribute "${attribute}"`);
299
+ propertyAttributeNames.add(attributeKey);
300
+ }
301
+ if (attribute === null && reflect) fail(member, "OEC9023", "a property with attribute: false cannot reflect");
302
+ fields.push({
303
+ name: member.name.text,
304
+ reflect,
305
+ attribute,
306
+ type: inferred.label,
307
+ converter,
308
+ typeConstructor: inferred.constructorName,
309
+ accessibility: accessibilityModifiers.length === 0 ? "" : accessibilityModifiers[0].kind === ts.SyntaxKind.PublicKeyword ? "public" : accessibilityModifiers[0].kind === ts.SyntaxKind.ProtectedKeyword ? "protected" : "private",
310
+ typeText: member.type ? `: ${member.type.getText(sf)}` : "",
311
+ initializerText: member.initializer.getText(sf),
312
+ defaultValue,
313
+ node: member,
314
+ ...computedInit ? { computed: computedInit } : {}
315
+ });
316
+ continue;
317
+ }
318
+ if (ts.isMethodDeclaration(member)) {
319
+ const modifiers = ts.getModifiers(member) ?? [];
320
+ if (modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword || modifier.kind === ts.SyntaxKind.AbstractKeyword || modifier.kind === ts.SyntaxKind.DeclareKeyword || modifier.kind === ts.SyntaxKind.AccessorKeyword) || !member.body) fail(member, "OEC9006", "compiled methods must be concrete instance methods");
321
+ if ((ts.getDecorators(member) ?? []).length > 0) fail(member, "OEC9004", "methods may not carry decorators in the compiler grammar");
322
+ if (member.parameters.some((parameter) => (ts.getDecorators(parameter) ?? []).length > 0)) fail(member, "OEC9004", "method parameters may not carry decorators in the compiler grammar");
323
+ if (!ts.isIdentifier(member.name)) fail(member, "OEC9006", "method names must be identifiers");
324
+ if (member.name.text === "render") {
325
+ if (render) fail(member, "OEC9007", "compiled classes may declare only one render() method");
326
+ if (member.parameters.length !== 0 || modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) fail(member, "OEC9007", "render() must be a synchronous zero-argument method");
327
+ render = member;
328
+ } else methods.push(member);
329
+ continue;
330
+ }
331
+ fail(member, "OEC9006", "constructors, accessors and undecorated fields are outside the compiler grammar");
332
+ }
333
+ if (!render) fail(classNode, "OEC9007", "compiled classes must declare render()");
334
+ return {
335
+ fields,
336
+ methods,
337
+ render,
338
+ stylesText,
339
+ stylesNode,
340
+ stylesTypeText
341
+ };
342
+ }
343
+ function isDeclareStatement(statement) {
344
+ return ts.canHaveModifiers(statement) && (ts.getModifiers(statement) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword);
345
+ }
346
+ /**
347
+ * The one extra runtime statement a compiled module may carry: the island
348
+ * delivery policy colocated with the class
349
+ * (`export const openElement = defineIslandConfig({ ... })`). The callee must
350
+ * bind a static-sidecar descriptor the host injected through the compile
351
+ * options (#1209); the default core knows none, so an unconfigured compiler
352
+ * rejects the statement as OEC9008. A same-name spelling bound to anything
353
+ * else is not the policy statement and falls through to the same rejection.
354
+ * The statement is validated here and copied verbatim into the generated
355
+ * module; the runtime factory validates the descriptor itself at module
356
+ * evaluation. Anything else stays outside the compiled module grammar
357
+ * (OEC9008).
358
+ */
359
+ function isIslandConfigStatement(statement, intrinsics) {
360
+ if (!ts.isVariableStatement(statement)) return false;
361
+ const modifiers = ts.getModifiers(statement) ?? [];
362
+ if (modifiers.length !== 1 || modifiers[0].kind !== ts.SyntaxKind.ExportKeyword) return false;
363
+ const declarations = statement.declarationList.declarations;
364
+ if (declarations.length !== 1) return false;
365
+ const declaration = declarations[0];
366
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== "openElement") return false;
367
+ const initializer = declaration.initializer;
368
+ if (!initializer || !ts.isCallExpression(initializer)) return false;
369
+ if (!intrinsics.isStaticSidecarCallee(initializer.expression)) return false;
370
+ if (initializer.arguments.length !== 1 || !ts.isObjectLiteralExpression(initializer.arguments[0])) return false;
371
+ return true;
372
+ }
373
+ /**
374
+ * Admit one parsed module to the compiled grammar and lift its shape
375
+ * (#1473 split): the top-level
376
+ * statement admission (OEC9008 fail-closed, island policy passthrough), the
377
+ * exactly-one-`@element`-class rule with its decorator options and canonical
378
+ * heritage provenance, and the {@link propertyFields} inventory. Component
379
+ * styles are admitted in one form only (#1558): `.css` file imports arrayed
380
+ * in `static styles` — any inline sheet shape fails closed with OEC9029.
381
+ */
382
+ function analyzeCompiledModule(sf, intrinsics, fail) {
383
+ const sheetImports = collectSheetImports(sf, fail);
384
+ const passthroughStatements = [];
385
+ for (const statement of sf.statements) {
386
+ if (ts.isImportDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isModuleDeclaration(statement) || isDeclareStatement(statement)) continue;
387
+ if (isIslandConfigStatement(statement, intrinsics)) {
388
+ passthroughStatements.push(statement);
389
+ continue;
390
+ }
391
+ fail(statement, "OEC9008", "runtime top-level statements are outside the compiled module grammar");
392
+ }
393
+ const classes = sf.statements.filter(ts.isClassDeclaration);
394
+ const decorated = classes.filter((node) => (ts.getDecorators(node) ?? []).some((decorator) => {
395
+ const expr = decorator.expression;
396
+ return ts.isCallExpression(expr) && intrinsics.resolveIntrinsic(expr.expression, "element").canonical;
397
+ }));
398
+ if (classes.length !== 1 || decorated.length !== 1) {
399
+ for (const node of classes) for (const decorator of ts.getDecorators(node) ?? []) {
400
+ const expr = decorator.expression;
401
+ if (!ts.isCallExpression(expr)) continue;
402
+ const resolution = intrinsics.resolveIntrinsic(expr.expression, "element");
403
+ if (resolution.unsupported) fail(decorator, "OEC9027", `unsupported @element provenance: ${resolution.unsupported}`);
404
+ }
405
+ fail(sf, "OEC9001", "expected exactly one @element(...) class per compiled module (the decorator must bind the canonical element import from '@openelement/element')");
406
+ }
407
+ const classNode = decorated[0];
408
+ const classDecorators = ts.getDecorators(classNode) ?? [];
409
+ if (classDecorators.length !== 1) fail(classNode, "OEC9004", "compiled OpenElement classes must carry exactly one @element decorator");
410
+ const classModifiers = ts.getModifiers(classNode) ?? [];
411
+ const isDefaultExport = classModifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
412
+ if (!(isDefaultExport ? classModifiers.length === 2 && classModifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) : classModifiers.length === 1 && classModifiers[0].kind === ts.SyntaxKind.ExportKeyword)) fail(classNode, "OEC9006", "compiled @element classes must be exported (optionally as the default export) without other class modifiers");
413
+ let tag = "";
414
+ const decorator = classDecorators[0];
415
+ const expr = decorator.expression;
416
+ if (!ts.isCallExpression(expr) || !intrinsics.resolveIntrinsic(expr.expression, "element").canonical) fail(decorator, "OEC9004", "unknown decorator on an OpenElement class; use only @element");
417
+ if (expr.arguments.length < 1 || expr.arguments.length > 2 || !ts.isStringLiteral(expr.arguments[0])) fail(decorator, "OEC9002", "@element requires a string tag name plus an optional options object");
418
+ tag = expr.arguments[0].text;
419
+ if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(tag)) fail(decorator, "OEC9002", `@element tag "${tag}" is not a custom-element name`);
420
+ let rootKind = "light";
421
+ let delegatesFocus = false;
422
+ let formAssociated = false;
423
+ if (expr.arguments.length === 2) {
424
+ const options = expr.arguments[1];
425
+ if (!ts.isObjectLiteralExpression(options)) fail(decorator, "OEC9002", "@element options must be an object literal");
426
+ const seenOptions = /* @__PURE__ */ new Set();
427
+ for (const entry of options.properties) {
428
+ if (!ts.isPropertyAssignment(entry)) fail(entry, "OEC9002", "@element options must be named literal assignments");
429
+ const optionName = entry.name.getText(sf);
430
+ if (seenOptions.has(optionName)) fail(entry, "OEC9002", `@element option "${optionName}" may appear only once`);
431
+ seenOptions.add(optionName);
432
+ if (optionName === "root") {
433
+ if (!ts.isStringLiteral(entry.initializer)) fail(entry, "OEC9002", "@element root must be a string literal");
434
+ const mode = entry.initializer.text;
435
+ if (mode !== "light" && mode !== "shadow-open" && mode !== "shadow-closed") fail(entry, "OEC9002", `@element root "${mode}" is unsupported; use "light", "shadow-open" or "shadow-closed"`);
436
+ rootKind = mode;
437
+ continue;
438
+ }
439
+ if (optionName === "delegatesFocus" || optionName === "formAssociated") {
440
+ if (entry.initializer.kind !== ts.SyntaxKind.TrueKeyword && entry.initializer.kind !== ts.SyntaxKind.FalseKeyword) fail(entry, "OEC9002", `@element ${optionName} must be a boolean literal`);
441
+ const value = entry.initializer.kind === ts.SyntaxKind.TrueKeyword;
442
+ if (optionName === "delegatesFocus") delegatesFocus = value;
443
+ else formAssociated = value;
444
+ continue;
445
+ }
446
+ fail(entry, "OEC9002", "@element options support only root, delegatesFocus and formAssociated");
447
+ }
448
+ }
449
+ const heritage = classNode.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);
450
+ const heritageExpression = heritage?.types.length === 1 ? unwrapExpression(heritage.types[0].expression) : void 0;
451
+ const heritageResolution = heritageExpression ? intrinsics.resolveIntrinsic(heritageExpression, "OpenElement") : void 0;
452
+ if (!heritageResolution?.canonical) fail(classNode.name ?? classNode, "OEC9003", `compiled classes must extend the canonical OpenElement import from '@openelement/element' (found ${heritage?.types[0]?.expression.getText(sf) ?? "no base class"}` + (heritageResolution?.unsupported ? `; ${heritageResolution.unsupported}` : "") + ")");
453
+ const openElementLocalName = heritageResolution.localName;
454
+ if (!classNode.name) fail(classNode, "OEC9003", "compiled classes must be named");
455
+ const className = classNode.name.text;
456
+ const { fields, methods, render, stylesText, stylesNode, stylesTypeText } = propertyFields(sf, classNode, intrinsics, fail);
457
+ const styleRequests = admitStylesInitializer(stylesNode, sheetImports, sf, fail);
458
+ return {
459
+ passthroughStatements,
460
+ classNode,
461
+ decorator,
462
+ tag,
463
+ rootKind,
464
+ delegatesFocus,
465
+ formAssociated,
466
+ isDefaultExport,
467
+ openElementLocalName,
468
+ className,
469
+ fields,
470
+ methods,
471
+ render,
472
+ stylesText,
473
+ stylesNode,
474
+ stylesTypeText,
475
+ styleRequests
476
+ };
477
+ }
478
+ //#endregion
479
+ export { analyzeCompiledModule, isSafeAttributeName$1 as isSafeAttributeName, literalValue, primitiveText, unwrapExpression, validateComputedExpressionBody };
@@ -0,0 +1,39 @@
1
+ import { SemanticCoreOptions } from "./module-analysis.js";
2
+ import { CompiledElementSourceMap } from "./source-map.js";
3
+ import { CompiledElementError, ElementCompilerDiagnostic } from "./compiler-diagnostics.js";
4
+ import { PartProgramV1 } from "@openelement/protocol/part-program";
5
+ //#region src/internal/compiler/semantic-core/compile.d.ts
6
+ /**
7
+ * The compiled module the transform emits for one authored TSX source: the
8
+ * generated `code`, its Source Map v3, the Part Program facts the runtime
9
+ * consumes, and the ordered diagnostics that did not fail the compile.
10
+ */
11
+ export interface CompileElementResult {
12
+ code: string;
13
+ /**
14
+ * Real Source Map v3 for the emitted module (VLQ line+column segments
15
+ * derived from the compiler's span records and emission provenance). The
16
+ * same map is embedded as the module's inline map; the Vite shell returns it
17
+ * as its `map` output for downstream composition (#1210).
18
+ */
19
+ map: CompiledElementSourceMap;
20
+ program: PartProgramV1;
21
+ /**
22
+ * The module's style edges (#1558): the authored `.css` specifiers the
23
+ * class's `static styles` arrays, in authored order. The host build's
24
+ * style-asset plugin intercepts these edges — a build with no intercepting
25
+ * plugin fails at import resolution, never by silently inlining.
26
+ */
27
+ styleRequests?: readonly string[];
28
+ }
29
+ /**
30
+ * Compile one authored TSX module into the compiled Part Program module.
31
+ * `fileName` is used for diagnostics and the emitted source map only —
32
+ * filesystem resolution is the caller's job. Fails closed with a
33
+ * {@link CompiledElementError} carrying the ordered OEC diagnostics.
34
+ * `options.staticSidecars` admits host-declared sidecar policy statements
35
+ * (e.g. an island delivery descriptor); the default core admits none.
36
+ */
37
+ export declare function compileElementProgram(source: string, fileName: string, options?: SemanticCoreOptions): CompileElementResult;
38
+ //#endregion
39
+ export { CompiledElementError, type ElementCompilerDiagnostic };
@@ -0,0 +1,98 @@
1
+ import { analyzeCompiledModule } from "./analyze-module.js";
2
+ import { CompiledElementError, failAt, parseDiagnostic } from "./compiler-diagnostics.js";
3
+ import { buildPartProgram } from "./emit-program.js";
4
+ import { Lowering } from "./lower-program.js";
5
+ import { createModuleIntrinsicBindings } from "./module-analysis.js";
6
+ import { emitCompiledModule } from "./emit-module.js";
7
+ import { typescriptParser } from "./parse-module.js";
8
+ import ts from "typescript";
9
+ //#region src/internal/compiler/semantic-core/compile.ts
10
+ /**
11
+ * @openelement/element — TSX-to-Part Program v1 compiler (#1161–#1163).
12
+ *
13
+ * The compiler accepts one deliberately bounded authoring grammar. It lowers
14
+ * every accepted dynamic expression to a typed fixed Part or Region with a
15
+ * stable compiler-owned location. Anything outside that grammar produces a
16
+ * source-located diagnostic; no runtime discovery or fallback renderer is
17
+ * emitted.
18
+ *
19
+ * Single-duty pipeline modules behind this facade (#1473): parse-module.ts
20
+ * (the one TypeScript parse seam), analyze-module.ts (module/class shape),
21
+ * lower-program.ts (JSX → Program tree), emit-program.ts (Part Program
22
+ * assembly + validation), emit-module.ts (generated module text + Source Map
23
+ * v3), compiler-diagnostics.ts (error dialect + source locations). This file
24
+ * stays the internal entry: it wires the stages in order and re-exports the
25
+ * boundary types the Vite plugin and the compiler tests import.
26
+ */
27
+ /**
28
+ * The authored module's canonical `computed` local binding (aliases
29
+ * followed), or null when the module never binds it. Synthesized
30
+ * conditional-class factories (#1556) reference the authored binding when it
31
+ * exists; otherwise the emitter adds a module-local import under the
32
+ * synthesized name. Same resolution discipline as the ReadonlySignal scan in
33
+ * the emitter: the canonical specifier is fixed because computed factories
34
+ * already require it.
35
+ */
36
+ function canonicalComputedLocal(sf, intrinsics) {
37
+ for (const statement of sf.statements) {
38
+ if (!ts.isImportDeclaration(statement)) continue;
39
+ if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "@openelement/element") continue;
40
+ const bindings = statement.importClause?.namedBindings;
41
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
42
+ for (const element of bindings.elements) if (intrinsics.isRuntimeNamedImport(element.name.text, "@openelement/element", "computed")) return element.name.text;
43
+ }
44
+ return null;
45
+ }
46
+ /**
47
+ * Compile one authored TSX module into the compiled Part Program module.
48
+ * `fileName` is used for diagnostics and the emitted source map only —
49
+ * filesystem resolution is the caller's job. Fails closed with a
50
+ * {@link CompiledElementError} carrying the ordered OEC diagnostics.
51
+ * `options.staticSidecars` admits host-declared sidecar policy statements
52
+ * (e.g. an island delivery descriptor); the default core admits none.
53
+ */
54
+ function compileElementProgram(source, fileName, options = {}) {
55
+ const parsed = typescriptParser.parseModule(source, fileName);
56
+ const sf = parsed.sourceFile;
57
+ const syntaxDiagnostics = parsed.syntaxDiagnostics;
58
+ if (syntaxDiagnostics.length > 0) throw new CompiledElementError([parseDiagnostic(sf, syntaxDiagnostics[0])]);
59
+ const fail = failAt(sf);
60
+ const intrinsics = createModuleIntrinsicBindings(sf, options);
61
+ const analyzed = analyzeCompiledModule(sf, intrinsics, fail);
62
+ const methodNames = analyzed.methods.map((method) => method.name.text);
63
+ const lowering = new Lowering(sf, analyzed.fields, methodNames, { computedLocal: canonicalComputedLocal(sf, intrinsics) });
64
+ const renderStatements = analyzed.render.body?.statements ?? [];
65
+ if (renderStatements.length !== 1 || !ts.isReturnStatement(renderStatements[0]) || !renderStatements[0].expression) fail(analyzed.render, "OEC9007", "render() must be a single return of one JSX element");
66
+ const returned = renderStatements[0];
67
+ const root = lowering.lowerRoot(returned.expression);
68
+ if (root.k !== "el") fail(analyzed.render, "OEC9007", "render() must return one intrinsic JSX element");
69
+ analyzed.fields.push(...lowering.synthesizedFields);
70
+ const { program, programJson, propertiesJson, metadataJson, observedJson } = buildPartProgram({
71
+ sf,
72
+ fileName,
73
+ analyzed,
74
+ root,
75
+ lowering
76
+ });
77
+ const { code, map } = emitCompiledModule({
78
+ sf,
79
+ source,
80
+ fileName,
81
+ analyzed,
82
+ lowering,
83
+ program,
84
+ programJson,
85
+ propertiesJson,
86
+ metadataJson,
87
+ observedJson
88
+ });
89
+ const { styleRequests } = analyzed;
90
+ return {
91
+ code,
92
+ map,
93
+ program,
94
+ ...styleRequests.length === 0 ? {} : { styleRequests }
95
+ };
96
+ }
97
+ //#endregion
98
+ export { CompiledElementError, compileElementProgram };
@@ -0,0 +1,31 @@
1
+ import { CompilerDiagnostic, CompilerDiagnosticError } from "./diagnostics/index.js";
2
+ import ts from "typescript";
3
+ //#region src/internal/compiler/semantic-core/compiler-diagnostics.d.ts
4
+ /** A source-aware compiler diagnostic: stable OEC code, message and source range. */
5
+ export interface ElementCompilerDiagnostic extends CompilerDiagnostic {}
6
+ /** Error shape consumed by the Vite plugin and compiler tests. */
7
+ export declare class CompiledElementError extends CompilerDiagnosticError {
8
+ constructor(diagnostics: ElementCompilerDiagnostic[]);
9
+ }
10
+ /**
11
+ * The fail closure every compiler stage takes: locate `node` in the parsed
12
+ * module's source file and fail closed with one source-located OEC diagnostic.
13
+ */
14
+ export type CompilerFail = (node: ts.Node, code: string, message: string) => never;
15
+ /** Build the fail closure for one parsed module source file. */
16
+ declare function failAt(sf: ts.SourceFile): CompilerFail;
17
+ declare function sourceRange(sf: ts.SourceFile, node: ts.Node): {
18
+ file: string;
19
+ start: {
20
+ offset: number;
21
+ line: number;
22
+ column: number;
23
+ };
24
+ end: {
25
+ offset: number;
26
+ line: number;
27
+ column: number;
28
+ };
29
+ };
30
+ declare function parseDiagnostic(sf: ts.SourceFile, diagnostic: ts.Diagnostic): ElementCompilerDiagnostic;
31
+ //#endregion