@unframework.dev/compiler 0.0.0-stage → 0.0.0

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/dist/config.js ADDED
@@ -0,0 +1,259 @@
1
+ import { TARGET_NAMES, builtinTargets } from "./targets.js";
2
+ import { closest } from "@unframework.dev/analyzer";
3
+ import { createDiagnostic } from "@unframework.dev/diagnostics";
4
+ import { existsSync } from "node:fs";
5
+ import { dirname, relative, resolve } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ //#region src/config.ts
8
+ /** The file names {@link loadConfig} looks for, the first one found winning. */
9
+ const CONFIG_FILES = [
10
+ "unframework.config.ts",
11
+ "unframework.config.mts",
12
+ "unframework.config.js",
13
+ "unframework.config.mjs"
14
+ ];
15
+ const FIELDS = [
16
+ "targets",
17
+ "srcDir",
18
+ "outDir",
19
+ "targetOptions",
20
+ "typeOracle",
21
+ "strict",
22
+ "package"
23
+ ];
24
+ const PACKAGE_FIELDS = ["targets", "resolveFrom"];
25
+ const TYPE_ORACLES = ["syntactic", "tsgo"];
26
+ /** A configuration has no source span to point at: the message names the file, or the field. */
27
+ const NO_SPAN = {
28
+ start: 0,
29
+ end: 0
30
+ };
31
+ /**
32
+ * Imports `unframework.config.{ts,mts,js,mjs}` from `root`, or `file` relative to it, through
33
+ * Node's type stripping. A project without a config file takes the defaults, so that is no error.
34
+ * It never throws: a file that cannot be imported, or has no default export, is UF7001.
35
+ */
36
+ async function loadConfig(root, file) {
37
+ const base = resolve(root);
38
+ const path = file === void 0 ? CONFIG_FILES.map((name) => resolve(base, name)).find((each) => existsSync(each)) : resolve(base, file);
39
+ if (path === void 0) return {
40
+ raw: {},
41
+ directory: base,
42
+ diagnostics: []
43
+ };
44
+ const shown = relative(base, path);
45
+ const failed = (reason) => ({
46
+ raw: void 0,
47
+ directory: dirname(path),
48
+ file: shown,
49
+ diagnostics: [createDiagnostic("UF7001", {
50
+ file: shown,
51
+ span: NO_SPAN,
52
+ message: `The configuration file ${shown} could not be loaded: ${reason}`
53
+ })]
54
+ });
55
+ try {
56
+ const loaded = await import(pathToFileURL(path).href);
57
+ if (!("default" in loaded) || isEmptyCommonJs(loaded)) return failed("it has no default export.");
58
+ return {
59
+ raw: loaded.default,
60
+ directory: dirname(path),
61
+ file: shown,
62
+ diagnostics: []
63
+ };
64
+ } catch (error) {
65
+ return failed(reasonOf(error));
66
+ }
67
+ }
68
+ /**
69
+ * Checks a configuration and applies its defaults. It never throws: a field of the wrong shape is
70
+ * UF7002, a name that is no built-in target UF7003, and options the target's schema rejects, or a
71
+ * target without a schema is given, UF7004, each with the field's JSON pointer. It is asynchronous
72
+ * because a Standard Schema may be.
73
+ */
74
+ async function resolveConfig(raw, origin = {}) {
75
+ const diagnostics = [];
76
+ const report = (code, pointer, problem) => {
77
+ diagnostics.push(createDiagnostic(code, {
78
+ file: origin.file ?? "unframework.config.ts",
79
+ span: NO_SPAN,
80
+ message: `The configuration at ${JSON.stringify(pointer)} ${problem}`
81
+ }));
82
+ };
83
+ try {
84
+ const config = await checkConfig(raw, resolve(origin.directory ?? "."), report);
85
+ return {
86
+ config: diagnostics.length > 0 ? void 0 : config,
87
+ diagnostics
88
+ };
89
+ } catch (error) {
90
+ report("UF7002", "", `could not be read: ${reasonOf(error)}`);
91
+ return {
92
+ config: void 0,
93
+ diagnostics
94
+ };
95
+ }
96
+ }
97
+ /** The configuration, whose result only counts when nothing was reported. */
98
+ async function checkConfig(raw, directory, report) {
99
+ if (!isRecord(raw)) {
100
+ report("UF7002", "", "must be an object, as `defineConfig` takes.");
101
+ return;
102
+ }
103
+ checkFields(raw, "", FIELDS, report);
104
+ const targets = raw.targets === void 0 ? [...TARGET_NAMES] : targetList(raw.targets, "/targets", report);
105
+ const srcDir = pathField(raw.srcDir === void 0 ? "src" : raw.srcDir, "/srcDir", directory, report);
106
+ const outDir = pathField(raw.outDir === void 0 ? "dist" : raw.outDir, "/outDir", directory, report);
107
+ const targetOptions = await resolveTargetOptions(raw.targetOptions, report);
108
+ if (raw.typeOracle !== void 0 && !TYPE_ORACLES.includes(raw.typeOracle)) report("UF7002", "/typeOracle", `must be "syntactic" or "tsgo".`);
109
+ if (raw.strict !== void 0 && typeof raw.strict !== "boolean") report("UF7002", "/strict", "must be a boolean.");
110
+ const packaging = raw.package === void 0 ? void 0 : resolvePackage(raw.package, targets, directory, report);
111
+ return {
112
+ targets,
113
+ srcDir,
114
+ outDir,
115
+ targetOptions,
116
+ typeOracle: raw.typeOracle ?? "syntactic",
117
+ strict: raw.strict ?? false,
118
+ ...packaging ? { package: packaging } : {}
119
+ };
120
+ }
121
+ /**
122
+ * Node gives a CommonJS file a `default`, its `module.exports`, even when it exports nothing, and a
123
+ * `.ts` or `.js` file with no ES module syntax left once its types are stripped loads as CommonJS
124
+ * unless its package sets `"type": "module"`. An explicit `module.exports = {}` reads the same, so
125
+ * it counts too.
126
+ */
127
+ function isEmptyCommonJs(loaded) {
128
+ return "module.exports" in loaded && isRecord(loaded.default) && Object.keys(loaded.default).length === 0;
129
+ }
130
+ /** What a thrown value says. Whatever the value is, reading it here can't throw again. */
131
+ function reasonOf(error) {
132
+ try {
133
+ if (!(error instanceof Error)) return String(error);
134
+ const reason = (String(error.message).trimEnd() || "it threw an error with no message").replace(/\.?$/, ".");
135
+ if (!("code" in error) || error.code !== "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") return reason;
136
+ return `${reason} Node loads a TypeScript configuration by stripping its types, so the file cannot use syntax that needs compiling, such as an enum or a parameter property.`;
137
+ } catch {
138
+ return "it threw a value that can't be read.";
139
+ }
140
+ }
141
+ function isRecord(value) {
142
+ if (typeof value !== "object" || value === null) return false;
143
+ const prototype = Object.getPrototypeOf(value);
144
+ return prototype === Object.prototype || prototype === null;
145
+ }
146
+ /** One key as a JSON pointer's segment (RFC 6901). */
147
+ function segment(key) {
148
+ return `/${key.replaceAll("~", "~0").replaceAll("/", "~1")}`;
149
+ }
150
+ function didYouMean(name, names) {
151
+ const meant = closest(name, names);
152
+ return meant ? ` Did you mean \`${meant}\`?` : "";
153
+ }
154
+ /** A misspelt field would otherwise be ignored in silence (P2). */
155
+ function checkFields(record, pointer, fields, report) {
156
+ for (const key of Object.keys(record)) {
157
+ if (fields.includes(key)) continue;
158
+ report("UF7002", `${pointer}${segment(key)}`, `is not a field of the configuration.${didYouMean(key, fields)}`);
159
+ }
160
+ }
161
+ /** Own names only: `toString` is not a target. */
162
+ function isTargetName(name) {
163
+ return Object.hasOwn(builtinTargets, name);
164
+ }
165
+ function reportUnknownTarget(name, pointer, report) {
166
+ const meant = didYouMean(name, TARGET_NAMES);
167
+ report("UF7003", pointer, `names the unknown target ${JSON.stringify(name)}.${meant || ` The built-in targets are ${TARGET_NAMES.join(", ")}.`}`);
168
+ }
169
+ /** A list of targets: `compile()` throws on a repeated one, so it is reported here first. */
170
+ function targetList(value, pointer, report, within) {
171
+ if (!Array.isArray(value) || value.length === 0) {
172
+ report("UF7002", pointer, "must be a list of at least one target name.");
173
+ return;
174
+ }
175
+ const seen = [];
176
+ for (const [index, item] of value.entries()) {
177
+ const at = `${pointer}/${index}`;
178
+ if (typeof item !== "string") report("UF7002", at, "must be a target name.");
179
+ else if (!isTargetName(item)) reportUnknownTarget(item, at, report);
180
+ else if (seen.includes(item)) report("UF7002", at, `repeats the target "${item}".`);
181
+ else if (within && !within.includes(item)) report("UF7002", at, `names the target "${item}", which "/targets" leaves out.`);
182
+ else seen.push(item);
183
+ }
184
+ return seen;
185
+ }
186
+ function pathField(value, pointer, directory, report) {
187
+ if (typeof value !== "string" || !value) {
188
+ report("UF7002", pointer, "must be a path, as a string that is not empty.");
189
+ return;
190
+ }
191
+ return resolve(directory, value);
192
+ }
193
+ async function resolveTargetOptions(value, report) {
194
+ const resolved = {};
195
+ if (value === void 0) return resolved;
196
+ if (!isRecord(value)) {
197
+ report("UF7002", "/targetOptions", "must be an object, by target name.");
198
+ return resolved;
199
+ }
200
+ for (const [name, options] of Object.entries(value)) {
201
+ const pointer = `/targetOptions${segment(name)}`;
202
+ if (!isTargetName(name)) {
203
+ reportUnknownTarget(name, pointer, report);
204
+ continue;
205
+ }
206
+ if (options === void 0) continue;
207
+ const schema = builtinTargets[name].options;
208
+ if (!schema) {
209
+ const problem = `is not valid: \`${name}\` declares no options.`;
210
+ if (!isRecord(options)) report("UF7004", pointer, problem);
211
+ else for (const key of Reflect.ownKeys(options)) report("UF7004", `${pointer}${segment(String(key))}`, problem);
212
+ continue;
213
+ }
214
+ try {
215
+ const result = await schema["~standard"].validate(options);
216
+ if (!result.issues) {
217
+ resolved[name] = result.value;
218
+ continue;
219
+ }
220
+ for (const issue of result.issues) report("UF7004", `${pointer}${(issue.path ?? []).map((part) => segment(String(typeof part === "object" ? part.key : part))).join("")}`, `is not valid: ${issue.message}`);
221
+ } catch (error) {
222
+ report("UF7004", pointer, `could not be validated: the target's schema threw: ${reasonOf(error)}`);
223
+ }
224
+ }
225
+ return resolved;
226
+ }
227
+ function resolvePackage(value, targets, directory, report) {
228
+ if (!isRecord(value)) {
229
+ report("UF7002", "/package", "must be an object.");
230
+ return;
231
+ }
232
+ checkFields(value, "/package", PACKAGE_FIELDS, report);
233
+ const resolved = {};
234
+ if (value.targets !== void 0) {
235
+ const list = targetList(value.targets, "/package/targets", report, targets);
236
+ if (list) resolved.targets = list;
237
+ }
238
+ const from = value.resolveFrom;
239
+ if (typeof from === "string") {
240
+ const path = pathField(from, "/package/resolveFrom", directory, report);
241
+ if (path) resolved.resolveFrom = path;
242
+ } else if (isRecord(from)) {
243
+ const each = {};
244
+ for (const [name, path] of Object.entries(from)) {
245
+ const pointer = `/package/resolveFrom${segment(name)}`;
246
+ if (!isTargetName(name)) {
247
+ reportUnknownTarget(name, pointer, report);
248
+ continue;
249
+ }
250
+ if (path === void 0) continue;
251
+ const absolute = pathField(path, pointer, directory, report);
252
+ if (absolute) each[name] = absolute;
253
+ }
254
+ resolved.resolveFrom = each;
255
+ } else if (from !== void 0) report("UF7002", "/package/resolveFrom", "must be a path, or an object of paths by target name.");
256
+ return resolved;
257
+ }
258
+ //#endregion
259
+ export { loadConfig, resolveConfig };
@@ -0,0 +1,12 @@
1
+ import { PackageConfig, TargetName, UnframeworkConfig } from "./config-types.js";
2
+ import { FileResolverOptions, ResolveRequest, ResolvedModule, ResolvedStylesheet, Resolver } from "./resolver.js";
3
+ import { TARGET_NAMES, builtinTargets, resolveTarget } from "./targets.js";
4
+ import { CompileOptions, CompileResult, CompilerPlugin, OutputHookContext, checkPassThrough, compile } from "./compile.js";
5
+ import { Project, ProjectOptions, ProjectUpdate, createFileResolver, createProject } from "./project.js";
6
+ import { ConfigOrigin, LoadedConfig, ResolveConfigResult, ResolvedConfig, loadConfig, resolveConfig } from "./config.js";
7
+ import { checkCapabilities } from "./capabilities.js";
8
+ import { OutputFile, Target, requiredCapabilities } from "@unframework.dev/codegen";
9
+ import { Diagnostic } from "@unframework.dev/diagnostics";
10
+ import { UfModule } from "@unframework.dev/ir";
11
+ import { SyntacticOracleOptions, TypeOracle, createSyntacticOracle } from "@unframework.dev/type-oracle";
12
+ export { type CompileOptions, type CompileResult, type CompilerPlugin, type ConfigOrigin, type Diagnostic, type FileResolverOptions, type LoadedConfig, type OutputFile, type OutputHookContext, type PackageConfig, type Project, type ProjectOptions, type ProjectUpdate, type ResolveConfigResult, type ResolveRequest, type ResolvedConfig, type ResolvedModule, type ResolvedStylesheet, type Resolver, type SyntacticOracleOptions, TARGET_NAMES, type Target, type TargetName, type TypeOracle, type UfModule, type UnframeworkConfig, builtinTargets, checkCapabilities, checkPassThrough, compile, createFileResolver, createProject, createSyntacticOracle, loadConfig, requiredCapabilities, resolveConfig, resolveTarget };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import { checkCapabilities } from "./capabilities.js";
2
+ import { TARGET_NAMES, builtinTargets, resolveTarget } from "./targets.js";
3
+ import { checkPassThrough, compile } from "./compile.js";
4
+ import { createFileResolver, createProject } from "./project.js";
5
+ import { loadConfig, resolveConfig } from "./config.js";
6
+ import { requiredCapabilities } from "@unframework.dev/codegen";
7
+ import { createSyntacticOracle } from "@unframework.dev/type-oracle";
8
+ export { TARGET_NAMES, builtinTargets, checkCapabilities, checkPassThrough, compile, createFileResolver, createProject, createSyntacticOracle, loadConfig, requiredCapabilities, resolveConfig, resolveTarget };
@@ -0,0 +1,310 @@
1
+ import { codeOf, expressionsOf, functionsOf, spansOf } from "@unframework.dev/ir";
2
+ //#region src/plugin-ir.ts
3
+ /**
4
+ * Where a plugin's module (schema-valid) stops describing the source it was analysed from:
5
+ * - another file, or a span outside the source: diagnostics point at those spans, and JSON and
6
+ * SARIF output refuse a location outside its file;
7
+ * - an expression, a piece of setup code, a function, a type annotation, a type declaration or
8
+ * the declared events that are not ones the analyser produced for this module (`analysed`),
9
+ * compared whole: spans, code, references and every flag. Every target copies them into its
10
+ * output, rewriting only the references, and the IR cannot parse code: a span moved into a
11
+ * string literal or a comment, a reference dropped, a write turned into a read, or a
12
+ * parameter's default or type changed, would hand the targets code nobody analysed (P2). A
13
+ * plugin may move, copy or drop analysed code, never write its own;
14
+ * - a function or a piece of code moved to a slot of another context or role: the analyser
15
+ * judges client code by looser rules than a getter or an initial value (time, chance and
16
+ * in-place changes), so a function is keyed by its context and role, and code by its context
17
+ * and whether it is statements or an expression (ADR-0045);
18
+ * - pass-through imports that are not a subsequence of the analyser's (ADR-0064): every output
19
+ * keeps them as written, so a plugin may drop one, never add, duplicate, reorder or change one.
20
+ */
21
+ function pluginIrProblems(result, analysed, source) {
22
+ const problems = [];
23
+ if (result.file !== analysed.file) problems.push({
24
+ path: "/file",
25
+ message: `must stay "${analysed.file}", the file analysed`
26
+ });
27
+ for (const { span, path } of spansOf(result)) if (!isSpanIn(span, source.length)) problems.push({
28
+ path,
29
+ message: `must lie in the source (${source.length} characters)`
30
+ });
31
+ const known = analysedCode(analysed);
32
+ const check = (key, path, message) => {
33
+ if (!known.has(key)) problems.push({
34
+ path,
35
+ message
36
+ });
37
+ };
38
+ for (const [index, component] of result.components.entries()) {
39
+ const base = `/components/${index}`;
40
+ if (component.propsParameter) check(typeTextKey(component.propsParameter.type), `${base}/propsParameter/type`, NOT_ANALYSED.type);
41
+ for (const [prop, { type }] of component.props.entries()) check(typeTextKey(type), `${base}/props/${prop}/type`, NOT_ANALYSED.type);
42
+ for (const { expression, path } of expressionsOf(component, base)) check(expressionKey(expression), path, NOT_ANALYSED.expression);
43
+ for (const [position, item] of component.setup.entries()) if ("type" in item && item.type) check(typeTextKey(item.type), `${base}/setup/${position}/type`, NOT_ANALYSED.type);
44
+ const functions = functionsOf(component, base);
45
+ for (const located of functions) check(functionKey(located), located.path, NOT_ANALYSED.function);
46
+ for (const { key, path } of codeKeys(component, functions, base)) {
47
+ if (functions.some((located) => path.startsWith(`${located.path}/`))) continue;
48
+ check(key, path, NOT_ANALYSED.code);
49
+ }
50
+ if (component.emits) check(emitsKey(component.emits), `${base}/emits`, NOT_ANALYSED.emits);
51
+ if (component.styles) check(stylesKey(component), `${base}/styles`, NOT_ANALYSED.styles);
52
+ }
53
+ for (const [index, declaration] of result.types.entries()) check(declarationKey(declaration), `/types/${index}`, NOT_ANALYSED.declaration);
54
+ const imports = (analysed.passThroughImports ?? []).map(passThroughKey);
55
+ let next = 0;
56
+ for (const [index, entry] of (result.passThroughImports ?? []).entries()) {
57
+ const key = passThroughKey(entry);
58
+ while (next < imports.length && imports[next] !== key) next++;
59
+ if (next === imports.length) problems.push({
60
+ path: `/passThroughImports/${index}`,
61
+ message: NOT_ANALYSED.passThrough
62
+ });
63
+ else next++;
64
+ }
65
+ return problems;
66
+ }
67
+ /** A pass-through import, as a key that equals another's when every field does. */
68
+ function passThroughKey({ specifier, names, span }) {
69
+ return JSON.stringify([
70
+ specifier,
71
+ names.map((name) => [
72
+ name.imported,
73
+ name.local,
74
+ spanValue(name.span)
75
+ ]),
76
+ spanValue(span)
77
+ ]);
78
+ }
79
+ const NOT_ANALYSED = {
80
+ passThrough: "must be an import the analyser passed through, in its order: a plugin may drop one, never add, duplicate, reorder or change one",
81
+ expression: "must be an expression the analyser produced, with its span, code and references: a plugin may move, copy or drop analysed code, never write its own",
82
+ code: "must be code the analyser produced, with its span, code and references, where code of its context runs: a plugin may move, copy or drop analysed code, never write its own",
83
+ function: "must be a function the analyser produced, with its parameters, types, body, event controls and flags, in a place of its context and role",
84
+ type: "must be a type annotation the analyser produced, with its span and code",
85
+ emits: "must be the events the analyser produced, as it produced them",
86
+ declaration: "must be a type declaration the analyser produced, as it produced it",
87
+ styles: "must be the stylesheets the analyser produced, with their scope id, as it produced them: the compiler scopes them (ADR-0063)"
88
+ };
89
+ /**
90
+ * Every expression, piece of code, function, type annotation, type declaration and events
91
+ * declaration of a module, by its key.
92
+ */
93
+ function analysedCode(module) {
94
+ const keys = /* @__PURE__ */ new Set();
95
+ for (const declaration of module.types) keys.add(declarationKey(declaration));
96
+ for (const component of module.components) {
97
+ if (component.propsParameter) keys.add(typeTextKey(component.propsParameter.type));
98
+ for (const { type } of component.props) keys.add(typeTextKey(type));
99
+ for (const { expression } of expressionsOf(component)) keys.add(expressionKey(expression));
100
+ for (const item of component.setup) if ("type" in item && item.type) keys.add(typeTextKey(item.type));
101
+ const functions = functionsOf(component);
102
+ for (const located of functions) keys.add(functionKey(located));
103
+ for (const { key } of codeKeys(component, functions)) keys.add(key);
104
+ if (component.emits) keys.add(emitsKey(component.emits));
105
+ if (component.styles) keys.add(stylesKey(component));
106
+ }
107
+ return keys;
108
+ }
109
+ function expressionKey(expression) {
110
+ return JSON.stringify(expressionValue(expression));
111
+ }
112
+ /**
113
+ * Each piece of code of a component with its key: the context it runs in, whether it is a block
114
+ * of statements (a function's block body) or an expression, and its value.
115
+ */
116
+ function codeKeys(component, functions, base = "") {
117
+ const bodies = new Map(functions.map(({ function: fn, path }) => [`${path}/body`, fn]));
118
+ return codeOf(component, base).map(({ code, path, context }) => {
119
+ const fn = bodies.get(path);
120
+ const kind = fn && fn.expression !== true ? "statements" : "expression";
121
+ return {
122
+ key: JSON.stringify([
123
+ context,
124
+ kind,
125
+ codeValue(code)
126
+ ]),
127
+ path
128
+ };
129
+ });
130
+ }
131
+ /** A function's key: the context it runs in, its role, and its value. */
132
+ function functionKey({ function: fn, context, role }) {
133
+ return JSON.stringify([
134
+ context,
135
+ role,
136
+ functionValue(fn)
137
+ ]);
138
+ }
139
+ function typeTextKey(type) {
140
+ return JSON.stringify(typeTextValue(type));
141
+ }
142
+ function emitsKey({ binding, type, events, span }) {
143
+ return JSON.stringify([
144
+ "Emits",
145
+ binding,
146
+ typeTextValue(type),
147
+ events.map((event) => [
148
+ event.name,
149
+ event.parameters.map((parameter) => [
150
+ parameter.name,
151
+ parameter.optional === true,
152
+ typeTextValue(parameter.type),
153
+ spanValue(parameter.span)
154
+ ]),
155
+ spanValue(event.span)
156
+ ]),
157
+ spanValue(span)
158
+ ]);
159
+ }
160
+ /** A component's sheets and their scope id, which a plugin may drop together, or keep. */
161
+ function stylesKey({ styles, scopeId }) {
162
+ return JSON.stringify([
163
+ "Styles",
164
+ scopeId ?? null,
165
+ (styles ?? []).map(({ specifier, source, span }) => [
166
+ specifier,
167
+ source,
168
+ spanValue(span)
169
+ ])
170
+ ]);
171
+ }
172
+ function declarationKey({ name, exported, code, span }) {
173
+ return JSON.stringify([
174
+ "TypeDeclaration",
175
+ name,
176
+ exported,
177
+ code,
178
+ span.start,
179
+ span.end
180
+ ]);
181
+ }
182
+ function expressionValue({ code, span, refs }) {
183
+ return [
184
+ "Expression",
185
+ code,
186
+ span.start,
187
+ span.end,
188
+ refs.map(referenceValue)
189
+ ];
190
+ }
191
+ function codeValue({ code, span, refs }) {
192
+ return [
193
+ "Code",
194
+ code,
195
+ span.start,
196
+ span.end,
197
+ refs.map(referenceValue)
198
+ ];
199
+ }
200
+ /** A reference with every field its kind has, each kind read exhaustively. */
201
+ function referenceValue(reference) {
202
+ switch (reference.kind) {
203
+ case "Binding": return [
204
+ reference.kind,
205
+ reference.binding,
206
+ spanValue(reference.span),
207
+ reference.shorthand === true,
208
+ reference.call === true
209
+ ];
210
+ case "Global": return [
211
+ reference.kind,
212
+ reference.name,
213
+ spanValue(reference.span)
214
+ ];
215
+ case "Write": return [
216
+ reference.kind,
217
+ reference.binding,
218
+ reference.operator,
219
+ spanValue(reference.span),
220
+ spanValue(reference.target),
221
+ reference.value ? spanValue(reference.value) : null,
222
+ reference.arrowBody === true
223
+ ];
224
+ case "Emit": return [
225
+ reference.kind,
226
+ reference.binding,
227
+ reference.event,
228
+ spanValue(reference.span),
229
+ reference.arguments.map(spanValue)
230
+ ];
231
+ case "Api": return [
232
+ reference.kind,
233
+ reference.api,
234
+ spanValue(reference.span)
235
+ ];
236
+ case "Event": return [
237
+ reference.kind,
238
+ reference.member,
239
+ spanValue(reference.span),
240
+ reference.call === true
241
+ ];
242
+ case "Slot": return [
243
+ reference.kind,
244
+ reference.slot,
245
+ spanValue(reference.span)
246
+ ];
247
+ case "Import": return [
248
+ reference.kind,
249
+ reference.name,
250
+ spanValue(reference.span)
251
+ ];
252
+ default: return unreachable(reference);
253
+ }
254
+ }
255
+ function functionValue(fn) {
256
+ return [
257
+ "Function",
258
+ fn.async === true,
259
+ fn.parameters.map(parameterValue),
260
+ fn.returnType ? typeTextValue(fn.returnType) : null,
261
+ codeValue(fn.body),
262
+ fn.expression === true,
263
+ (fn.eventControls ?? []).map(controlValue),
264
+ spanValue(fn.span)
265
+ ];
266
+ }
267
+ function parameterValue(parameter) {
268
+ const { pattern } = parameter;
269
+ return [
270
+ parameter.name ?? null,
271
+ pattern ? [
272
+ pattern.code,
273
+ pattern.names,
274
+ spanValue(pattern.span)
275
+ ] : null,
276
+ parameter.type ? typeTextValue(parameter.type) : null,
277
+ parameter.optional === true,
278
+ parameter.rest === true,
279
+ parameter.default ? expressionValue(parameter.default) : null,
280
+ parameter.event ?? null,
281
+ spanValue(parameter.span)
282
+ ];
283
+ }
284
+ function controlValue(control) {
285
+ return [
286
+ control.method,
287
+ control.condition ? codeValue(control.condition) : null,
288
+ spanValue(control.span)
289
+ ];
290
+ }
291
+ function typeTextValue({ code, span }) {
292
+ return [
293
+ "TypeText",
294
+ code,
295
+ span.start,
296
+ span.end
297
+ ];
298
+ }
299
+ const spanValue = ({ start, end }) => [start, end];
300
+ /** Whether a span is a well-formed range of UTF-16 offsets in a source of `length` characters. */
301
+ function isSpanIn(span, length) {
302
+ const isOffset = (offset) => typeof offset === "number" && Number.isInteger(offset) && offset >= 0 && offset <= length;
303
+ return typeof span === "object" && span !== null && "start" in span && "end" in span && isOffset(span.start) && isOffset(span.end) && span.start <= span.end;
304
+ }
305
+ /** The `never` default of an exhaustive switch: a kind added to a union fails type checking. */
306
+ function unreachable(value) {
307
+ throw new Error(`Unexpected IR value: ${JSON.stringify(value)}`);
308
+ }
309
+ //#endregion
310
+ export { isSpanIn, pluginIrProblems };
@@ -0,0 +1,74 @@
1
+ import { FileResolverOptions, Resolver } from "./resolver.js";
2
+ import { CompileOptions, CompileResult } from "./compile.js";
3
+ import { OutputFile } from "@unframework.dev/codegen";
4
+ //#region src/project.d.ts
5
+ /**
6
+ * Options for {@link createProject}: its files, as `createFileResolver`'s, and the options each of
7
+ * its compiles takes, but the file name and the resolver, which are the project's.
8
+ */
9
+ export type ProjectOptions = FileResolverOptions & Omit<CompileOptions, "filename" | "resolve" | "typeOracle">;
10
+ /** What {@link Project.update} did. */
11
+ export interface ProjectUpdate {
12
+ /** The modules compiled again, sorted, each once. */
13
+ compiled: string[];
14
+ /** The shared `.ts` modules whose copy was added, changed or went, sorted. */
15
+ copied: string[];
16
+ }
17
+ /** A project's module graph (ADR-0071). Every file is named relative to its root. */
18
+ export interface Project {
19
+ /**
20
+ * The resolver its compiles read imports through (ADR-0053), for a caller that runs
21
+ * `compile()` itself: `createFileResolver` gives it.
22
+ */
23
+ readonly resolve: Resolver;
24
+ /**
25
+ * Compiles a `.uf.tsx` or `.uf.ts` module, or gives its last result: {@link Project.update}
26
+ * compiles it again when what it read changed. The result's outputs leave out the copies of
27
+ * shared `.ts` modules, which belong to each module's own node: {@link Project.copy} gives them.
28
+ */
29
+ compile(file: string): Promise<CompileResult>;
30
+ /**
31
+ * The text of a shared `.ts` module that a compiled module reaches, which every output tree
32
+ * holds unchanged (ADR-0070), or `undefined` for a file no compile copied.
33
+ */
34
+ copy(file: string): string | undefined;
35
+ /**
36
+ * The copies of shared `.ts` modules that a compiled module's result leaves out, at their paths
37
+ * relative to it, each with its module's current text: what `compile()` adds to every output
38
+ * tree beside the module's own files (ADR-0070). Empty for a module the project has not compiled.
39
+ */
40
+ copies(file: string): OutputFile[];
41
+ /** What a module read, sorted: files, and packages as `pkg:<name>` (ADR-0071). */
42
+ dependencies(file: string): string[];
43
+ /**
44
+ * Routes changed, created or deleted files through the project: it tells the type oracle, reads
45
+ * again the copies among them, then checks each compiled module that depends on a file,
46
+ * directly or not, and compiles it again only where what it read changed.
47
+ */
48
+ update(files: readonly string[]): Promise<ProjectUpdate>;
49
+ }
50
+ /**
51
+ * The project graph (ADR-0071) over the files `readFile` gives. A module's cache key is a hash of
52
+ * its source and of everything it read through the project: its children's APIs and the shapes
53
+ * they were analysed with, its stylesheets, the files of its shared modules, its import cycles
54
+ * and its own types' shapes. A shared module's text is no part of it: its copy is the module's own
55
+ * node, so an edit that changes only a copy recompiles nothing. The caller owns `typeOracle`.
56
+ */
57
+ export declare function createProject(options: ProjectOptions): Project;
58
+ /**
59
+ * A resolver over files (ADR-0053): a project's (ADR-0071), which reads the imported file,
60
+ * analyses it up to its declarations, its types read through the type oracle (ADR-0067), and
61
+ * gives its API with its `file` relative to the importer. The analysis is cached by the contents
62
+ * of the file, its stylesheets and its shapes, so an edit that leaves the API alone resolves to
63
+ * the same API, and the parent compiles to the same bytes. A child's API is read from its
64
+ * declarations alone, never from its own `.uf.tsx` imports, so a cycle cannot make it loop: only
65
+ * `cycle` resolves those, for their APIs.
66
+ * Its stylesheets are read, for the scope id its API carries (ADR-0063). It reads a stylesheet for
67
+ * `stylesheet` too, and for `module` a shared `.ts` module, a specifier without an extension
68
+ * naming its `.ts`, and follows its relative imports through every `.ts` module they reach, each
69
+ * read once (ADR-0070). Its `cycle` follows the component edges from an import, each a value
70
+ * import of a component from a `.uf.tsx` module, for the shortest cycle back to the importer
71
+ * (UF1205).
72
+ */
73
+ export declare function createFileResolver(options: FileResolverOptions): Resolver;
74
+ //#endregion