@openelement/compiler 1.0.0-alpha.15 → 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.
- package/package.json +3 -2
- package/src/compiler.d.ts +8 -6
- package/src/compiler.js +7 -6
- package/src/internal/compiler/compiled-artifact-class-candidates.d.ts +5 -30
- package/src/internal/compiler/compiled-artifact-class-candidates.js +18 -32
- package/src/internal/compiler/compiled-artifact-style-requests.d.ts +9 -7
- package/src/internal/compiler/compiled-artifact-style-requests.js +9 -7
- package/src/internal/compiler/plugin.d.ts +31 -50
- package/src/internal/compiler/plugin.js +41 -108
- package/src/internal/compiler/semantic-core/analyze-module.d.ts +1 -45
- package/src/internal/compiler/semantic-core/analyze-module.js +10 -405
- package/src/internal/compiler/semantic-core/attribute-classification.js +92 -0
- package/src/internal/compiler/semantic-core/compiler-diagnostics.js +2 -16
- package/src/internal/compiler/semantic-core/expression-lowering.js +469 -0
- package/src/internal/compiler/semantic-core/expression-registry.js +165 -0
- package/src/internal/compiler/semantic-core/function-frontend.js +1229 -0
- package/src/internal/compiler/semantic-core/island-policy-statement.js +52 -0
- package/src/internal/compiler/semantic-core/jsx-module-id.d.ts +4 -0
- package/src/internal/compiler/semantic-core/jsx-module-id.js +7 -0
- package/src/internal/compiler/semantic-core/lower-program.d.ts +51 -0
- package/src/internal/compiler/semantic-core/lower-program.js +186 -90
- package/src/internal/compiler/semantic-core/module-analysis.d.ts +28 -5
- package/src/internal/compiler/semantic-core/module-analysis.js +16 -17
- package/src/internal/compiler/semantic-core/parse-module.js +16 -16
- package/src/internal/compiler/semantic-core/scope-resolution.d.ts +208 -0
- package/src/internal/compiler/semantic-core/scope-resolution.js +1121 -0
- package/src/internal/compiler/semantic-core/server-component.d.ts +22 -7
- package/src/internal/compiler/semantic-core/server-component.js +163 -57
- package/src/internal/compiler/semantic-core/type-erasure.js +156 -0
- package/src/internal/compiler/semantic-ir/generated-element/compile.d.ts +61 -0
- package/src/internal/compiler/semantic-ir/generated-element/compile.js +137 -0
- package/src/internal/compiler/semantic-ir/generated-element/contract.d.ts +201 -0
- package/src/internal/compiler/semantic-ir/generated-element/contract.js +147 -0
- package/src/internal/compiler/semantic-ir/generated-element/emit.js +452 -0
- package/src/internal/compiler/semantic-ir/generated-element/site.js +1195 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/claim-emission.js +1372 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/codegen-literals.js +31 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/component-emission.js +647 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/emission.js +388 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/generate.js +395 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/instance-emission.js +865 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/mount-emission.js +960 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/server-emission.js +1011 -0
- package/src/internal/compiler/semantic-ir/generated-leaf/structure.js +714 -0
- package/src/internal/compiler/style-requests.d.ts +0 -8
- package/src/internal/compiler/style-requests.js +1 -14
- package/src/internal/compiler/semantic-core/compile.d.ts +0 -47
- package/src/internal/compiler/semantic-core/compile.js +0 -100
- package/src/internal/compiler/semantic-core/emit-module.js +0 -317
- package/src/internal/compiler/semantic-core/emit-program.js +0 -141
- package/src/internal/compiler/semantic-core/style-imports.js +0 -87
|
@@ -69,14 +69,6 @@ export declare function clearStyleRequests(): void;
|
|
|
69
69
|
* can only fail closed at the intercept — never emit an unscoped asset.
|
|
70
70
|
*/
|
|
71
71
|
export declare function styleRequestModuleId(importerId: string, specifier: string, scopeTag?: string): string;
|
|
72
|
-
/**
|
|
73
|
-
* The light-root scope tag of a compiled Part Program — undefined for a
|
|
74
|
-
* shadow-root program, whose sheets ship exactly as authored (they already
|
|
75
|
-
* have a boundary). One reader for the fact, shared by both host bindings of
|
|
76
|
-
* the compiled-element transform (the build plugin and the dev/HMR plugin)
|
|
77
|
-
* and by the compiled-artifact read.
|
|
78
|
-
*/
|
|
79
|
-
export declare function lightRootScopeTag(program: unknown): string | undefined;
|
|
80
72
|
/**
|
|
81
73
|
* The sheet file's absolute path for one authored edge: the importing
|
|
82
74
|
* module's directory joined with the authored specifier. Relative specifiers
|
|
@@ -75,19 +75,6 @@ function styleRequestModuleId(importerId, specifier, scopeTag) {
|
|
|
75
75
|
return scope === void 0 ? file : `${file}${SCOPE_KEY_SEPARATOR}${scope}`;
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
|
-
* The light-root scope tag of a compiled Part Program — undefined for a
|
|
79
|
-
* shadow-root program, whose sheets ship exactly as authored (they already
|
|
80
|
-
* have a boundary). One reader for the fact, shared by both host bindings of
|
|
81
|
-
* the compiled-element transform (the build plugin and the dev/HMR plugin)
|
|
82
|
-
* and by the compiled-artifact read.
|
|
83
|
-
*/
|
|
84
|
-
function lightRootScopeTag(program) {
|
|
85
|
-
const candidate = program;
|
|
86
|
-
const tag = candidate?.tag;
|
|
87
|
-
if (typeof tag !== "string" || tag === "") return void 0;
|
|
88
|
-
return candidate?.root?.kind === "light" ? tag : void 0;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
78
|
* The sheet file's absolute path for one authored edge: the importing
|
|
92
79
|
* module's directory joined with the authored specifier. Relative specifiers
|
|
93
80
|
* only (the compiler refuses bare ones), so the join is total. Parent
|
|
@@ -106,4 +93,4 @@ function styleRequestFile(importerId, specifier) {
|
|
|
106
93
|
return segments.join("/");
|
|
107
94
|
}
|
|
108
95
|
//#endregion
|
|
109
|
-
export { clearStyleRequests, getStyleRequest, hasStyleImporter,
|
|
96
|
+
export { clearStyleRequests, getStyleRequest, hasStyleImporter, registerStyleRequest, styleEdgesForFile, styleRequestFile, styleRequestModuleId, styleRequestsForImporter };
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { SemanticCoreOptions } from "./module-analysis.js";
|
|
2
|
-
import { CompiledElementSourceMap } from "./source-map.js";
|
|
3
|
-
import { CompiledElementError, ElementCompilerDiagnostic } from "./compiler-diagnostics.js";
|
|
4
|
-
import { PartProgramV2 } 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: PartProgramV2;
|
|
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
|
-
* The component's statically admitted class tokens (alpha15 S lane): every
|
|
30
|
-
* whitespace-separated token of a compile-time `class` value the lowering
|
|
31
|
-
* admitted. Opaque strings — the compiler attaches no Tailwind meaning to
|
|
32
|
-
* them; the host build forwards them to the official Tailwind compiler as
|
|
33
|
-
* explicit candidates and emits the generated CSS as an external asset.
|
|
34
|
-
*/
|
|
35
|
-
classCandidates?: readonly string[];
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Compile one authored TSX module into the compiled Part Program module.
|
|
39
|
-
* `fileName` is used for diagnostics and the emitted source map only —
|
|
40
|
-
* filesystem resolution is the caller's job. Fails closed with a
|
|
41
|
-
* {@link CompiledElementError} carrying the ordered OEC diagnostics.
|
|
42
|
-
* `options.staticSidecars` admits host-declared sidecar policy statements
|
|
43
|
-
* (e.g. an island delivery descriptor); the default core admits none.
|
|
44
|
-
*/
|
|
45
|
-
export declare function compileElementProgram(source: string, fileName: string, options?: SemanticCoreOptions): CompileElementResult;
|
|
46
|
-
//#endregion
|
|
47
|
-
export { CompiledElementError, type ElementCompilerDiagnostic };
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import { createModuleIntrinsicBindings } from "./module-analysis.js";
|
|
2
|
-
import { analyzeCompiledModule } from "./analyze-module.js";
|
|
3
|
-
import { CompiledElementError, failAt, parseDiagnostic } from "./compiler-diagnostics.js";
|
|
4
|
-
import { buildPartProgram } from "./emit-program.js";
|
|
5
|
-
import { Lowering } from "./lower-program.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 v2 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 Block 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(syntaxDiagnostics.map((diagnostic) => parseDiagnostic(sf, diagnostic)));
|
|
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
|
-
const classCandidates = [...lowering.classCandidates];
|
|
91
|
-
return {
|
|
92
|
-
code,
|
|
93
|
-
map,
|
|
94
|
-
program,
|
|
95
|
-
...styleRequests.length === 0 ? {} : { styleRequests },
|
|
96
|
-
...classCandidates.length === 0 ? {} : { classCandidates }
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
//#endregion
|
|
100
|
-
export { CompiledElementError, compileElementProgram };
|
|
@@ -1,317 +0,0 @@
|
|
|
1
|
-
import { isCompileTimeOnlyImport } from "./module-analysis.js";
|
|
2
|
-
import { SYNTHESIZED_COMPUTED_LOCAL } from "./lower-program.js";
|
|
3
|
-
import { SourceMapSegmentBuilder } from "./source-map.js";
|
|
4
|
-
import ts from "typescript";
|
|
5
|
-
import { COMPILED_MODULE_ABI_VERSION, PART_PROGRAM_VERSION } from "@openelement/protocol/part-program";
|
|
6
|
-
//#region src/internal/compiler/semantic-core/emit-module.ts
|
|
7
|
-
/**
|
|
8
|
-
* Generated-module emission for the compiled grammar (#1473 split): renders
|
|
9
|
-
* the compiled module text with
|
|
10
|
-
* verbatim copies, synthesized statics and forwarding handlers, each mapped
|
|
11
|
-
* through a real Source Map v3 segment.
|
|
12
|
-
*/
|
|
13
|
-
/**
|
|
14
|
-
* Copy one source import statement into the generated module. Compile-time-
|
|
15
|
-
* only intrinsic bindings (element/property from '@openelement/element') are
|
|
16
|
-
* stripped: the decorators they powered are erased by compilation and the
|
|
17
|
-
* runtime package exports neither, so keeping them would emit an unresolvable
|
|
18
|
-
* runtime import. A statement whose entire clause stripped away is dropped.
|
|
19
|
-
*/
|
|
20
|
-
function rewriteImportForGeneratedModule(sf, statement) {
|
|
21
|
-
if (!ts.isStringLiteral(statement.moduleSpecifier)) return statement.getText(sf);
|
|
22
|
-
const module = statement.moduleSpecifier.text;
|
|
23
|
-
const clause = statement.importClause;
|
|
24
|
-
if (!clause) return statement.getText(sf);
|
|
25
|
-
const bindings = clause.namedBindings;
|
|
26
|
-
if (!bindings || !ts.isNamedImports(bindings)) return statement.getText(sf);
|
|
27
|
-
const kept = bindings.elements.filter((element) => !isCompileTimeOnlyImport(module, element.propertyName?.text ?? element.name.text));
|
|
28
|
-
if (kept.length === bindings.elements.length) return statement.getText(sf);
|
|
29
|
-
const parts = [];
|
|
30
|
-
if (clause.name) parts.push(clause.name.text);
|
|
31
|
-
if (kept.length > 0) {
|
|
32
|
-
const specifiers = kept.map((element) => `${element.isTypeOnly ? "type " : ""}${element.propertyName ? `${element.propertyName.text} as ` : ""}${element.name.text}`);
|
|
33
|
-
parts.push(`{ ${specifiers.join(", ")} }`);
|
|
34
|
-
}
|
|
35
|
-
if (parts.length === 0) return null;
|
|
36
|
-
return `import ${clause.isTypeOnly ? "type " : ""}${parts.join(", ")} from '${module}';`;
|
|
37
|
-
}
|
|
38
|
-
function encodeBase64(value) {
|
|
39
|
-
const bytes = new TextEncoder().encode(value);
|
|
40
|
-
let binary = "";
|
|
41
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
42
|
-
return btoa(binary);
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* The platform lifecycle callbacks whose authored bodies the compiler wraps
|
|
46
|
-
* in the error-boundary capture contract. These are the callbacks the platform
|
|
47
|
-
* invokes outside any application stack — a throw inside them would otherwise
|
|
48
|
-
* escape straight to window.onerror with no boundary the way a render throw
|
|
49
|
-
* in React reaches the nearest error boundary. Everything else (event
|
|
50
|
-
* handlers, plain author methods) keeps the verbatim emission: those already
|
|
51
|
-
* run inside caller stacks, and the runtime capture points (the facade
|
|
52
|
-
* property setter, the kernel update sink) own their failure modes.
|
|
53
|
-
*/
|
|
54
|
-
const CAPTURE_WRAPPED_LIFECYCLE_CALLBACKS = /* @__PURE__ */ new Set([
|
|
55
|
-
"connectedCallback",
|
|
56
|
-
"disconnectedCallback",
|
|
57
|
-
"adoptedCallback",
|
|
58
|
-
"attributeChangedCallback",
|
|
59
|
-
"formAssociatedCallback",
|
|
60
|
-
"formResetCallback",
|
|
61
|
-
"formStateRestoreCallback"
|
|
62
|
-
]);
|
|
63
|
-
function generatedHandlerText(handler) {
|
|
64
|
-
const action = handler.action;
|
|
65
|
-
if (action.kind === "method") return ` ${handler.name}(): void { this.${action.name}(); }`;
|
|
66
|
-
if (action.kind === "call") return ` ${handler.name}(): void { this.${action.name}(); }`;
|
|
67
|
-
if (action.kind === "increment") return ` ${handler.name}(): void { this.${action.signal}++; }`;
|
|
68
|
-
if (action.kind === "decrement") return ` ${handler.name}(): void { this.${action.signal}--; }`;
|
|
69
|
-
if (action.kind === "add") return ` ${handler.name}(): void { this.${action.signal} += ${action.value}; }`;
|
|
70
|
-
if (action.kind === "subtract") return ` ${handler.name}(): void { this.${action.signal} -= ${action.value}; }`;
|
|
71
|
-
if (action.kind === "assign") return ` ${handler.name}(): void { this.${action.signal} = ${JSON.stringify(action.value)}; }`;
|
|
72
|
-
return ` ${handler.name}(): void {}`;
|
|
73
|
-
}
|
|
74
|
-
/** Render the compiled module text and its inline Source Map v3. */
|
|
75
|
-
function emitCompiledModule(input) {
|
|
76
|
-
const { sf, source, fileName, analyzed, lowering, program, programJson, propertiesJson, metadataJson, observedJson } = input;
|
|
77
|
-
const { fields, methods, render, stylesText, stylesNode, stylesTypeText, passthroughStatements, decorator, classNode, tag, className, isDefaultExport, openElementLocalName, delegatesFocus, formAssociated } = analyzed;
|
|
78
|
-
const segments = new SourceMapSegmentBuilder();
|
|
79
|
-
const codeLines = [];
|
|
80
|
-
const nodePosition = (node) => {
|
|
81
|
-
const position = sf.getLineAndCharacterOfPosition(node.getStart(sf));
|
|
82
|
-
return {
|
|
83
|
-
line: position.line + 1,
|
|
84
|
-
column: position.character
|
|
85
|
-
};
|
|
86
|
-
};
|
|
87
|
-
const mapLineAt = (generatedLine, generatedColumn, node, name) => {
|
|
88
|
-
const position = nodePosition(node);
|
|
89
|
-
segments.add({
|
|
90
|
-
generatedLine,
|
|
91
|
-
generatedColumn,
|
|
92
|
-
sourceLine: position.line,
|
|
93
|
-
sourceColumn: position.column,
|
|
94
|
-
...name === void 0 ? {} : { name }
|
|
95
|
-
});
|
|
96
|
-
};
|
|
97
|
-
/**
|
|
98
|
-
* Continuation lines of a verbatim-copied block: text line i is authored
|
|
99
|
-
* line (start + i) verbatim, so generated column (prefix + whitespace) maps
|
|
100
|
-
* to authored column (whitespace) — the first non-whitespace character.
|
|
101
|
-
*/
|
|
102
|
-
const mapContinuationLines = (text, firstGeneratedLine, node, prefix) => {
|
|
103
|
-
const position = nodePosition(node);
|
|
104
|
-
const lines = text.split("\n");
|
|
105
|
-
for (let index = 1; index < lines.length; index++) {
|
|
106
|
-
const whitespace = /^\s*/.exec(lines[index])[0].length;
|
|
107
|
-
segments.add({
|
|
108
|
-
generatedLine: firstGeneratedLine + index,
|
|
109
|
-
generatedColumn: prefix + whitespace,
|
|
110
|
-
sourceLine: position.line + index,
|
|
111
|
-
sourceColumn: whitespace
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
/** Push a line or block: multiline text always splits so codeLines.length tracks emitted lines. */
|
|
116
|
-
const push = (text) => {
|
|
117
|
-
for (const line of text.split("\n")) codeLines.push(line);
|
|
118
|
-
};
|
|
119
|
-
/** Push a verbatim copy of a node's text (optionally line-prefixed). */
|
|
120
|
-
const pushVerbatim = (text, node, prefix = "", name) => {
|
|
121
|
-
const firstGeneratedLine = codeLines.length + 1;
|
|
122
|
-
push(text.split("\n").map((line) => prefix + line).join("\n"));
|
|
123
|
-
mapLineAt(firstGeneratedLine, prefix.length, node, name);
|
|
124
|
-
mapContinuationLines(text, firstGeneratedLine, node, prefix.length);
|
|
125
|
-
};
|
|
126
|
-
/** Push one synthesized line embedding a verbatim value, mapping both. */
|
|
127
|
-
const pushDerivedLine = (head, valueText, tail, nameNode, nameColumn, name, valueNode) => {
|
|
128
|
-
const generatedLine = codeLines.length + 1;
|
|
129
|
-
push(`${head}${valueText}${tail}`);
|
|
130
|
-
mapLineAt(generatedLine, nameColumn, nameNode, name);
|
|
131
|
-
if (valueNode !== void 0) {
|
|
132
|
-
mapLineAt(generatedLine, head.length, valueNode);
|
|
133
|
-
mapContinuationLines(valueText, generatedLine, valueNode, 0);
|
|
134
|
-
}
|
|
135
|
-
};
|
|
136
|
-
/** Push a synthesized block whose first line traces to `node`. */
|
|
137
|
-
const pushDerivedBlock = (text, node, name) => {
|
|
138
|
-
const firstGeneratedLine = codeLines.length + 1;
|
|
139
|
-
push(text);
|
|
140
|
-
mapLineAt(firstGeneratedLine, 0, node, name);
|
|
141
|
-
};
|
|
142
|
-
push(`// <auto-generated by open:compiled-element; part-program format ${PART_PROGRAM_VERSION} / module ABI ${COMPILED_MODULE_ABI_VERSION} - do not edit>`);
|
|
143
|
-
for (const statement of sf.statements) {
|
|
144
|
-
if (!ts.isImportDeclaration(statement)) continue;
|
|
145
|
-
const rewritten = rewriteImportForGeneratedModule(sf, statement);
|
|
146
|
-
if (rewritten !== null) pushVerbatim(rewritten, statement);
|
|
147
|
-
}
|
|
148
|
-
let readonlySignalLocal = null;
|
|
149
|
-
for (const statement of sf.statements) {
|
|
150
|
-
if (!ts.isImportDeclaration(statement)) continue;
|
|
151
|
-
if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "@openelement/element") continue;
|
|
152
|
-
const bindings = statement.importClause?.namedBindings;
|
|
153
|
-
if (!bindings || !ts.isNamedImports(bindings)) continue;
|
|
154
|
-
for (const element of bindings.elements) if ((element.propertyName?.text ?? element.name.text) === "ReadonlySignal") readonlySignalLocal = element.name.text;
|
|
155
|
-
}
|
|
156
|
-
const needsComputedTypes = fields.some((field) => field.computed);
|
|
157
|
-
const signalType = readonlySignalLocal ?? "ReadonlySignal";
|
|
158
|
-
if (needsComputedTypes && readonlySignalLocal === null) push(`import type { ReadonlySignal } from '@openelement/element';`);
|
|
159
|
-
if (lowering.synthesizedFields.length > 0 && !lowering.sourceBindsComputed) push(`import { computed as ${SYNTHESIZED_COMPUTED_LOCAL} } from '@openelement/element';`);
|
|
160
|
-
push("");
|
|
161
|
-
for (const statement of passthroughStatements) pushVerbatim(statement.getText(sf), statement);
|
|
162
|
-
if (passthroughStatements.length > 0) push("");
|
|
163
|
-
const programStartLine = codeLines.length + 1;
|
|
164
|
-
pushDerivedBlock(`const __partProgram = ${programJson};`, render);
|
|
165
|
-
const programJsonPosition = (offset) => {
|
|
166
|
-
const before = programJson.slice(0, offset);
|
|
167
|
-
return {
|
|
168
|
-
line: programStartLine + before.split("\n").length - 1,
|
|
169
|
-
column: offset - (before.lastIndexOf("\n") + 1)
|
|
170
|
-
};
|
|
171
|
-
};
|
|
172
|
-
const tagOffset = programJson.indexOf(`"tag": ${JSON.stringify(tag)}`);
|
|
173
|
-
if (tagOffset >= 0) {
|
|
174
|
-
const at = programJsonPosition(tagOffset);
|
|
175
|
-
mapLineAt(at.line, at.column, decorator);
|
|
176
|
-
}
|
|
177
|
-
push("");
|
|
178
|
-
pushDerivedBlock(`const __compiledProperties = ${propertiesJson};`, classNode.name);
|
|
179
|
-
push("");
|
|
180
|
-
pushDerivedBlock(`const __elementMetadata = ${metadataJson};`, classNode.name);
|
|
181
|
-
push("");
|
|
182
|
-
pushDerivedBlock(`const __observedAttributes: string[] = ${observedJson};`, classNode.name);
|
|
183
|
-
push("");
|
|
184
|
-
pushDerivedBlock("const __compiledProps = {", classNode.name);
|
|
185
|
-
for (const field of fields) {
|
|
186
|
-
if (field.computed) {
|
|
187
|
-
const computedLine = codeLines.length + 1;
|
|
188
|
-
push(` ${field.name}: { type: Object, default: undefined, reflect: false, attribute: false },`);
|
|
189
|
-
mapLineAt(computedLine, 2, field.node.name, field.name);
|
|
190
|
-
continue;
|
|
191
|
-
}
|
|
192
|
-
const attribute = field.attribute === null ? "false" : JSON.stringify(field.attribute);
|
|
193
|
-
pushDerivedLine(` ${field.name}: { type: ${field.typeConstructor}, default: `, field.initializerText, `, reflect: ${field.reflect}, attribute: ${attribute} },`, field.node.name, 2, field.name, field.node.initializer);
|
|
194
|
-
}
|
|
195
|
-
push("};");
|
|
196
|
-
push("");
|
|
197
|
-
const classLine = `export ${isDefaultExport ? "default " : ""}class ${className} extends ${openElementLocalName} {`;
|
|
198
|
-
push(classLine);
|
|
199
|
-
mapLineAt(codeLines.length, classLine.indexOf(className), classNode.name, className);
|
|
200
|
-
push([
|
|
201
|
-
" static __partProgram: typeof __partProgram = __partProgram;",
|
|
202
|
-
" static __compiledProperties: typeof __compiledProperties = __compiledProperties;",
|
|
203
|
-
" static __elementMetadata: typeof __elementMetadata = __elementMetadata;",
|
|
204
|
-
" static props: typeof __compiledProps = __compiledProps;",
|
|
205
|
-
" static observedAttributes: typeof __observedAttributes = __observedAttributes;"
|
|
206
|
-
].join("\n"));
|
|
207
|
-
if (delegatesFocus) push(" static override delegatesFocus: boolean = true;");
|
|
208
|
-
if (formAssociated) push(" static override formAssociated: boolean = true;");
|
|
209
|
-
if (analyzed.rootKind !== "light" && lowering.classCandidates.size > 0) {
|
|
210
|
-
push(" static __oeUtilityClasses: boolean = true;");
|
|
211
|
-
push(` static __oeClassCandidates: readonly string[] = ${JSON.stringify([...lowering.classCandidates])};`);
|
|
212
|
-
}
|
|
213
|
-
const computedFields = fields.filter((field) => field.computed);
|
|
214
|
-
if (computedFields.length > 0) {
|
|
215
|
-
const plainFieldByName = new Map(fields.filter((field) => !field.computed).map((field) => [field.name, field]));
|
|
216
|
-
const signalValueType = (name) => {
|
|
217
|
-
const plain = plainFieldByName.get(name);
|
|
218
|
-
const annotated = plain?.typeText.replace(/^:\s*/, "").trim() ?? "";
|
|
219
|
-
if (annotated) return annotated;
|
|
220
|
-
switch (plain?.typeConstructor) {
|
|
221
|
-
case "String": return "string";
|
|
222
|
-
case "Number": return "number";
|
|
223
|
-
case "Boolean": return "boolean";
|
|
224
|
-
case "Array": return "unknown[]";
|
|
225
|
-
case "Object": return "Record<string, unknown>";
|
|
226
|
-
default: return "unknown";
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
const computedReturnType = (field) => {
|
|
230
|
-
return field.typeText.replace(/^:\s*/, "").trim() || `${signalType}<unknown>`;
|
|
231
|
-
};
|
|
232
|
-
push(" static __computedFields: {");
|
|
233
|
-
for (const field of computedFields) {
|
|
234
|
-
const params = field.computed.deps.map((dep) => `${dep}: ${signalType}<${signalValueType(dep)}>`).join(", ");
|
|
235
|
-
push(` ${field.name}: (__s: { ${params} }) => ${computedReturnType(field)};`);
|
|
236
|
-
}
|
|
237
|
-
push(" } = {");
|
|
238
|
-
for (const field of computedFields) {
|
|
239
|
-
const factoryLine = codeLines.length + 1;
|
|
240
|
-
push(` ${field.name}: ${field.computed.factoryText},`);
|
|
241
|
-
mapLineAt(factoryLine, 4, field.node.name, field.name);
|
|
242
|
-
mapLineAt(factoryLine, 4 + field.name.length + 2, field.node.initializer);
|
|
243
|
-
mapContinuationLines(field.computed.factoryText, factoryLine, field.computed.body, 0);
|
|
244
|
-
}
|
|
245
|
-
push(" };");
|
|
246
|
-
}
|
|
247
|
-
if (stylesText !== void 0 && stylesNode !== void 0) {
|
|
248
|
-
const stylesHead = ` static override styles${stylesTypeText ?? ""} = `;
|
|
249
|
-
const stylesLine = codeLines.length + 1;
|
|
250
|
-
push(`${stylesHead}${stylesText};`);
|
|
251
|
-
mapLineAt(stylesLine, stylesHead.length, stylesNode);
|
|
252
|
-
mapContinuationLines(stylesText, stylesLine, stylesNode, 0);
|
|
253
|
-
}
|
|
254
|
-
for (const field of fields) {
|
|
255
|
-
if (field.computed) continue;
|
|
256
|
-
const accessibility = field.accessibility ? `${field.accessibility} ` : "";
|
|
257
|
-
pushDerivedLine(` ${accessibility}${field.name}${field.typeText} = `, field.initializerText, ";", field.node.name, 2 + accessibility.length, field.name, field.node.initializer);
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Emit one platform lifecycle callback with the boundary-capture wrapper
|
|
261
|
-
* (P2: the wrapper is a compile-time cost; the runtime delta is one method
|
|
262
|
-
* call on the failure path only). The body bytes and their columns are
|
|
263
|
-
* emitted UNCHANGED from the verbatim copy — body line i keeps the authored
|
|
264
|
-
* text at the authored column, so the continuation mapping stays
|
|
265
|
-
* byte-identical to what `pushVerbatim` produced; the inserted `try {` and
|
|
266
|
-
* `} catch` lines are pure scaffolding and stay unmapped (consumers fall
|
|
267
|
-
* through to the nearest real construct, the method's own first-line
|
|
268
|
-
* mapping). Prior art (P7): React error boundaries capture lifecycle and
|
|
269
|
-
* render throws at runtime; the compiled difference is that this capture
|
|
270
|
-
* point is materialized once, at compile time, around exactly the platform
|
|
271
|
-
* entry points — `_captureError` on the base class then performs the same
|
|
272
|
-
* nearest-boundary climb React's component stack does.
|
|
273
|
-
*/
|
|
274
|
-
const pushLifecycleCapture = (method, name) => {
|
|
275
|
-
const body = method.body;
|
|
276
|
-
const methodText = method.getText(sf);
|
|
277
|
-
const header = methodText.slice(0, body.getStart(sf) - method.getStart(sf));
|
|
278
|
-
const bodyText = methodText.slice(header.length + 1, methodText.length - 1).replace(/\n[ \t]*$/, "");
|
|
279
|
-
const firstGeneratedLine = codeLines.length + 1;
|
|
280
|
-
push(` ${header}{`);
|
|
281
|
-
mapLineAt(firstGeneratedLine, 2, method, name);
|
|
282
|
-
push(` try {${bodyText}`);
|
|
283
|
-
mapContinuationLines(bodyText, firstGeneratedLine + 1, body, 0);
|
|
284
|
-
push(` } catch (error) { if (!this._captureError(error)) throw error; }`);
|
|
285
|
-
push(` }`);
|
|
286
|
-
};
|
|
287
|
-
for (const method of methods) {
|
|
288
|
-
const name = method.name.text;
|
|
289
|
-
if (CAPTURE_WRAPPED_LIFECYCLE_CALLBACKS.has(name)) {
|
|
290
|
-
pushLifecycleCapture(method, name);
|
|
291
|
-
continue;
|
|
292
|
-
}
|
|
293
|
-
pushVerbatim(method.getText(sf), method, " ", name);
|
|
294
|
-
}
|
|
295
|
-
for (const handler of lowering.generatedHandlers) {
|
|
296
|
-
const handlerLine = codeLines.length + 1;
|
|
297
|
-
push(generatedHandlerText(handler));
|
|
298
|
-
mapLineAt(handlerLine, 2, handler.node);
|
|
299
|
-
}
|
|
300
|
-
push(" render(): never {");
|
|
301
|
-
mapLineAt(codeLines.length, 2, render, "render");
|
|
302
|
-
push(` throw new Error(
|
|
303
|
-
'[open:compiled-element] ${tag} is compiled to a Part Program; the runtime JSX render path is not available.',
|
|
304
|
-
);
|
|
305
|
-
}`);
|
|
306
|
-
push("}");
|
|
307
|
-
push("");
|
|
308
|
-
push("export { __partProgram, __elementMetadata };");
|
|
309
|
-
const map = segments.build(fileName, source, program.sourceMap);
|
|
310
|
-
push(`//# sourceMappingURL=data:application/json;base64,${encodeBase64(JSON.stringify(map))}`);
|
|
311
|
-
return {
|
|
312
|
-
code: codeLines.join("\n") + "\n",
|
|
313
|
-
map
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
//#endregion
|
|
317
|
-
export { emitCompiledModule };
|
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
import { CompiledElementError, sourceRange } from "./compiler-diagnostics.js";
|
|
2
|
-
import { PART_PROGRAM_VERSION, validatePartProgram } from "@openelement/protocol/part-program";
|
|
3
|
-
//#region src/internal/compiler/semantic-core/emit-program.ts
|
|
4
|
-
/**
|
|
5
|
-
* Path-addressed fixed Parts can use DOM child indexes only before any dynamic
|
|
6
|
-
* anchor. An anchor expands to multiple DOM nodes, so accepting a fixed sink
|
|
7
|
-
* after one would make server output, fresh creation and claim address
|
|
8
|
-
* different nodes. The v1 location id remains the identity; this guard keeps
|
|
9
|
-
* the path retained for seed consumers safe until they consume that id.
|
|
10
|
-
*
|
|
11
|
-
* A when-branch sink is exempt: its path is branch-relative, and the branch
|
|
12
|
-
* tree holds no anchors of its own (the lowering rejects them), so the
|
|
13
|
-
* branch's own node list is a stable address space. Attribution is by the
|
|
14
|
-
* branch element's globally unique location id.
|
|
15
|
-
*/
|
|
16
|
-
function assertPathSafety(program) {
|
|
17
|
-
const branchNodeIds = /* @__PURE__ */ new Set();
|
|
18
|
-
for (const part of program.parts) {
|
|
19
|
-
if (part.k !== "when") continue;
|
|
20
|
-
collectElementIds(part.on, branchNodeIds);
|
|
21
|
-
collectElementIds(part.off, branchNodeIds);
|
|
22
|
-
}
|
|
23
|
-
for (const part of program.parts) {
|
|
24
|
-
if (part.k === "text" || part.k === "when" || part.k === "each") continue;
|
|
25
|
-
const nodeId = part.location.node;
|
|
26
|
-
if (nodeId !== void 0 && branchNodeIds.has(nodeId)) continue;
|
|
27
|
-
let nodes = program.template;
|
|
28
|
-
for (const target of part.path) {
|
|
29
|
-
for (let sibling = 0; sibling < target; sibling++) if (nodes[sibling]?.k === "part") {
|
|
30
|
-
const source = program.sourceMap.records.find((record) => record.id === `p${part.index}`)?.source;
|
|
31
|
-
throw new CompiledElementError([{
|
|
32
|
-
code: "OEC9015",
|
|
33
|
-
message: `${part.k} part path [${part.path.join(",")}] is preceded by a dynamic anchor; path-addressed fixed sinks must appear before any dynamic anchor sibling`,
|
|
34
|
-
file: source?.file ?? program.sourceMap.file,
|
|
35
|
-
line: source?.start.line ?? 1,
|
|
36
|
-
character: source?.start.column ?? 1,
|
|
37
|
-
start: source?.start.offset ?? 0,
|
|
38
|
-
end: source?.end.offset ?? 0
|
|
39
|
-
}]);
|
|
40
|
-
}
|
|
41
|
-
const next = nodes[target];
|
|
42
|
-
nodes = next?.k === "el" ? next.children : [];
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
/** Every element id a node list declares (branch trees are the branch set). */
|
|
47
|
-
function collectElementIds(nodes, out) {
|
|
48
|
-
for (const node of nodes) if (node.k === "el") {
|
|
49
|
-
out.add(node.id);
|
|
50
|
-
collectElementIds(node.children, out);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
/** Assemble, path-check and validate the Part Program; derive the serialized payloads. */
|
|
54
|
-
function buildPartProgram(input) {
|
|
55
|
-
const { sf, fileName, analyzed, root, lowering } = input;
|
|
56
|
-
const { tag, className, fields, render, rootKind } = analyzed;
|
|
57
|
-
const metadata = {
|
|
58
|
-
tag,
|
|
59
|
-
className,
|
|
60
|
-
sourceFile: fileName,
|
|
61
|
-
properties: fields.map((field) => ({
|
|
62
|
-
name: field.name,
|
|
63
|
-
attribute: field.attribute,
|
|
64
|
-
type: field.type,
|
|
65
|
-
converter: field.converter,
|
|
66
|
-
reflect: field.reflect,
|
|
67
|
-
default: field.defaultValue,
|
|
68
|
-
...field.computed ? {
|
|
69
|
-
computed: true,
|
|
70
|
-
deps: field.computed.deps
|
|
71
|
-
} : {}
|
|
72
|
-
})),
|
|
73
|
-
observedAttributes: fields.flatMap((field) => field.attribute === null ? [] : [field.attribute]),
|
|
74
|
-
cem: {
|
|
75
|
-
tagName: tag,
|
|
76
|
-
className,
|
|
77
|
-
declaration: {
|
|
78
|
-
name: className,
|
|
79
|
-
module: fileName
|
|
80
|
-
},
|
|
81
|
-
attributes: fields.flatMap((field) => field.attribute === null ? [] : [{
|
|
82
|
-
name: field.attribute,
|
|
83
|
-
fieldName: field.name,
|
|
84
|
-
type: field.type,
|
|
85
|
-
reflect: field.reflect
|
|
86
|
-
}]),
|
|
87
|
-
members: fields.map((field) => ({
|
|
88
|
-
name: field.name,
|
|
89
|
-
fieldName: field.name,
|
|
90
|
-
type: field.type,
|
|
91
|
-
attribute: field.attribute,
|
|
92
|
-
reflect: field.reflect
|
|
93
|
-
}))
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
const sourceRecords = [
|
|
97
|
-
{
|
|
98
|
-
id: "root",
|
|
99
|
-
kind: "root",
|
|
100
|
-
source: sourceRange(sf, render)
|
|
101
|
-
},
|
|
102
|
-
...fields.map((field) => ({
|
|
103
|
-
id: `property:${field.name}`,
|
|
104
|
-
kind: "property",
|
|
105
|
-
source: sourceRange(sf, field.node)
|
|
106
|
-
})),
|
|
107
|
-
...lowering.sourceRecords
|
|
108
|
-
];
|
|
109
|
-
const program = {
|
|
110
|
-
version: PART_PROGRAM_VERSION,
|
|
111
|
-
tag,
|
|
112
|
-
root: {
|
|
113
|
-
id: "root",
|
|
114
|
-
kind: rootKind,
|
|
115
|
-
nodes: [root.id]
|
|
116
|
-
},
|
|
117
|
-
template: [root],
|
|
118
|
-
parts: lowering.parts,
|
|
119
|
-
blocks: lowering.blocks,
|
|
120
|
-
dependencies: lowering.dependencies,
|
|
121
|
-
locations: lowering.locations,
|
|
122
|
-
sourceMap: {
|
|
123
|
-
version: 1,
|
|
124
|
-
file: fileName,
|
|
125
|
-
records: sourceRecords
|
|
126
|
-
},
|
|
127
|
-
metadata
|
|
128
|
-
};
|
|
129
|
-
assertPathSafety(program);
|
|
130
|
-
validatePartProgram(program);
|
|
131
|
-
const { sourceMap: _provenance, ...wireProgram } = program;
|
|
132
|
-
return {
|
|
133
|
-
program,
|
|
134
|
-
programJson: JSON.stringify(wireProgram, null, 2),
|
|
135
|
-
propertiesJson: JSON.stringify(metadata.properties, null, 2),
|
|
136
|
-
metadataJson: JSON.stringify(metadata, null, 2),
|
|
137
|
-
observedJson: JSON.stringify(metadata.observedAttributes, null, 2)
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
//#endregion
|
|
141
|
-
export { buildPartProgram };
|