@openelement/compiler 1.0.0-alpha.14 → 1.0.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/package.json +4 -2
  2. package/src/compiler.d.ts +12 -6
  3. package/src/compiler.js +11 -6
  4. package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +11 -0
  5. package/src/internal/compiler/compiled-artifact-class-candidates.js +46 -0
  6. package/src/internal/compiler/compiled-artifact-style-requests.d.ts +26 -7
  7. package/src/internal/compiler/compiled-artifact-style-requests.js +57 -9
  8. package/src/internal/compiler/plugin.d.ts +68 -49
  9. package/src/internal/compiler/plugin.js +93 -82
  10. package/src/internal/compiler/semantic-core/analyze-module.d.ts +73 -0
  11. package/src/internal/compiler/semantic-core/analyze-module.js +29 -379
  12. package/src/internal/compiler/semantic-core/attribute-classification.js +92 -0
  13. package/src/internal/compiler/semantic-core/compiler-diagnostics.js +2 -16
  14. package/src/internal/compiler/semantic-core/diagnostics/index.d.ts +21 -1
  15. package/src/internal/compiler/semantic-core/diagnostics/index.js +32 -1
  16. package/src/internal/compiler/semantic-core/expression-lowering.js +469 -0
  17. package/src/internal/compiler/semantic-core/expression-registry.js +165 -0
  18. package/src/internal/compiler/semantic-core/function-frontend.js +1229 -0
  19. package/src/internal/compiler/semantic-core/island-policy-statement.js +52 -0
  20. package/src/internal/compiler/semantic-core/jsx-module-id.d.ts +4 -0
  21. package/src/internal/compiler/semantic-core/jsx-module-id.js +7 -0
  22. package/src/internal/compiler/semantic-core/lower-program.d.ts +220 -0
  23. package/src/internal/compiler/semantic-core/lower-program.js +350 -142
  24. package/src/internal/compiler/semantic-core/module-analysis.d.ts +82 -4
  25. package/src/internal/compiler/semantic-core/module-analysis.js +88 -19
  26. package/src/internal/compiler/semantic-core/parse-module.js +16 -16
  27. package/src/internal/compiler/semantic-core/scope-resolution.d.ts +208 -0
  28. package/src/internal/compiler/semantic-core/scope-resolution.js +1121 -0
  29. package/src/internal/compiler/semantic-core/server-component.d.ts +129 -0
  30. package/src/internal/compiler/semantic-core/server-component.js +587 -0
  31. package/src/internal/compiler/semantic-core/type-check.js +1 -1
  32. package/src/internal/compiler/semantic-core/type-erasure.js +156 -0
  33. package/src/internal/compiler/semantic-ir/generated-element/compile.d.ts +61 -0
  34. package/src/internal/compiler/semantic-ir/generated-element/compile.js +137 -0
  35. package/src/internal/compiler/semantic-ir/generated-element/contract.d.ts +201 -0
  36. package/src/internal/compiler/semantic-ir/generated-element/contract.js +147 -0
  37. package/src/internal/compiler/semantic-ir/generated-element/emit.js +452 -0
  38. package/src/internal/compiler/semantic-ir/generated-element/site.js +1195 -0
  39. package/src/internal/compiler/semantic-ir/generated-leaf/claim-emission.js +1372 -0
  40. package/src/internal/compiler/semantic-ir/generated-leaf/codegen-literals.js +31 -0
  41. package/src/internal/compiler/semantic-ir/generated-leaf/component-emission.js +647 -0
  42. package/src/internal/compiler/semantic-ir/generated-leaf/emission.js +388 -0
  43. package/src/internal/compiler/semantic-ir/generated-leaf/generate.js +395 -0
  44. package/src/internal/compiler/semantic-ir/generated-leaf/instance-emission.js +865 -0
  45. package/src/internal/compiler/semantic-ir/generated-leaf/mount-emission.js +960 -0
  46. package/src/internal/compiler/semantic-ir/generated-leaf/server-emission.js +1011 -0
  47. package/src/internal/compiler/semantic-ir/generated-leaf/structure.js +714 -0
  48. package/src/internal/compiler/style-requests.d.ts +35 -7
  49. package/src/internal/compiler/style-requests.js +57 -11
  50. package/src/internal/compiler/tailwind-candidates.d.ts +84 -0
  51. package/src/internal/compiler/tailwind-candidates.js +54 -0
  52. package/src/internal/compiler/semantic-core/compile.d.ts +0 -39
  53. package/src/internal/compiler/semantic-core/compile.js +0 -98
  54. package/src/internal/compiler/semantic-core/emit-module.js +0 -313
  55. package/src/internal/compiler/semantic-core/emit-program.js +0 -121
  56. package/src/internal/compiler/semantic-core/style-imports.js +0 -87
