@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,815 @@
1
+ import { isSafeAttributeName as isSafeAttributeName$1, literalValue, primitiveText, unwrapExpression, validateComputedExpressionBody } from "./analyze-module.js";
2
+ import { diagnosticAt } from "./diagnostics/index.js";
3
+ import { CompiledElementError, sourceRange } from "./compiler-diagnostics.js";
4
+ import ts from "typescript";
5
+ import { forbiddenSinkReason } from "@openelement/protocol/forbidden-sinks";
6
+ import { VOID_TAGS, conditionLiteralAllowed } from "@openelement/protocol/part-program";
7
+ //#region src/internal/compiler/semantic-core/lower-program.ts
8
+ /**
9
+ * JSX → Part Program lowering for the compiled grammar (#1473 split): the
10
+ * {@link Lowering} walk turns
11
+ * the analyzed render() tree into fixed Parts, Regions, locations and source
12
+ * records with stable compiler-owned paths.
13
+ */
14
+ /**
15
+ * Local name the generated module binds the canonical `computed` import to
16
+ * when a synthesized conditional-class field (#1556) exists but the authored
17
+ * module never imported computed. The synthesized name cannot collide with an
18
+ * authored binding the compiler would have resolved (a canonical computed
19
+ * import is reused by name instead), and the emitter adds the import
20
+ * alongside it.
21
+ */
22
+ const SYNTHESIZED_COMPUTED_LOCAL = "__openelementComputed";
23
+ const BOOLEAN_ATTRIBUTES = /* @__PURE__ */ new Set([
24
+ "allowfullscreen",
25
+ "async",
26
+ "autofocus",
27
+ "autoplay",
28
+ "checked",
29
+ "controls",
30
+ "default",
31
+ "defer",
32
+ "disabled",
33
+ "formnovalidate",
34
+ "hidden",
35
+ "inert",
36
+ "ismap",
37
+ "itemscope",
38
+ "loop",
39
+ "multiple",
40
+ "muted",
41
+ "nomodule",
42
+ "open",
43
+ "playsinline",
44
+ "readonly",
45
+ "required",
46
+ "reversed",
47
+ "selected"
48
+ ]);
49
+ const DOM_PROPERTY_NAMES = /* @__PURE__ */ new Set([
50
+ "checked",
51
+ "files",
52
+ "indeterminate",
53
+ "readOnly",
54
+ "scrollLeft",
55
+ "scrollTop",
56
+ "selected",
57
+ "value"
58
+ ]);
59
+ function isIdentifier(value) {
60
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);
61
+ }
62
+ /**
63
+ * Token→operator map for when-Region conditions (#1372). Only strict
64
+ * equality tokens are admitted; `==`/`!=` fail closed with OEC9013 so the
65
+ * coercion difference cannot ride in unnoticed.
66
+ */
67
+ const CONDITION_TOKEN_OPS = {
68
+ [ts.SyntaxKind.GreaterThanToken]: "greater-than",
69
+ [ts.SyntaxKind.GreaterThanEqualsToken]: "greater-or-equal",
70
+ [ts.SyntaxKind.LessThanToken]: "less-than",
71
+ [ts.SyntaxKind.LessThanEqualsToken]: "less-or-equal",
72
+ [ts.SyntaxKind.EqualsEqualsEqualsToken]: "equals",
73
+ [ts.SyntaxKind.ExclamationEqualsEqualsToken]: "not-equals"
74
+ };
75
+ /**
76
+ * React-contract JSX text cleaning (owner ruling 2026-10-02): the facebook/jsx
77
+ * whitespace rules exactly as the React toolchain implements them (Babel's
78
+ * `cleanJSXElementLiteralChild`, TypeScript's JSX transformer). Applied per
79
+ * JSXText node, three rules fall out:
80
+ * R1 (node boundaries) — a leading/trailing whitespace run touching a
81
+ * newline is stripped; a whitespace-only node containing a newline cleans
82
+ * to '' (the caller drops it);
83
+ * R2 (node interior) — a whitespace run containing a newline folds to a
84
+ * single space; a run of spaces/tabs not touching a newline is preserved
85
+ * verbatim;
86
+ * R3 (between elements) — a sibling-delimiting whitespace run with a
87
+ * newline cleans to '' (removed); a run without a newline survives
88
+ * verbatim (the one-space form oxfmt/Prettier emit between inline
89
+ * siblings renders as a single space).
90
+ * This makes React-family formatters (oxfmt included) safe on OE JSX: the
91
+ * multiline layout they produce serializes identically to the inline layout
92
+ * under React semantics (`40⏎<span>4</span>` renders `404`, not `40 4`).
93
+ *
94
+ * The input must be the parser's canonical `JsxText.text` — NOT
95
+ * `getText(sourceFile)`, which drops the leading whitespace of a run abutting
96
+ * a tag (node pos vs start gap) and would silently narrow the run before the
97
+ * rules apply. The TypeScript JSX transformer cleans this same value.
98
+ */
99
+ function cleanJsxText(raw) {
100
+ const lines = raw.split(/\r\n|\n|\r/);
101
+ let lastNonEmptyLine = 0;
102
+ for (let i = 0; i < lines.length; i++) if (/[^ \t]/.test(lines[i])) lastNonEmptyLine = i;
103
+ let text = "";
104
+ for (let i = 0; i < lines.length; i++) {
105
+ const isFirstLine = i === 0;
106
+ const isLastLine = i === lines.length - 1;
107
+ const isLastNonEmptyLine = i === lastNonEmptyLine;
108
+ let line = lines[i].replace(/\t/g, " ");
109
+ if (!isFirstLine) line = line.replace(/^ +/, "");
110
+ if (!isLastLine) line = line.replace(/ +$/, "");
111
+ if (line) {
112
+ if (!isLastNonEmptyLine) line += " ";
113
+ text += line;
114
+ }
115
+ }
116
+ return text;
117
+ }
118
+ /** Meaningful under the same React contract the emission applies. */
119
+ function hasMeaningfulJsxChild(sf, child) {
120
+ if (ts.isJsxText(child)) return cleanJsxText(child.text).length > 0;
121
+ if (ts.isJsxExpression(child)) {
122
+ if (!child.expression) return false;
123
+ const literal = literalValue(child.expression, sf);
124
+ if (literal !== void 0) return primitiveText(literal) !== "";
125
+ }
126
+ return true;
127
+ }
128
+ var Lowering = class {
129
+ parts = [];
130
+ regions = [];
131
+ dependencies = [];
132
+ locations = [];
133
+ sourceRecords = [];
134
+ generatedHandlers = [];
135
+ fieldNames;
136
+ methodNames;
137
+ computedNames;
138
+ fieldTypes;
139
+ /**
140
+ * Compiler-synthesized computed fields (#1556): one per inline conditional
141
+ * class. The caller appends them to the analyzed fields after lowering so
142
+ * the metadata, `__compiledProps` and `__computedFields` emission treat
143
+ * them exactly like authored computeds — the Part Program IR itself stays
144
+ * v1 (one class Part bound to the synthesized signal).
145
+ */
146
+ synthesizedFields = [];
147
+ /** True when the authored module binds the canonical `computed` import. */
148
+ sourceBindsComputed;
149
+ plainFieldNames;
150
+ computedFieldNames;
151
+ sf;
152
+ options;
153
+ elementSerial = 0;
154
+ conditionalClassSerial = 0;
155
+ constructor(sf, fields, methodNames, options = { computedLocal: null }) {
156
+ this.sf = sf;
157
+ this.fieldNames = new Set(fields.map((field) => field.name));
158
+ this.methodNames = new Set(methodNames);
159
+ this.computedNames = new Set(fields.filter((field) => field.computed).map((field) => field.name));
160
+ this.fieldTypes = new Map(fields.map((field) => [field.name, field.type]));
161
+ this.plainFieldNames = new Set(fields.filter((field) => !field.computed).map((f) => f.name));
162
+ this.computedFieldNames = new Set(this.computedNames);
163
+ this.sourceBindsComputed = options.computedLocal !== null;
164
+ this.options = options;
165
+ }
166
+ fail(node, code, message) {
167
+ throw new CompiledElementError([diagnosticAt(this.sf, node, code, message)]);
168
+ }
169
+ addSource(id, kind, node) {
170
+ if (this.sourceRecords.some((record) => record.id === id)) return;
171
+ this.sourceRecords.push({
172
+ id,
173
+ kind,
174
+ source: sourceRange(this.sf, node)
175
+ });
176
+ }
177
+ reserveElement(tag, path, node) {
178
+ const id = `e${this.elementSerial++}`;
179
+ this.locations.push({
180
+ id,
181
+ kind: "element",
182
+ tag,
183
+ path: [...path]
184
+ });
185
+ this.addSource(id, "element", node);
186
+ return id;
187
+ }
188
+ addElement(id, tag, attrs, children, iattrs) {
189
+ return {
190
+ k: "el",
191
+ id,
192
+ tag,
193
+ attrs,
194
+ ...iattrs && iattrs.length > 0 ? { iattrs } : {},
195
+ children
196
+ };
197
+ }
198
+ addPart(part, path, node, targetNode) {
199
+ const index = this.parts.length;
200
+ const isAnchor = part.k === "text" || part.k === "when" || part.k === "each";
201
+ const location = {
202
+ id: `p${index}`,
203
+ kind: isAnchor ? "anchor" : "sink",
204
+ path: [...path],
205
+ ...targetNode ? { node: targetNode } : {}
206
+ };
207
+ const fullPart = {
208
+ ...part,
209
+ index,
210
+ location
211
+ };
212
+ this.parts.push(fullPart);
213
+ if (isAnchor) this.locations.push({
214
+ id: `p${index}`,
215
+ kind: "anchor",
216
+ part: index,
217
+ path: [...path]
218
+ });
219
+ else this.locations.push({
220
+ id: `p${index}`,
221
+ kind: "sink",
222
+ part: index,
223
+ node: targetNode,
224
+ path: [...path]
225
+ });
226
+ const sourceKind = part.k === "when" || part.k === "each" ? "region" : "part";
227
+ this.addSource(`p${index}`, sourceKind, node);
228
+ if (part.k === "when" || part.k === "each") {
229
+ this.regions.push({
230
+ id: `r${index}`,
231
+ index,
232
+ kind: part.k,
233
+ anchor: `p${index}`,
234
+ end: `p${index}:end`,
235
+ source: `p${index}`
236
+ });
237
+ this.addSource(`r${index}`, "region", node);
238
+ }
239
+ if (part.k === "text" || part.k === "prop" || part.k === "attr" || part.k === "bool" || part.k === "class" || part.k === "style" || part.k === "html" || part.k === "when" || part.k === "each") this.dependencies.push({
240
+ signal: part.signal,
241
+ owner: {
242
+ kind: part.k === "when" || part.k === "each" ? "region" : "part",
243
+ index
244
+ },
245
+ location: `p${index}`
246
+ });
247
+ return index;
248
+ }
249
+ fieldAccess(expr) {
250
+ const value = unwrapExpression(expr);
251
+ if (ts.isPropertyAccessExpression(value) && value.expression.kind === ts.SyntaxKind.ThisKeyword && this.fieldNames.has(value.name.text)) return value.name.text;
252
+ return null;
253
+ }
254
+ methodAccess(expr) {
255
+ const value = unwrapExpression(expr);
256
+ if (ts.isPropertyAccessExpression(value) && value.expression.kind === ts.SyntaxKind.ThisKeyword && this.methodNames.has(value.name.text)) return value.name.text;
257
+ return null;
258
+ }
259
+ lowerRoot(expr) {
260
+ const root = unwrapExpression(expr);
261
+ if (ts.isJsxElement(root)) return this.lowerElement(root.openingElement.tagName, root.openingElement.attributes, [...root.children], [0], root);
262
+ if (ts.isJsxSelfClosingElement(root)) return this.lowerElement(root.tagName, root.attributes, [], [0], root);
263
+ return this.fail(root, "OEC9007", "render() must return a single JSX element");
264
+ }
265
+ normalizeAttributeName(name) {
266
+ return name === "className" ? "class" : name;
267
+ }
268
+ lowerElement(tagNameNode, attributes, children, path, sourceNode, staticOnly = false) {
269
+ const tag = tagNameNode.getText(this.sf);
270
+ const isCustomHost = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(tag);
271
+ if (!/^[a-z][a-z0-9]*$/.test(tag) && !isCustomHost) this.fail(tagNameNode, "OEC9010", `component tag <${tag}> is outside the compiler grammar (intrinsic lowercase elements and custom-element hosts only)`);
272
+ const tagReason = forbiddenSinkReason("tag", tag);
273
+ if (tagReason !== null) this.fail(tagNameNode, "OEC9010", tagReason);
274
+ const attrs = [];
275
+ const elementId = this.reserveElement(tag, path, sourceNode);
276
+ const attributeNames = /* @__PURE__ */ new Set();
277
+ let trustedHtmlCapability = false;
278
+ for (const prop of attributes.properties) {
279
+ if (ts.isJsxSpreadAttribute(prop)) continue;
280
+ if (this.normalizeAttributeName(prop.name.getText(this.sf)) !== "trustedHtml") continue;
281
+ const init = prop.initializer;
282
+ trustedHtmlCapability = init === void 0 || ts.isJsxExpression(init) && init.expression?.kind === ts.SyntaxKind.TrueKeyword;
283
+ if (!trustedHtmlCapability) this.fail(prop, "OEC9026", "trustedHtml capability marker must be the literal true");
284
+ }
285
+ for (const prop of attributes.properties) {
286
+ if (ts.isJsxSpreadAttribute(prop)) this.fail(prop, "OEC9011", "spread attributes are not supported by the compiler grammar");
287
+ const name = this.normalizeAttributeName(prop.name.getText(this.sf));
288
+ const init = prop.initializer;
289
+ if (name === "trustedHtml") continue;
290
+ const isDynamicEvent = /^on[A-Z]/.test(name) && init !== void 0 && ts.isJsxExpression(init) && init.expression !== void 0;
291
+ if (isCustomHost && (isDynamicEvent || /^on[A-Z]/.test(name))) this.fail(prop, "OEC9017", `custom-element host <${tag}> may not carry event handlers`);
292
+ if (!isSafeAttributeName$1(name) && !isDynamicEvent && name !== "innerHTML") this.fail(prop, "OEC9011", `attribute name "${name}" is unsafe`);
293
+ if (name === "innerHTML" && !(init !== void 0 && ts.isJsxExpression(init) && init.expression !== void 0 && this.fieldAccess(unwrapExpression(init.expression)) !== null)) this.fail(prop, "OEC9011", `attribute name "${name}" is unsafe`);
294
+ const attributeKey = name.toLowerCase();
295
+ if (attributeNames.has(attributeKey)) this.fail(prop, "OEC9011", `duplicate attribute "${name}" is unsupported`);
296
+ attributeNames.add(attributeKey);
297
+ if (!init) {
298
+ attrs.push([name, ""]);
299
+ continue;
300
+ }
301
+ if (ts.isStringLiteral(init)) {
302
+ attrs.push([name, init.text]);
303
+ continue;
304
+ }
305
+ if (!ts.isJsxExpression(init) || !init.expression) this.fail(prop, "OEC9011", `attribute "${name}" must be a literal or a supported expression`);
306
+ const expr = unwrapExpression(init.expression);
307
+ if (/^on[A-Z]/.test(name)) {
308
+ if (staticOnly) this.fail(prop, "OEC9012", "Region branches must be fully static");
309
+ this.lowerEvent(name, expr, path, prop, elementId);
310
+ continue;
311
+ }
312
+ if (name === "ref") {
313
+ if (isCustomHost) this.fail(prop, "OEC9017", `custom-element host <${tag}> may not carry a ref`);
314
+ if (staticOnly) this.fail(prop, "OEC9012", "Region branches must be fully static");
315
+ const ref = this.fieldAccess(expr);
316
+ if (!ref) this.fail(prop, "OEC9011", "ref must reference this.<field>");
317
+ this.addPart({
318
+ k: "ref",
319
+ ref,
320
+ path
321
+ }, path, prop, elementId);
322
+ continue;
323
+ }
324
+ if (name === "class" && !staticOnly && !isCustomHost && ts.isConditionalExpression(expr)) {
325
+ this.lowerConditionalClass(expr, path, prop, elementId);
326
+ continue;
327
+ }
328
+ const field = this.fieldAccess(expr);
329
+ if (field) {
330
+ if (staticOnly) this.fail(prop, "OEC9012", "Region branches must be fully static");
331
+ if (name === "innerHTML") {
332
+ this.lowerDynamicAttribute(name, field, tag, path, prop, elementId, trustedHtmlCapability);
333
+ continue;
334
+ }
335
+ if (isCustomHost) {
336
+ if (forbiddenSinkReason("prop", name) !== null) this.fail(prop, "OEC9011", `property sink name "${name}" is unsafe`);
337
+ this.addPart({
338
+ k: "prop",
339
+ signal: field,
340
+ name,
341
+ path
342
+ }, path, prop, elementId);
343
+ continue;
344
+ }
345
+ this.lowerDynamicAttribute(name, field, tag, path, prop, elementId, trustedHtmlCapability);
346
+ continue;
347
+ }
348
+ const literal = literalValue(expr, this.sf);
349
+ if (literal === void 0) this.fail(prop, "OEC9011", `attribute "${name}" must be a literal, this.<property>, or a supported expression`);
350
+ const text = primitiveText(literal);
351
+ if (text === null) this.fail(prop, "OEC9011", `attribute "${name}" only accepts primitive literal values`);
352
+ if (literal === false || literal === null) continue;
353
+ attrs.push([name, literal === true ? "" : text ?? ""]);
354
+ }
355
+ const hasHtmlSink = this.parts.some((part) => part.k === "html" && part.path.length === path.length && part.path.every((value, index) => value === path[index]));
356
+ if (trustedHtmlCapability && !hasHtmlSink) this.fail(sourceNode, "OEC9026", "trustedHtml capability marker requires an innerHTML sink");
357
+ if (!isCustomHost && hasHtmlSink && children.some((child) => hasMeaningfulJsxChild(this.sf, child))) this.fail(sourceNode, "OEC9026", "an innerHTML sink target must be otherwise childless (the sink owns its content)");
358
+ const lowered = [];
359
+ for (const child of children) {
360
+ const childPath = [...path, lowered.length];
361
+ if (ts.isJsxText(child)) {
362
+ const value = cleanJsxText(child.text);
363
+ if (value === "") continue;
364
+ lowered.push({
365
+ k: "text",
366
+ value
367
+ });
368
+ continue;
369
+ }
370
+ if (ts.isJsxExpression(child)) {
371
+ const loweredChild = this.lowerExpressionChild(child, staticOnly, childPath);
372
+ if (loweredChild) lowered.push(loweredChild);
373
+ continue;
374
+ }
375
+ if (ts.isJsxElement(child)) {
376
+ lowered.push(this.lowerElement(child.openingElement.tagName, child.openingElement.attributes, [...child.children], childPath, child, staticOnly));
377
+ continue;
378
+ }
379
+ if (ts.isJsxSelfClosingElement(child)) {
380
+ lowered.push(this.lowerElement(child.tagName, child.attributes, [], childPath, child, staticOnly));
381
+ continue;
382
+ }
383
+ this.fail(child, "OEC9013", "JSX fragments and spreads are outside the compiler grammar");
384
+ }
385
+ if (VOID_TAGS.has(tag)) {
386
+ const child = children.find((candidate) => hasMeaningfulJsxChild(this.sf, candidate));
387
+ if (child) this.fail(child, "OEC9013", `void element <${tag}> may not have children`);
388
+ }
389
+ return this.addElement(elementId, tag, attrs, lowered);
390
+ }
391
+ lowerEvent(attributeName, expr, path, sourceNode, elementId) {
392
+ const action = this.eventAction(expr, sourceNode);
393
+ return this.addPart({
394
+ k: "event",
395
+ event: attributeName.slice(2).toLowerCase(),
396
+ handler: action.handler,
397
+ action: action.action,
398
+ path
399
+ }, path, sourceNode, elementId);
400
+ }
401
+ eventAction(expr, sourceNode) {
402
+ const method = this.methodAccess(expr);
403
+ if (method) return {
404
+ handler: method,
405
+ action: {
406
+ kind: "method",
407
+ name: method
408
+ }
409
+ };
410
+ if (!ts.isArrowFunction(expr) || expr.parameters.length > 1) this.fail(sourceNode, "OEC9016", "event handlers must be this.<method> or a single-action arrow");
411
+ const expression = ts.isBlock(expr.body) ? expr.body.statements.length === 1 && ts.isExpressionStatement(expr.body.statements[0]) ? expr.body.statements[0].expression : void 0 : expr.body;
412
+ if (!expression) this.fail(sourceNode, "OEC9016", "event arrow handlers must contain exactly one supported action");
413
+ const action = this.parseEventMutation(expression, sourceNode);
414
+ let name = `__compiledEvent${this.generatedHandlers.length}`;
415
+ while (this.methodNames.has(name) || this.fieldNames.has(name)) name = `_${name}`;
416
+ this.methodNames.add(name);
417
+ this.generatedHandlers.push({
418
+ name,
419
+ action,
420
+ node: expr
421
+ });
422
+ this.addSource(`handler:${name}`, "handler", expr);
423
+ return {
424
+ handler: name,
425
+ action
426
+ };
427
+ }
428
+ parseEventMutation(expr, near) {
429
+ const value = unwrapExpression(expr);
430
+ const assertWritable = (signal) => {
431
+ if (this.computedNames.has(signal)) this.fail(near, "OEC9024", `event actions may not write computed field "${signal}" — assign its source properties`);
432
+ };
433
+ if (ts.isPostfixUnaryExpression(value) || ts.isPrefixUnaryExpression(value)) {
434
+ const signal = this.fieldAccess(value.operand);
435
+ if (!signal || value.operator !== ts.SyntaxKind.PlusPlusToken && value.operator !== ts.SyntaxKind.MinusMinusToken) this.fail(near, "OEC9016", "event mutations support only this.<number>++ or --");
436
+ assertWritable(signal);
437
+ return {
438
+ kind: value.operator === ts.SyntaxKind.PlusPlusToken ? "increment" : "decrement",
439
+ signal
440
+ };
441
+ }
442
+ if (ts.isBinaryExpression(value)) {
443
+ const signal = this.fieldAccess(value.left);
444
+ const literal = literalValue(value.right, this.sf);
445
+ if (!signal || literal === void 0) this.fail(near, "OEC9016", "event assignment values must be serializable literals");
446
+ assertWritable(signal);
447
+ if (value.operatorToken.kind === ts.SyntaxKind.EqualsToken) return {
448
+ kind: "assign",
449
+ signal,
450
+ value: literal
451
+ };
452
+ if ((value.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken || value.operatorToken.kind === ts.SyntaxKind.MinusEqualsToken) && typeof literal === "number") return {
453
+ kind: value.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken ? "add" : "subtract",
454
+ signal,
455
+ value: literal
456
+ };
457
+ this.fail(near, "OEC9016", "event arithmetic supports only numeric += or -= literals");
458
+ }
459
+ if (ts.isCallExpression(value) && value.arguments.length === 0) {
460
+ const method = this.methodAccess(value.expression);
461
+ if (method) return {
462
+ kind: "call",
463
+ name: method
464
+ };
465
+ }
466
+ this.fail(near, "OEC9016", "unsupported event action; use this.<field>++, assignment or this.<method>()");
467
+ }
468
+ /**
469
+ * Inline conditional class (#1556): `class={this.<cond> ? 'a' : 'b'}` is
470
+ * authoring sugar for a computed field bound to the element's class Part —
471
+ * exactly the shape the author would hand-write as
472
+ * `@property({ reflect: false, attribute: false }) x = computed(() => ...)`
473
+ * plus `class={x}`. The lowering therefore reuses the computed-field
474
+ * machinery end to end: the condition validates under the same body grammar
475
+ * (only `this.<declared plain property>` reads; module-scope values pass
476
+ * through), the synthesized factory rides the existing `__computedFields`
477
+ * emission, and the Part Program stays v1 — one `class` Part whose signal
478
+ * is the synthesized computed signal. No runtime or IR shape changes; the
479
+ * serialized class value and its reactivity are the existing class-Part
480
+ * and computed-signal semantics on every execution mode.
481
+ *
482
+ * Both branches must be string literals (the class-attribute text); an
483
+ * empty string is the idiomatic off-branch. Everything else fails closed
484
+ * with OEC9011 — no runtime fallback (P2). A condition reading no declared
485
+ * property would emit a computed entry with an empty dep list, which the
486
+ * wire validator rejects, so it fails here at the source.
487
+ */
488
+ lowerConditionalClass(expr, path, sourceNode, elementId) {
489
+ for (const branch of [expr.whenTrue, expr.whenFalse]) {
490
+ const value = unwrapExpression(branch);
491
+ if (!ts.isStringLiteral(value) && !ts.isNoSubstitutionTemplateLiteral(value)) this.fail(sourceNode, "OEC9011", "conditional class branches must be string literals: class={this.<cond> ? 'a' : 'b'}");
492
+ }
493
+ const { deps, bodyText } = validateComputedExpressionBody(expr, this.sf, this.plainFieldNames, this.computedFieldNames, (node, code, message) => this.fail(node, code, message), {
494
+ actor: "conditional class conditions",
495
+ single: "conditional class condition",
496
+ plural: "conditional class conditions"
497
+ });
498
+ if (deps.length === 0) this.fail(sourceNode, "OEC9011", "conditional class conditions must read at least one this.<property>");
499
+ const computedName = this.options.computedLocal ?? "__openelementComputed";
500
+ let name = `__compiledClass${this.conditionalClassSerial++}`;
501
+ while (this.methodNames.has(name) || this.fieldNames.has(name)) name = `_${name}`;
502
+ this.fieldNames.add(name);
503
+ this.computedNames.add(name);
504
+ const node = Object.assign(Object.create(expr), {
505
+ name: expr,
506
+ initializer: expr
507
+ });
508
+ this.synthesizedFields.push({
509
+ name,
510
+ reflect: false,
511
+ attribute: null,
512
+ type: "string",
513
+ converter: "string",
514
+ typeConstructor: "String",
515
+ accessibility: "",
516
+ typeText: "",
517
+ initializerText: "",
518
+ defaultValue: null,
519
+ node,
520
+ computed: {
521
+ deps,
522
+ factoryText: `(__s) => ${computedName}(() => ${bodyText})`,
523
+ body: expr
524
+ }
525
+ });
526
+ this.addPart({
527
+ k: "class",
528
+ signal: name,
529
+ path
530
+ }, path, sourceNode, elementId);
531
+ }
532
+ lowerDynamicAttribute(name, signal, tag, path, sourceNode, elementId, trustedHtmlCapability) {
533
+ const lowerName = name.toLowerCase();
534
+ if (name === "class") {
535
+ this.addPart({
536
+ k: "class",
537
+ signal,
538
+ path
539
+ }, path, sourceNode, elementId);
540
+ return;
541
+ }
542
+ if (name === "style") {
543
+ this.addPart({
544
+ k: "style",
545
+ signal,
546
+ path
547
+ }, path, sourceNode, elementId);
548
+ return;
549
+ }
550
+ if (name === "innerHTML") {
551
+ if (this.fieldTypes.get(signal) !== "object") this.fail(sourceNode, "OEC9026", "innerHTML sinks require an Object-typed TrustedHtml property");
552
+ if (!trustedHtmlCapability) this.fail(sourceNode, "OEC9026", "innerHTML sinks require the explicit trustedHtml capability marker");
553
+ if (VOID_TAGS.has(tag)) this.fail(sourceNode, "OEC9026", `void element <${tag}> cannot carry an innerHTML sink`);
554
+ this.addPart({
555
+ k: "html",
556
+ signal,
557
+ path
558
+ }, path, sourceNode, elementId);
559
+ return;
560
+ }
561
+ if (BOOLEAN_ATTRIBUTES.has(lowerName)) {
562
+ if (forbiddenSinkReason("bool", name) !== null) this.fail(sourceNode, "OEC9011", `attribute name "${name}" is unsafe`);
563
+ this.addPart({
564
+ k: "bool",
565
+ signal,
566
+ name,
567
+ path
568
+ }, path, sourceNode, elementId);
569
+ return;
570
+ }
571
+ if (name === "value" || DOM_PROPERTY_NAMES.has(name) || tag === "input" && name === "value") {
572
+ if (forbiddenSinkReason("prop", name) !== null) this.fail(sourceNode, "OEC9011", `property sink name "${name}" is unsafe`);
573
+ this.addPart({
574
+ k: "prop",
575
+ signal,
576
+ name,
577
+ path
578
+ }, path, sourceNode, elementId);
579
+ return;
580
+ }
581
+ if (forbiddenSinkReason("attr", name) !== null) this.fail(sourceNode, "OEC9011", `attribute name "${name}" is unsafe`);
582
+ this.addPart({
583
+ k: "attr",
584
+ signal,
585
+ name,
586
+ path
587
+ }, path, sourceNode, elementId);
588
+ }
589
+ lowerExpressionChild(child, staticOnly, path) {
590
+ if (!child.expression) return null;
591
+ const expr = unwrapExpression(child.expression);
592
+ const field = this.fieldAccess(expr);
593
+ if (field) {
594
+ if (staticOnly) this.fail(child, "OEC9012", "Region branches must be fully static");
595
+ const index = this.addPart({
596
+ k: "text",
597
+ signal: field
598
+ }, path, child);
599
+ return {
600
+ k: "part",
601
+ id: `p${index}`,
602
+ index
603
+ };
604
+ }
605
+ const literal = literalValue(expr, this.sf);
606
+ if (literal !== void 0) {
607
+ const text = primitiveText(literal);
608
+ if (text === null) this.fail(child, "OEC9013", "dynamic child literals must be primitive values");
609
+ if (text === "") return null;
610
+ return {
611
+ k: "text",
612
+ value: text ?? ""
613
+ };
614
+ }
615
+ if (ts.isConditionalExpression(expr)) {
616
+ if (staticOnly) this.fail(child, "OEC9012", "nested Regions are outside the compiler grammar");
617
+ const test = this.parseCondition(expr.condition, child);
618
+ const on = this.lowerStaticBranch(expr.whenTrue, child);
619
+ const off = this.lowerStaticBranch(expr.whenFalse, child);
620
+ const index = this.addPart({
621
+ k: "when",
622
+ signal: test.signal,
623
+ test,
624
+ on: [on],
625
+ off: [off]
626
+ }, path, child);
627
+ return {
628
+ k: "part",
629
+ id: `p${index}`,
630
+ index
631
+ };
632
+ }
633
+ if (ts.isCallExpression(expr)) {
634
+ if (staticOnly) this.fail(child, "OEC9012", "nested Regions are outside the compiler grammar");
635
+ return this.lowerEach(expr, child, path);
636
+ }
637
+ this.fail(child, "OEC9013", "unsupported dynamic expression; use this.<property>, a supported condition, or this.<array>.map(...)");
638
+ }
639
+ parseCondition(expr, near) {
640
+ const condition = unwrapExpression(expr);
641
+ const bareSignal = this.fieldAccess(condition);
642
+ if (bareSignal) return {
643
+ signal: bareSignal,
644
+ op: "truthy",
645
+ value: true
646
+ };
647
+ if (ts.isPrefixUnaryExpression(condition) && condition.operator === ts.SyntaxKind.ExclamationToken) {
648
+ const negatedSignal = this.fieldAccess(unwrapExpression(condition.operand));
649
+ if (negatedSignal) return {
650
+ signal: negatedSignal,
651
+ op: "truthy",
652
+ value: false
653
+ };
654
+ }
655
+ if (ts.isBinaryExpression(condition)) {
656
+ const signal = this.fieldAccess(condition.left);
657
+ const value = literalValue(condition.right, this.sf);
658
+ const op = CONDITION_TOKEN_OPS[condition.operatorToken.kind];
659
+ if (signal && op && value !== void 0 && typeof value !== "object" && conditionLiteralAllowed(op, value)) return {
660
+ signal,
661
+ op,
662
+ value
663
+ };
664
+ }
665
+ this.fail(near, "OEC9013", "conditional Regions support this.<property> compared with a numeric literal (>, >=, <, <=), a number/string/boolean equality (===, !==), or a bare this.<property> (optionally negated) truthiness test");
666
+ }
667
+ lowerStaticBranch(expr, near) {
668
+ const branch = unwrapExpression(expr);
669
+ if (ts.isJsxElement(branch)) return this.lowerElement(branch.openingElement.tagName, branch.openingElement.attributes, [...branch.children], [], branch, true);
670
+ if (ts.isJsxSelfClosingElement(branch)) return this.lowerElement(branch.tagName, branch.attributes, [], [], branch, true);
671
+ this.fail(near, "OEC9012", "conditional Region branches must be single static JSX elements");
672
+ }
673
+ lowerEach(expr, near, path) {
674
+ const callee = expr.expression;
675
+ if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== "map" || expr.arguments.length !== 1) this.fail(near, "OEC9013", "list Regions support exactly this.<property>.map(...)");
676
+ const signal = this.fieldAccess(callee.expression);
677
+ if (!signal) this.fail(near, "OEC9013", "list Regions must map over this.<property>");
678
+ const arrow = expr.arguments[0];
679
+ if (!ts.isArrowFunction(arrow) || arrow.parameters.length !== 1 || !ts.isIdentifier(arrow.parameters[0].name)) this.fail(near, "OEC9013", "list Region mapper must be a single-parameter arrow function");
680
+ if (ts.isBlock(arrow.body)) this.fail(near, "OEC9013", "list Region mapper must return one JSX element");
681
+ const body = unwrapExpression(arrow.body);
682
+ if (!ts.isJsxElement(body) && !ts.isJsxSelfClosingElement(body)) this.fail(near, "OEC9013", "list Region mapper must return one JSX element");
683
+ const param = arrow.parameters[0].name.text;
684
+ const attributes = ts.isJsxElement(body) ? body.openingElement.attributes : body.attributes;
685
+ let key = null;
686
+ for (const prop of attributes.properties) {
687
+ if (!ts.isJsxAttribute(prop)) this.fail(prop, "OEC9011", "list Region items do not support spread attributes");
688
+ if (prop.name.getText(this.sf) !== "key") continue;
689
+ if (key !== null) this.fail(prop, "OEC9014", "list Region items may declare key only once");
690
+ if (!prop.initializer || !ts.isJsxExpression(prop.initializer) || !prop.initializer.expression) this.fail(prop, "OEC9014", "key must be key={<item>.<field>}");
691
+ const keyExpr = unwrapExpression(prop.initializer.expression);
692
+ if (ts.isPropertyAccessExpression(keyExpr) && ts.isIdentifier(keyExpr.expression) && keyExpr.expression.text === param && isIdentifier(keyExpr.name.text)) key = keyExpr.name.text;
693
+ else this.fail(prop, "OEC9014", `key must reference ${param}.<field>`);
694
+ }
695
+ if (!key) this.fail(body, "OEC9014", "list Region items require key={<item>.<field>}");
696
+ const itemFields = [];
697
+ const itemEvents = [];
698
+ const item = this.lowerItemElement(body, param, itemFields, [], true, itemEvents, "");
699
+ const uniqueFields = [...new Set(itemFields)];
700
+ if (uniqueFields.length === 0) this.fail(body, "OEC9013", "list Region items must bind at least one {<item>.<field>} value or attribute slot");
701
+ const index = this.addPart({
702
+ k: "each",
703
+ signal,
704
+ key,
705
+ ...uniqueFields.length === 1 ? { field: uniqueFields[0] } : {},
706
+ item: [item],
707
+ ...itemEvents.length > 0 ? { itemEvents } : {}
708
+ }, path, near);
709
+ return {
710
+ k: "part",
711
+ id: `p${index}`,
712
+ index
713
+ };
714
+ }
715
+ lowerItemElement(element, param, itemFields, path, allowKey = false, itemEvents, selector = "") {
716
+ const tagName = ts.isJsxElement(element) ? element.openingElement.tagName : element.tagName;
717
+ const attributes = ts.isJsxElement(element) ? element.openingElement.attributes : element.attributes;
718
+ const tag = tagName.getText(this.sf);
719
+ const isCustomHost = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(tag);
720
+ if (!/^[a-z][a-z0-9]*$/.test(tag) && !isCustomHost) this.fail(tagName, "OEC9010", "list Region item must be an intrinsic lowercase element");
721
+ const itemTagReason = forbiddenSinkReason("tag", tag);
722
+ if (itemTagReason !== null) this.fail(tagName, "OEC9010", itemTagReason);
723
+ const elementId = this.reserveElement(tag, path, element);
724
+ const attrs = [];
725
+ const iattrs = [];
726
+ const attributeNames = /* @__PURE__ */ new Set();
727
+ for (const prop of attributes.properties) {
728
+ if (!ts.isJsxAttribute(prop)) this.fail(prop, "OEC9011", "spread attributes are not supported in item templates");
729
+ const name = this.normalizeAttributeName(prop.name.getText(this.sf));
730
+ if (name === "key") {
731
+ if (!allowKey) this.fail(prop, "OEC9011", "key is only supported on the list Region item root");
732
+ continue;
733
+ }
734
+ const isItemEvent = /^on[A-Z]/.test(name) && prop.initializer !== void 0 && ts.isJsxExpression(prop.initializer) && prop.initializer.expression !== void 0;
735
+ if (!isSafeAttributeName$1(name) && !isItemEvent) this.fail(prop, "OEC9011", `attribute name "${name}" is unsafe`);
736
+ const attributeKey = name.toLowerCase();
737
+ if (attributeNames.has(attributeKey)) this.fail(prop, "OEC9011", `duplicate attribute "${name}" is unsupported`);
738
+ attributeNames.add(attributeKey);
739
+ if (!prop.initializer) {
740
+ attrs.push([name, ""]);
741
+ continue;
742
+ }
743
+ if (ts.isStringLiteral(prop.initializer)) {
744
+ attrs.push([name, prop.initializer.text]);
745
+ continue;
746
+ }
747
+ if (!ts.isJsxExpression(prop.initializer) || !prop.initializer.expression) this.fail(prop, "OEC9011", "item template attributes must be static literals");
748
+ if (/^on[A-Z]/.test(name)) {
749
+ if (isCustomHost) this.fail(prop, "OEC9017", `custom-element host <${tag}> may not carry event handlers`);
750
+ if (itemEvents === void 0) this.fail(prop, "OEC9012", "event handlers are only supported on list Region item templates");
751
+ const action = this.eventAction(unwrapExpression(prop.initializer.expression), prop);
752
+ itemEvents.push({
753
+ event: name.slice(2).toLowerCase(),
754
+ handler: action.handler,
755
+ action: action.action,
756
+ ...selector ? { selector } : {}
757
+ });
758
+ continue;
759
+ }
760
+ const attrExpr = unwrapExpression(prop.initializer.expression);
761
+ if (ts.isPropertyAccessExpression(attrExpr) && ts.isIdentifier(attrExpr.expression) && attrExpr.expression.text === param && isIdentifier(attrExpr.name.text)) {
762
+ itemFields.push(attrExpr.name.text);
763
+ iattrs.push([name, attrExpr.name.text]);
764
+ continue;
765
+ }
766
+ const literal = literalValue(prop.initializer.expression, this.sf);
767
+ if (literal === void 0) this.fail(prop, "OEC9011", `item template attribute "${name}" must be a static literal or {${param}.<field>}`);
768
+ const text = primitiveText(literal);
769
+ if (text === null) this.fail(prop, "OEC9011", "item template attributes must use primitive literals");
770
+ if (literal === false || literal === null) continue;
771
+ attrs.push([name, literal === true ? "" : text ?? ""]);
772
+ }
773
+ const children = [];
774
+ const rawChildren = ts.isJsxElement(element) ? [...element.children] : [];
775
+ if (VOID_TAGS.has(tag)) {
776
+ const child = rawChildren.find((candidate) => hasMeaningfulJsxChild(this.sf, candidate));
777
+ if (child) this.fail(child, "OEC9013", `void element <${tag}> may not have children`);
778
+ }
779
+ if (isCustomHost && rawChildren.some((child) => hasMeaningfulJsxChild(this.sf, child))) this.fail(element, "OEC9017", `custom-element host <${tag}> may not have children in the compiler grammar (slots are unsupported)`);
780
+ let elementChildIndex = 0;
781
+ for (const child of rawChildren) {
782
+ const childPath = [...path, children.length];
783
+ if (ts.isJsxText(child)) {
784
+ const text = cleanJsxText(child.text);
785
+ if (text !== "") children.push({
786
+ k: "text",
787
+ value: text
788
+ });
789
+ continue;
790
+ }
791
+ if (ts.isJsxExpression(child) && child.expression) {
792
+ const expr = unwrapExpression(child.expression);
793
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) && expr.expression.text === param && isIdentifier(expr.name.text)) {
794
+ itemFields.push(expr.name.text);
795
+ children.push({
796
+ k: "ival",
797
+ field: expr.name.text
798
+ });
799
+ continue;
800
+ }
801
+ this.fail(child, "OEC9013", `item child must be {${param}.<field>}`);
802
+ }
803
+ if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child)) {
804
+ const childSelector = `${selector || ":scope"} > *:nth-child(${elementChildIndex + 1})`;
805
+ children.push(this.lowerItemElement(child, param, itemFields, childPath, false, itemEvents, childSelector));
806
+ elementChildIndex += 1;
807
+ continue;
808
+ }
809
+ this.fail(child, "OEC9013", "item templates support static text, item values and intrinsic elements");
810
+ }
811
+ return this.addElement(elementId, tag, attrs, children, iattrs);
812
+ }
813
+ };
814
+ //#endregion
815
+ export { Lowering, SYNTHESIZED_COMPUTED_LOCAL };