@@ -1,5 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { OpenElementError } from "@openelement/protocol/errors";
3
+ import { DiagnosticEnvelope } from "@openelement/protocol/diagnostics";
3
4
  //#region src/internal/compiler/semantic-core/diagnostics/index.d.ts
4
5
  export interface CompilerDiagnostic {
5
6
  code: string;
@@ -26,6 +27,25 @@ export declare class CompilerDiagnosticError extends OpenElementError {
26
27
  declare function diagnosticAt(sourceFile: ts.SourceFile, node: ts.Node, code: string, message: string): CompilerDiagnostic;
27
28
  /** Flatten a TypeScript parse diagnostic without leaking compiler internals. */
28
29
  declare function diagnosticMessage(diagnostic: ts.Diagnostic): string;
30
+ /**
31
+ * The record fields the envelope projection reads — the structural subset
32
+ * both a full {@linkcode CompilerDiagnostic} and the build-carried record
33
+ * (the `this.error()` projection, which drops the compiler-internal range)
34
+ * satisfy.
35
+ */
36
+ export type ProjectableCompilerDiagnostic = Pick<CompilerDiagnostic, 'code' | 'message' | 'file' | 'line' | 'character'>;
37
+ /**
38
+ * Project the compiler's already-structured diagnostics onto the protocol's
39
+ * {@linkcode DiagnosticEnvelope} shape. An empty list projects to an empty
40
+ * list — the caller keeps its own fallback rather than inventing a record.
41
+ */
42
+ export declare function compilerDiagnosticsToEnvelopes(diagnostics: ReadonlyArray<ProjectableCompilerDiagnostic>): DiagnosticEnvelope[];
43
+ /** Record one compile failure's envelopes for the build exit (#1612). */
44
+ export declare function recordCompilerDiagnostics(diagnostics: ReadonlyArray<ProjectableCompilerDiagnostic>): void;
45
+ /** Drain the recorded envelopes: the exit reads them exactly once. */
46
+ export declare function takeCompilerDiagnostics(): DiagnosticEnvelope[];
47
+ /** Clear without reading — the hygiene a fresh build invocation starts with. */
48
+ export declare function clearCompilerDiagnostics(): void;
29
49
  /** Rollup-compatible error shape emitted by the Vite adapter boundary. */
30
50
  export interface PluginDiagnosticError {
31
51
  id: string;
@@ -50,5 +70,5 @@ declare function formatDiagnosticFrame(source: string, diagnostic: CompilerDiagn
50
70
  * for an empty diagnostics list: there is nothing to locate or render, and
51
71
  * the caller keeps its own fallback rather than inventing a location.
52
72
  */
53
- declare function diagnosticPluginError(diagnostics: CompilerDiagnostic[], source: string, id: string): PluginDiagnosticError | null;
73
+ export declare function diagnosticPluginError(diagnostics: CompilerDiagnostic[], source: string, id: string): PluginDiagnosticError | null;
54
74
  //#endregion
@@ -49,6 +49,37 @@ function diagnosticMessage(diagnostic) {
49
49
  return ts.flattenDiagnosticMessageText(diagnostic.messageText, " ");
50
50
  }
51
51
  /**
52
+ * Project the compiler's already-structured diagnostics onto the protocol's
53
+ * {@linkcode DiagnosticEnvelope} shape. An empty list projects to an empty
54
+ * list — the caller keeps its own fallback rather than inventing a record.
55
+ */
56
+ function compilerDiagnosticsToEnvelopes(diagnostics) {
57
+ return diagnostics.map((diagnostic) => ({
58
+ code: diagnostic.code,
59
+ severity: "error",
60
+ phase: "build",
61
+ message: diagnostic.message,
62
+ file: diagnostic.file,
63
+ line: diagnostic.line,
64
+ column: diagnostic.character
65
+ }));
66
+ }
67
+ let exitRecord = [];
68
+ /** Record one compile failure's envelopes for the build exit (#1612). */
69
+ function recordCompilerDiagnostics(diagnostics) {
70
+ exitRecord.push(...compilerDiagnosticsToEnvelopes(diagnostics));
71
+ }
72
+ /** Drain the recorded envelopes: the exit reads them exactly once. */
73
+ function takeCompilerDiagnostics() {
74
+ const drained = exitRecord;
75
+ exitRecord = [];
76
+ return drained;
77
+ }
78
+ /** Clear without reading — the hygiene a fresh build invocation starts with. */
79
+ function clearCompilerDiagnostics() {
80
+ exitRecord = [];
81
+ }
82
+ /**
52
83
  * Render the authored line and its neighbours with a caret under the recorded
53
84
  * range — the frame field a build overlay consumes. Multi-line ranges caret
54
85
  * only the first line (Rollup's own frames do the same); an empty or
@@ -94,4 +125,4 @@ function diagnosticPluginError(diagnostics, source, id) {
94
125
  };
95
126
  }
96
127
  //#endregion
97
- export { CompilerDiagnosticError, diagnosticAt, diagnosticMessage, diagnosticPluginError, formatDiagnosticFrame };
128
+ export { CompilerDiagnosticError, clearCompilerDiagnostics, compilerDiagnosticsToEnvelopes, diagnosticAt, diagnosticMessage, diagnosticPluginError, formatDiagnosticFrame, recordCompilerDiagnostics, takeCompilerDiagnostics };
@@ -0,0 +1,469 @@
1
+ import { collectErasureBoundaryRefusals, eraseTypeScriptSyntax } from "./type-erasure.js";
2
+ import ts from "typescript";
3
+ //#region src/internal/compiler/semantic-core/expression-lowering.ts
4
+ /**
5
+ * M03-I-2 — expression lowering text mechanics (Alpha16a, compiler-private).
6
+ *
7
+ * Design authority: `docs/architecture/m03-expression-identity.md` (M03-B) and
8
+ * `docs/architecture/m03-i0-sourcemap-prototype.md` (M03-I-0, adopted M1
9
+ * mechanism). This module is the **production** transform behind Route 3:
10
+ *
11
+ * 1. transform the existing SourceFile (no reparse): every JSX node in the
12
+ * expression is replaced 1:1 by a caller-supplied recipe **reference**
13
+ * call at the same authored position (`setTextRange`);
14
+ * 2. attach a namespaced synthetic comment around every expression/JSX node
15
+ * so the public printer can report one **anchor** (node start) per node;
16
+ * 3. print once with `ts.createPrinter().printNode(EmitHint.Expression)`;
17
+ * 4. index the markers in one pass, strip them through prefix sums + binary
18
+ * search, trim at anchor boundaries, and resolve generated offsets;
19
+ * 5. restore the temporarily-attached synthetic comments and dispose the
20
+ * `TransformationResult` in a `finally` — no transformed tree survives the
21
+ * call.
22
+ *
23
+ * Deliberate boundaries:
24
+ *
25
+ * - **Erasure is integrated (M03-I-3, A3).** `type-erasure.ts` strips the
26
+ * admitted TypeScript-only syntax inside the same transform (before/with JSX
27
+ * replacement); anything outside that set still fails closed
28
+ * (`OEIR_ERASURE_UNSUPPORTED` for class authoring, plus the context matrix).
29
+ * The differential `ts.transpileModule` erasure oracle lives in tests only.
30
+ * - **No production compile-path wiring.** A4 owns the component frontend; the
31
+ * registry is a sidecar M05 consumes, not a stage in the current pipeline.
32
+ * - **No runtime recipe naming.** The recipe-reference call shape is supplied by
33
+ * the caller (`RecipeReference`); this module invents no runtime identifier.
34
+ * - **End-to-end module source map is M05.** This module produces expression
35
+ * segments in the existing `EmissionSegment` convention and supports codegen
36
+ * rebasing; composing them into the generated module's map is M05's job.
37
+ *
38
+ * Diagnostics reuse the A1 resolver's source-located shape (`ScopeDiagnostic`,
39
+ * `SourceSpan`), so one module's diagnostics aggregate without translation.
40
+ */
41
+ /** Bump when the marker/print/erasure pipeline changes; recorded in the registry. */
42
+ const EXPRESSION_LOWERING_TRANSFORM_VERSION = "alpha16a-m03-i3.1";
43
+ /** Prefix of the synthetic marker namespace (derived from the source hash). */
44
+ const MARKER_PREFIX = "__oe_lm_";
45
+ /** `true` for the JSX nodes M03 replaces with recipe references. */
46
+ function isJsxNode(node) {
47
+ return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
48
+ }
49
+ function sourceSpan(sourceFile, node) {
50
+ const start = node.getStart(sourceFile);
51
+ const end = node.getEnd();
52
+ const position = sourceFile.getLineAndCharacterOfPosition(start);
53
+ return {
54
+ file: sourceFile.fileName,
55
+ start,
56
+ end,
57
+ line: position.line + 1,
58
+ column: position.character + 1
59
+ };
60
+ }
61
+ function refusal(sourceFile, node, code, message) {
62
+ return {
63
+ severity: "error",
64
+ code,
65
+ message,
66
+ span: sourceSpan(sourceFile, node),
67
+ origin: "source"
68
+ };
69
+ }
70
+ /** Whether `node` is an identifier occurrence evaluated as a value. */
71
+ function isValueIdentifier(node) {
72
+ const parent = node.parent;
73
+ if (parent === void 0) return true;
74
+ if (ts.isPropertyAccessExpression(parent)) return parent.expression === node;
75
+ if (ts.isQualifiedName(parent)) return false;
76
+ if (ts.isPropertyAssignment(parent)) return parent.name !== node;
77
+ if (ts.isShorthandPropertyAssignment(parent)) return parent.name === node;
78
+ if (ts.isBindingElement(parent)) return false;
79
+ if (ts.isVariableDeclaration(parent) || ts.isParameter(parent)) return false;
80
+ if (ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent) || ts.isClassDeclaration(parent) || ts.isClassExpression(parent) || ts.isMethodDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isGetAccessorDeclaration(parent) || ts.isSetAccessorDeclaration(parent)) return false;
81
+ if (ts.isImportClause(parent) || ts.isImportSpecifier(parent) || ts.isNamespaceImport(parent) || ts.isImportEqualsDeclaration(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent)) return false;
82
+ if (ts.isLabeledStatement(parent)) return false;
83
+ if (ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) return false;
84
+ if (ts.isJsxAttribute(parent) || ts.isJsxNamespacedName(parent) || ts.isMetaProperty(parent)) return false;
85
+ return true;
86
+ }
87
+ /** Collect the M03-B §6 context-sensitive constructs (JSX interiors excluded). */
88
+ function collectContextRefusals(sourceFile, root, diagnostics) {
89
+ const visit = (node) => {
90
+ if (isJsxNode(node)) return;
91
+ if (node.kind === ts.SyntaxKind.ThisKeyword) {
92
+ diagnostics.push(refusal(sourceFile, node, "OEIR_UNSUPPORTED_THIS", "a function component has no `this`; use the props parameter"));
93
+ return;
94
+ }
95
+ if (node.kind === ts.SyntaxKind.SuperKeyword) {
96
+ diagnostics.push(refusal(sourceFile, node, "OEIR_UNSUPPORTED_SUPER", "`super` is not part of the model"));
97
+ return;
98
+ }
99
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.NewKeyword && node.name.text === "target") {
100
+ diagnostics.push(refusal(sourceFile, node, "OEIR_UNSUPPORTED_NEW_TARGET", "`new.target` is not part of the function-component model"));
101
+ return;
102
+ }
103
+ if (ts.isAwaitExpression(node)) {
104
+ diagnostics.push(refusal(sourceFile, node, "OEIR_AWAIT_OUTSIDE_ASYNC", "`await` is only admitted inside an async server component (M14); not in M03"));
105
+ return;
106
+ }
107
+ if (ts.isYieldExpression(node)) {
108
+ diagnostics.push(refusal(sourceFile, node, "OEIR_UNSUPPORTED_GENERATOR", "generators are not part of the function-component model"));
109
+ return;
110
+ }
111
+ if (ts.isIdentifier(node) && node.text === "arguments" && isValueIdentifier(node)) {
112
+ diagnostics.push(refusal(sourceFile, node, "OEIR_UNSUPPORTED_ARGUMENTS", "`arguments` is not part of the function-component model"));
113
+ return;
114
+ }
115
+ if (ts.isIdentifier(node) && node.text === "eval" && isValueIdentifier(node)) {
116
+ diagnostics.push(refusal(sourceFile, node, "OEIR_DYNAMIC_SCOPE", "eval introduces dynamic scope; forbidden by the static resolution model"));
117
+ return;
118
+ }
119
+ ts.forEachChild(node, visit);
120
+ };
121
+ visit(root);
122
+ }
123
+ const JAVASCRIPT_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
124
+ function replaceJsxReferences(sourceFile, root, options) {
125
+ const replaced = /* @__PURE__ */ new Set();
126
+ const spans = [];
127
+ const diagnostics = [];
128
+ const transformer = (context) => {
129
+ const visit = (node) => {
130
+ if (isJsxNode(node)) {
131
+ const reference = options.recipeReference(node);
132
+ if (reference === void 0) {
133
+ diagnostics.push(refusal(sourceFile, node, "OEIR_RECIPE_REFERENCE_MISSING", "the JSX node has no recipe reference: the caller must create the recipe in the same walk"));
134
+ return node;
135
+ }
136
+ if (!JAVASCRIPT_IDENTIFIER.test(reference.callee)) {
137
+ diagnostics.push(refusal(sourceFile, node, "OEIR_RECIPE_CALLEE_INVALID", `recipe reference callee '${reference.callee}' is not a valid JavaScript identifier`));
138
+ return node;
139
+ }
140
+ spans.push({
141
+ start: node.getStart(sourceFile),
142
+ end: node.getEnd()
143
+ });
144
+ const call = ts.factory.createCallExpression(ts.factory.createIdentifier(reference.callee), void 0, [ts.factory.createStringLiteral(reference.id)]);
145
+ const positioned = ts.setTextRange(call, node);
146
+ replaced.add(positioned);
147
+ return positioned;
148
+ }
149
+ const erased = eraseTypeScriptSyntax(node, visit);
150
+ if (erased !== void 0) return erased;
151
+ return ts.visitEachChild(node, visit, context);
152
+ };
153
+ return (node) => ts.visitNode(node, visit);
154
+ };
155
+ const result = ts.transform(root, [transformer]);
156
+ options.lifecycle?.created?.();
157
+ return {
158
+ root: result.transformed[0] ?? root,
159
+ replaced,
160
+ spans,
161
+ diagnostics,
162
+ dispose: () => {
163
+ try {
164
+ result.dispose();
165
+ } finally {
166
+ options.lifecycle?.disposed?.();
167
+ }
168
+ }
169
+ };
170
+ }
171
+ /** FNV-1a over the authored text; only makes the marker namespace compile-specific. */
172
+ function hashText(text) {
173
+ let hash = 2166136261;
174
+ for (let index = 0; index < text.length; index++) {
175
+ hash ^= text.charCodeAt(index);
176
+ hash = Math.imul(hash, 16777619) >>> 0;
177
+ }
178
+ return hash.toString(36);
179
+ }
180
+ /**
181
+ * The marker namespace for one source file. Namespace is extended while it
182
+ * occurs in the authored text, so an author comment can never collide with a
183
+ * synthetic marker (I-0 rule; regression-tested by the prototype).
184
+ */
185
+ function markerNamespaceFor(sourceFile) {
186
+ let namespace = `${MARKER_PREFIX}${hashText(sourceFile.text)}_`;
187
+ while (sourceFile.text.includes(namespace)) namespace += "x";
188
+ return namespace;
189
+ }
190
+ /** One pass over the printed text; anything that is not a namespace marker is untouched. */
191
+ function scanLoweringMarkers(markedText, namespace, expectedIds) {
192
+ const diagnostics = [];
193
+ const occurrences = [];
194
+ const escaped = namespace.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
195
+ const pattern = new RegExp(`/\\*${escaped}([se])(\\d+)\\*/`, "g");
196
+ for (const match of markedText.matchAll(pattern)) {
197
+ const start = match.index ?? 0;
198
+ occurrences.push({
199
+ kind: match[1],
200
+ id: Number(match[2]),
201
+ start,
202
+ end: start + match[0].length
203
+ });
204
+ }
205
+ const counts = /* @__PURE__ */ new Map();
206
+ for (const occurrence of occurrences) {
207
+ if (!expectedIds.has(occurrence.id)) {
208
+ diagnostics.push(`unknown marker id ${occurrence.id} in the printed output`);
209
+ continue;
210
+ }
211
+ const key = `${occurrence.kind}${occurrence.id}`;
212
+ counts.set(key, (counts.get(key) ?? 0) + 1);
213
+ }
214
+ for (const [key, count] of counts) if (count > 1) diagnostics.push(`marker ${key} appears ${count} times (expected exactly once)`);
215
+ for (const id of expectedIds) {
216
+ if (!counts.has(`s${id}`)) diagnostics.push(`start marker ${id} is missing`);
217
+ if (!counts.has(`e${id}`)) diagnostics.push(`end marker ${id} is missing`);
218
+ }
219
+ const starts = new Set(occurrences.filter((occurrence) => occurrence.kind === "s").map((o) => o.id));
220
+ const ends = new Set(occurrences.filter((occurrence) => occurrence.kind === "e").map((o) => o.id));
221
+ for (const id of starts) if (!ends.has(id)) diagnostics.push(`marker ${id} is unpaired (no end)`);
222
+ for (const id of ends) if (!starts.has(id)) diagnostics.push(`marker ${id} is unpaired (no start)`);
223
+ return {
224
+ occurrences,
225
+ diagnostics
226
+ };
227
+ }
228
+ /** Remove marker ranges and build a prefix-sum index for O(log n) lookups. */
229
+ function stripMarkers(markedText, ranges) {
230
+ const ordered = [...ranges].sort((left, right) => left.start - right.start);
231
+ const removed = [];
232
+ let removedTotal = 0;
233
+ for (const range of ordered) {
234
+ removed.push({
235
+ start: range.start,
236
+ end: range.end,
237
+ removedBefore: removedTotal
238
+ });
239
+ removedTotal += range.end - range.start;
240
+ }
241
+ let text = "";
242
+ let cursor = 0;
243
+ for (const range of ordered) {
244
+ text += markedText.slice(cursor, range.start);
245
+ cursor = range.end;
246
+ }
247
+ text += markedText.slice(cursor);
248
+ const toStripped = (markedOffset) => {
249
+ let low = 0;
250
+ let high = removed.length - 1;
251
+ let index = -1;
252
+ while (low <= high) {
253
+ const middle = low + high >> 1;
254
+ if (removed[middle].start < markedOffset) {
255
+ index = middle;
256
+ low = middle + 1;
257
+ } else high = middle - 1;
258
+ }
259
+ if (index < 0) return markedOffset;
260
+ const range = removed[index];
261
+ const inside = Math.min(markedOffset, range.end) - range.start;
262
+ return markedOffset - range.removedBefore - inside;
263
+ };
264
+ return {
265
+ text,
266
+ toStripped
267
+ };
268
+ }
269
+ /** `true` when the printed node has an authored position to map back to. */
270
+ function hasRealPosition(node) {
271
+ return node.pos >= 0 && node.end >= 0;
272
+ }
273
+ /**
274
+ * Capture the synthetic-comment state of every node in the expression before the
275
+ * transform runs. The transform and `TransformationResult.dispose()` clear the
276
+ * emit-node state of authored nodes, so pre-existing synthetic metadata is
277
+ * reinstated from this snapshot after disposal.
278
+ */
279
+ function snapshotSyntheticComments(root) {
280
+ const saved = [];
281
+ const visit = (node) => {
282
+ const leading = ts.getSyntheticLeadingComments(node);
283
+ const trailing = ts.getSyntheticTrailingComments(node);
284
+ if (leading !== void 0 || trailing !== void 0) saved.push({
285
+ node,
286
+ leading,
287
+ trailing
288
+ });
289
+ ts.forEachChild(node, visit);
290
+ };
291
+ visit(root);
292
+ return { restore: () => {
293
+ for (const entry of saved) {
294
+ ts.setSyntheticLeadingComments(entry.node, entry.leading);
295
+ ts.setSyntheticTrailingComments(entry.node, entry.trailing);
296
+ }
297
+ } };
298
+ }
299
+ /**
300
+ * Attach synthetic markers to one node start per expression/JSX node. The
301
+ * authored AST may be touched here (identity transforms keep authored nodes),
302
+ * so the caller MUST call `restore()`; it reinstates the exact previous
303
+ * synthetic-comment state and is safe when the printer throws.
304
+ */
305
+ function markAnchorTargets(root, replaced, namespace) {
306
+ const marked = [];
307
+ let nextId = 0;
308
+ const visit = (node, depth) => {
309
+ if (hasRealPosition(node) && (ts.isExpression(node) || isJsxNode(node))) {
310
+ const id = nextId++;
311
+ marked.push({
312
+ node,
313
+ id,
314
+ depth,
315
+ fromJsx: replaced.has(node)
316
+ });
317
+ ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${namespace}s${id}`, false);
318
+ ts.addSyntheticTrailingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `${namespace}e${id}`, false);
319
+ }
320
+ ts.forEachChild(node, (child) => visit(child, depth + 1));
321
+ };
322
+ visit(root, 0);
323
+ return {
324
+ root,
325
+ marked
326
+ };
327
+ }
328
+ /** Print the marked tree once and resolve every marker anchor. */
329
+ function printWithAnchors(sourceFile, markedTree, expressionSpan) {
330
+ const namespace = markerNamespaceFor(sourceFile);
331
+ {
332
+ const markedText = ts.createPrinter().printNode(ts.EmitHint.Expression, markedTree.root, sourceFile);
333
+ const scan = scanLoweringMarkers(markedText, namespace, new Set(markedTree.marked.map((entry) => entry.id)));
334
+ if (scan.diagnostics.length > 0) return {
335
+ text: markedText,
336
+ anchors: [],
337
+ diagnostics: [{
338
+ severity: "error",
339
+ code: "OEIR_LOWERING_MARKER",
340
+ message: `internal lowering marker failure: ${scan.diagnostics.join("; ")}`,
341
+ span: expressionSpan,
342
+ origin: "source"
343
+ }]
344
+ };
345
+ const starts = /* @__PURE__ */ new Map();
346
+ const ends = /* @__PURE__ */ new Map();
347
+ for (const occurrence of scan.occurrences) (occurrence.kind === "s" ? starts : ends).set(occurrence.id, occurrence);
348
+ const stripped = stripMarkers(markedText, scan.occurrences.map((occurrence) => ({
349
+ start: occurrence.start,
350
+ end: occurrence.end
351
+ })));
352
+ const anchors = [];
353
+ for (const entry of markedTree.marked) {
354
+ const startMarker = starts.get(entry.id);
355
+ const endMarker = ends.get(entry.id);
356
+ if (startMarker === void 0 || endMarker === void 0) continue;
357
+ let generatedStart = stripped.toStripped(startMarker.end);
358
+ let generatedEnd = stripped.toStripped(endMarker.start);
359
+ while (generatedStart < generatedEnd && /\s/.test(stripped.text[generatedStart] ?? "")) generatedStart += 1;
360
+ while (generatedEnd > generatedStart && /\s/.test(stripped.text[generatedEnd - 1] ?? "")) generatedEnd -= 1;
361
+ anchors.push({
362
+ generatedStart,
363
+ generatedEnd,
364
+ authoredStart: entry.node.getStart(sourceFile),
365
+ authoredEnd: entry.node.getEnd(),
366
+ depth: entry.depth,
367
+ kind: ts.SyntaxKind[entry.node.kind],
368
+ fromJsx: entry.fromJsx,
369
+ ...ts.isIdentifier(entry.node) ? { name: entry.node.text } : {}
370
+ });
371
+ }
372
+ return {
373
+ text: stripped.text,
374
+ anchors,
375
+ diagnostics: []
376
+ };
377
+ }
378
+ }
379
+ /** Generated line/column for an offset (1-based line, 0-based column). */
380
+ function generatedPosition(text, offset) {
381
+ let line = 1;
382
+ let lineStart = 0;
383
+ const clamped = Math.min(Math.max(offset, 0), text.length);
384
+ for (let index = 0; index < clamped; index++) if (text.charCodeAt(index) === 10) {
385
+ line += 1;
386
+ lineStart = index + 1;
387
+ }
388
+ return {
389
+ line,
390
+ column: clamped - lineStart
391
+ };
392
+ }
393
+ /** Authored line/column for an offset (1-based line, 0-based column). */
394
+ function authoredPosition(sourceFile, offset) {
395
+ const position = sourceFile.getLineAndCharacterOfPosition(Math.min(Math.max(offset, 0), sourceFile.text.length));
396
+ return {
397
+ line: position.line + 1,
398
+ column: position.character
399
+ };
400
+ }
401
+ /**
402
+ * Merge anchors into source-map segments (deepest node wins at one generated
403
+ * position — M03-I-0 rule 3) in the existing `EmissionSegment` convention.
404
+ */
405
+ function anchorsToSegments(anchors, loweredText, sourceFile) {
406
+ const byPosition = /* @__PURE__ */ new Map();
407
+ for (const anchor of anchors) {
408
+ const position = generatedPosition(loweredText, anchor.generatedStart);
409
+ const key = `${position.line}:${position.column}`;
410
+ const existing = byPosition.get(key);
411
+ if (existing === void 0 || anchor.depth > existing.depth) byPosition.set(key, anchor);
412
+ }
413
+ return [...byPosition.values()].sort((left, right) => left.generatedStart - right.generatedStart).map((anchor) => {
414
+ const generated = generatedPosition(loweredText, anchor.generatedStart);
415
+ const authored = authoredPosition(sourceFile, anchor.authoredStart);
416
+ return {
417
+ generatedLine: generated.line,
418
+ generatedColumn: generated.column,
419
+ sourceLine: authored.line,
420
+ sourceColumn: authored.column,
421
+ ...anchor.name === void 0 ? {} : { name: anchor.name }
422
+ };
423
+ });
424
+ }
425
+ /**
426
+ * Lower one authored expression to JavaScript text with JSX replaced by recipe
427
+ * references, returning node-start anchors and the replaced JSX authored spans.
428
+ *
429
+ * Fail-closed: any refusal (needs erasure, context-sensitive construct, missing
430
+ * recipe reference, marker failure) yields diagnostics and empty text/anchors;
431
+ * the caller must not emit anything for it. The `TransformationResult` is always
432
+ * disposed, and synthetic comment state is always restored.
433
+ */
434
+ function lowerExpressionText(sourceFile, expression, options) {
435
+ const diagnostics = [];
436
+ const expressionSpan = sourceSpan(sourceFile, expression);
437
+ collectContextRefusals(sourceFile, expression, diagnostics);
438
+ collectErasureBoundaryRefusals(sourceFile, expression, diagnostics);
439
+ if (diagnostics.length > 0) return {
440
+ text: "",
441
+ anchors: [],
442
+ replacedJsxSpans: [],
443
+ diagnostics
444
+ };
445
+ const comments = snapshotSyntheticComments(expression);
446
+ const replacement = replaceJsxReferences(sourceFile, expression, options);
447
+ let markedTree;
448
+ try {
449
+ if (replacement.diagnostics.length > 0) return {
450
+ text: "",
451
+ anchors: [],
452
+ replacedJsxSpans: [],
453
+ diagnostics: [...replacement.diagnostics]
454
+ };
455
+ markedTree = markAnchorTargets(replacement.root, replacement.replaced, markerNamespaceFor(sourceFile));
456
+ const printed = printWithAnchors(sourceFile, markedTree, expressionSpan);
457
+ return {
458
+ text: printed.text,
459
+ anchors: printed.anchors,
460
+ replacedJsxSpans: replacement.spans,
461
+ diagnostics: printed.diagnostics
462
+ };
463
+ } finally {
464
+ replacement.dispose();
465
+ comments.restore();
466
+ }
467
+ }
468
+ //#endregion
469
+ export { EXPRESSION_LOWERING_TRANSFORM_VERSION, anchorsToSegments, isJsxNode, lowerExpressionText, markerNamespaceFor, scanLoweringMarkers };