@jxsuite/compiler 8.7.0 → 9.1.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.
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * Prototype-resolver.js — Generic $prototype resolution at build time
3
3
  *
4
- * Mirrors the runtime's import-map → .class.json → $implementation → resolve() pipeline, but runs
5
- * at compile time using filesystem APIs.
4
+ * Mirrors the runtime's import-map → .class.json → class → resolve() pipeline, but runs at compile
5
+ * time using filesystem APIs.
6
6
  *
7
- * Any state entry with a $prototype that maps to a .class.json via doc.imports gets resolved: the
8
- * class is instantiated, .resolve() is called, and the state entry is replaced with the resolved
9
- * value.
7
+ * Any state entry with a $prototype that names an external class (through its `$src`, the
8
+ * document's `imports`, or an enabled extension's manifest) gets resolved: the class is
9
+ * constructed, its value is taken, and the state entry is replaced with it. An entry the build
10
+ * cannot resolve fails the build (compiler.md §3).
10
11
  *
11
12
  * This is the extension point for content sources (Markdown, CSV, etc.) — each provides a
12
13
  * .class.json + JS implementation, and the compiler resolves them generically.
@@ -14,24 +15,21 @@
14
15
  * @module prototype-resolver
15
16
  */
16
17
 
17
- import { readFileSync } from "node:fs";
18
- import { dirname, resolve } from "node:path";
19
- import { createRequire } from "node:module";
20
- import { importImplementation } from "./format-host.ts";
21
- import { isFunction, isJsonObject, isPrototypeDef, isString } from "@jxsuite/schema/guards";
22
- import { errorMessage, parseClassDef } from "@jxsuite/schema/parse";
18
+ import { dirname } from "node:path";
19
+ import { isJsonObject, isPrototypeDef, isString } from "@jxsuite/schema/guards";
20
+ import { errorMessage } from "@jxsuite/schema/parse";
23
21
  import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
24
22
  import type {
25
- JsonObject,
26
- JsonValue,
27
23
  JxDocument,
28
- JxDocumentValue,
29
24
  JxMutableNode,
30
25
  JxPrototypeDef,
31
26
  JxStateDefinition,
32
27
  ProjectConfig,
33
28
  } from "@jxsuite/schema/types";
34
- import type { ProjectSectionData, ProjectSections } from "./project-sections.ts";
29
+ import { externalClassConfig, isExternalClassDef } from "../shared.ts";
30
+ import { instantiateAndResolve, loadClass, locateClass } from "./external-class.ts";
31
+ import type { ClassRoute, ExternalClassConfig } from "./external-class.ts";
32
+ import type { ProjectSections } from "./project-sections.ts";
35
33
 
36
34
  /**
37
35
  * Prototype names handled elsewhere (builtins + legacy content system). These are skipped by the
@@ -39,109 +37,60 @@ import type { ProjectSectionData, ProjectSections } from "./project-sections.ts"
39
37
  */
40
38
  const SKIP_PROTOTYPES = new Set(["Function", "LocalStorage", "SessionStorage", "Array"]);
41
39
 
42
- /**
43
- * Keys reserved by the Jx prototype system — stripped before passing config to the external class
44
- * constructor. Mirrors runtime's EXTERNAL_RESERVED.
45
- */
46
- const RESERVED_KEYS = new Set([
47
- "$prototype",
48
- "$src",
49
- "$export",
50
- "timing",
51
- "default",
52
- "description",
53
- ]);
54
-
55
- /** The route a document is being resolved for, as far as classes and `lower` read it. */
56
- interface PrototypeRoute {
57
- sourcePath?: string;
58
- _pathParams?: Record<string, string>;
59
- }
60
-
61
40
  /** Project-level context the build threads into every resolved class. */
62
41
  interface PrototypeProjectContext {
63
42
  config?: ProjectConfig;
64
43
  sections?: ProjectSections;
65
44
  registry?: ExtensionRegistry;
66
45
  registerBundle?: (specifier: string) => void;
67
- }
68
-
69
- /** `config._project`: the project config and root, plus every loaded section under its key. */
70
- interface ClassProjectContext {
71
- config: ProjectConfig | null;
72
- root: string;
73
- [sectionKey: string]: ProjectSectionData | ProjectConfig | string | null;
74
- }
75
-
76
- /** `config._document`: the route being built and the page's whole state. */
77
- interface ClassDocumentContext {
78
- route: PrototypeRoute;
79
- state: Record<string, JxStateDefinition>;
80
- }
81
-
82
- /**
83
- * The config an external class is constructed with: the def's own non-reserved keys, plus the
84
- * universal `_project` and `_document` context.
85
- */
86
- type ExternalClassConfig = Record<
87
- string,
88
- JxDocumentValue | ClassProjectContext | ClassDocumentContext | undefined
89
- >;
90
-
91
- /** A class instance that computes its value: `resolve()` answers with the JSON to bake in. */
92
- interface ResolvingInstance {
93
- resolve: () => JsonValue | Promise<JsonValue>;
94
- }
95
-
96
- /**
97
- * What an external class constructs (specs/extensions.md §8): either an instance that resolves its
98
- * value, or an instance whose own fields ARE the value.
99
- */
100
- type ExternalClassInstance = ResolvingInstance | JsonObject;
101
-
102
- /** An external class as its implementation module exports it. */
103
- type ExternalClass = new (config: ExternalClassConfig) => ExternalClassInstance;
104
-
105
- /**
106
- * Whether a constructed instance computes its value through `resolve()`.
107
- *
108
- * @param {ExternalClassInstance} instance
109
- * @returns {boolean}
110
- */
111
- function isResolvingInstance(instance: ExternalClassInstance): instance is ResolvingInstance {
112
- return isFunction(instance.resolve);
46
+ /**
47
+ * Write each resolved value as the entry's initial value (`{ "default": value }`) instead of the
48
+ * value itself. A component's state is what its compiled module starts from, so a value resolved
49
+ * for one has to stay a state entry; a page's is baked into its markup and then stripped.
50
+ */
51
+ asInitialValues?: boolean;
113
52
  }
114
53
 
115
54
  /**
116
55
  * Resolve all generic $prototype entries in a document's state at build time.
117
56
  *
118
- * For each state entry with a $prototype that: 1. Is not a builtin (Function, Array, etc.) 2. Maps
119
- * to a .class.json path via doc.imports
57
+ * A client- or server-timed entry stays for its own pipeline, unless its registry class has a
58
+ * `lower` capability, which compiles it away here into a core-shape def (specs/extensions.md §8.3).
59
+ * Every other entry that names an external class (`timing: "compiler"`, or no `timing`) is located,
60
+ * loaded, constructed and replaced with its value (`external-class.ts`).
120
61
  *
121
- * The resolver: - Reads the .class.json from disk - Follows $implementation to import the JS module
62
+ * Nothing is swallowed: a `lower` that throws, a compiler-timed entry that names no class, and a
63
+ * class that cannot be located, loaded or resolved are each collected, and one error naming every
64
+ * such entry is thrown after the rest have been tried.
122
65
  *
123
- * - Instantiates the class with the config - Calls .resolve() and replaces the state entry with the
124
- * result
125
- *
126
- * @param {JxMutableNode | JxDocument} doc - The page document (mutated in place)
127
- * @param {PrototypeRoute} route - Route info
66
+ * @param {JxMutableNode | JxDocument} doc - The document (mutated in place)
67
+ * @param {ClassRoute} route - Route info
128
68
  * @param {string} projectRoot - Absolute path to the project root
129
69
  * @param {PrototypeProjectContext} [projectContext] - Project-level context injected into all
130
70
  * classes; `sections` holds the extension-loaded project sections keyed by section key (spread
131
71
  * into `_project`); `registry` enables manifest class resolution and the generic `lower`
132
72
  * capability
73
+ * @returns {Promise<Record<string, JxStateDefinition>>} The entries it replaced, lowered or
74
+ * resolved, by state key
133
75
  */
134
76
  export async function resolvePrototypes(
135
77
  doc: JxMutableNode | JxDocument,
136
- route: PrototypeRoute,
78
+ route: ClassRoute,
137
79
  projectRoot: string,
138
80
  projectContext: PrototypeProjectContext = {},
139
- ) {
140
- const imports = doc.imports ?? {};
81
+ ): Promise<Record<string, JxStateDefinition>> {
82
+ const replaced: Record<string, JxStateDefinition> = {};
141
83
  const { state } = doc;
142
84
  if (!state) {
143
- return;
85
+ return replaced;
144
86
  }
87
+ const failures: string[] = [];
88
+ const lookup = {
89
+ docDir: route.sourcePath ? dirname(route.sourcePath) : null,
90
+ imports: doc.imports,
91
+ projectRoot,
92
+ registry: projectContext.registry,
93
+ };
145
94
 
146
95
  for (const [key, def] of Object.entries(state)) {
147
96
  if (!isPrototypeDef(def)) {
@@ -150,6 +99,7 @@ export async function resolvePrototypes(
150
99
  if (SKIP_PROTOTYPES.has(def.$prototype)) {
151
100
  continue;
152
101
  }
102
+ const label = `"${key}" ($prototype "${def.$prototype}")`;
153
103
  // Only resolve timing: "compiler" (or unset timing with a class mapping). Timing: "server"
154
104
  // And timing: "client" stay for their pipelines — but a registry class with a `lower`
155
105
  // Capability compiles away here into a core-shape def (specs/extensions.md §8.3): dynamic
@@ -178,126 +128,79 @@ export async function resolvePrototypes(
178
128
  delete lowered.$bundle;
179
129
  }
180
130
  state[key] = lowered;
131
+ replaced[key] = lowered;
181
132
  } catch (error) {
182
- console.warn(
183
- `prototype-resolver: failed to lower "${key}" ($prototype: "${def.$prototype}"):`,
184
- errorMessage(error),
185
- );
133
+ failures.push(`${label}: its class could not lower it: ${errorMessage(error)}`);
186
134
  }
187
135
  }
188
136
  continue;
189
137
  }
190
138
 
191
- // Look up in imports (project-local wins), then the extension registry's manifest classes.
192
- if (!def.$src) {
193
- const mapped = imports[def.$prototype] ?? registryClassPath(projectContext, def.$prototype);
194
- if (!mapped) {
139
+ try {
140
+ const located = locateClass(def, lookup);
141
+ if (located === undefined) {
142
+ // A built-in at compiler timing, and an unset-timing name nothing maps, are not this
143
+ // Resolver's: the first belongs to its own target, the second may only ever run interpreted.
144
+ if (def.timing === "compiler" && isExternalClassDef(def)) {
145
+ failures.push(
146
+ `${label} names no class: give it a $src or an imports entry, or enable the ` +
147
+ `extension that provides "${def.$prototype}"`,
148
+ );
149
+ }
195
150
  continue;
196
151
  }
197
- def.$src = mapped;
198
- }
199
-
200
- try {
201
- const resolved = await resolveClassPrototype(def, route, projectRoot, state, projectContext);
202
- // Preserve timing metadata on the resolved value so compilePage() can strip it
203
- if (def.timing && isJsonObject(resolved)) {
204
- resolved.timing = def.timing;
152
+ const Ctor = await loadClass(located);
153
+ const { value } = await instantiateAndResolve(
154
+ Ctor,
155
+ buildConfig(def, route, projectRoot, state, projectContext),
156
+ );
157
+ if (projectContext.asInitialValues) {
158
+ state[key] = { default: value ?? null };
159
+ } else {
160
+ // Preserve timing metadata on the resolved value so compilePage() can strip it
161
+ if (def.timing && isJsonObject(value)) {
162
+ value.timing = def.timing;
163
+ }
164
+ state[key] = value;
205
165
  }
206
- state[key] = resolved;
166
+ replaced[key] = state[key];
207
167
  } catch (error) {
208
- console.warn(
209
- `prototype-resolver: failed to resolve "${key}" ($prototype: "${def.$prototype}"):`,
210
- errorMessage(error),
211
- );
168
+ const hint = def.timing ? "" : ' (set "timing": "client" if it must run in the browser)';
169
+ failures.push(`${label}: ${errorMessage(error)}${hint}`);
212
170
  }
213
171
  }
214
- }
215
172
 
216
- /**
217
- * Descriptor path of a manifest class from the extension registry, when one is enabled. Lets
218
- * `timing: "compiler"` defs name extension classes (TableQuery, ContentCollection, …) without a
219
- * project-local imports entry.
220
- *
221
- * @param {{ registry?: ExtensionRegistry }} projectContext
222
- * @param {string} prototypeName
223
- * @returns {string | undefined}
224
- */
225
- function registryClassPath(
226
- projectContext: { registry?: ExtensionRegistry },
227
- prototypeName: string,
228
- ): string | undefined {
229
- return projectContext.registry?.byName(prototypeName)?.classPath;
173
+ if (failures.length > 0) {
174
+ throw new Error(
175
+ failures.length === 1
176
+ ? `state entry ${failures[0]}`
177
+ : `${failures.length} state entries could not be resolved: ${failures.join("; ")}`,
178
+ );
179
+ }
180
+ return replaced;
230
181
  }
231
182
 
232
183
  /**
233
- * Resolve a single $prototype entry via its .class.json.
184
+ * The config a class is constructed with during the build: the entry's own keys minus the reserved
185
+ * ones (spec.md §12.3), plus what only the build host knows.
234
186
  *
235
- * @param {JxPrototypeDef} def - The state entry definition
236
- * @param {PrototypeRoute} route
187
+ * @param {JxPrototypeDef} def
188
+ * @param {ClassRoute} route
237
189
  * @param {string} projectRoot
238
- * @param {Record<string, JxStateDefinition>} state - The full page state object
190
+ * @param {Record<string, JxStateDefinition>} state - The document's whole state
239
191
  * @param {PrototypeProjectContext} projectContext
240
- * @returns {Promise<JsonValue>} The resolved value
192
+ * @returns {ExternalClassConfig}
241
193
  */
242
- async function resolveClassPrototype(
194
+ function buildConfig(
243
195
  def: JxPrototypeDef,
244
- route: PrototypeRoute,
196
+ route: ClassRoute,
245
197
  projectRoot: string,
246
198
  state: Record<string, JxStateDefinition>,
247
199
  projectContext: PrototypeProjectContext,
248
- ): Promise<JsonValue> {
249
- const src = def.$src;
250
- if (!src) {
251
- throw new Error(`$prototype "${def.$prototype}" has no $src to resolve`);
252
- }
200
+ ): ExternalClassConfig {
201
+ const config: ExternalClassConfig = { ...externalClassConfig(def) };
253
202
 
254
- // 1. Resolve .class.json path — handles both npm specifiers and relative paths
255
- let classJsonPath;
256
- if (src.startsWith("./") || src.startsWith("../")) {
257
- // Relative path — resolve from page directory
258
- classJsonPath = route.sourcePath
259
- ? resolve(dirname(route.sourcePath), src)
260
- : resolve(projectRoot, src);
261
- } else {
262
- // Npm/bare specifier — use createRequire from the project root to walk node_modules
263
- const require = createRequire(resolve(projectRoot, "package.json"));
264
- classJsonPath = require.resolve(src);
265
- }
266
-
267
- // 2. Read and parse .class.json
268
- const classJsonText = readFileSync(classJsonPath, "utf8");
269
- const classDef = parseClassDef(classJsonText, classJsonPath);
270
-
271
- if (!classDef.$implementation) {
272
- throw new Error(`${src} has no $implementation field`);
273
- }
274
-
275
- // 3. Resolve $implementation relative to .class.json location
276
- const implPath = resolve(dirname(classJsonPath), classDef.$implementation);
277
-
278
- // 4. Import the module (tolerates src-vs-dist layouts and .js → .ts under Bun)
279
- const mod = await importImplementation(implPath);
280
-
281
- // 5. Find the exported class
282
- const exportName = def.$export ?? classDef.title ?? def.$prototype;
283
- /* SAFETY: what is found is the export a `.class.json` names as its implementation, which by the
284
- external-class contract (specs/extensions.md §8) is a class taking this config and building an
285
- ExternalClassInstance; only its presence is checked below, and the result is baked into the
286
- page as JSON. */
287
- const ExportedClass = (mod[exportName] ?? mod.default?.[exportName]) as ExternalClass | undefined;
288
- if (!ExportedClass) {
289
- throw new Error(`Module ${classDef.$implementation} does not export "${exportName}"`);
290
- }
291
-
292
- // 6. Build config — filter out reserved keys
293
- const config: ExternalClassConfig = {};
294
- for (const [k, v] of Object.entries(def)) {
295
- if (!RESERVED_KEYS.has(k)) {
296
- config[k] = v;
297
- }
298
- }
299
-
300
- // Auto-set basePath from the page's directory if the config has `src` but no `basePath`
203
+ // Auto-set basePath from the document's directory if the config has `src` but no `basePath`
301
204
  if (config.src && !config.basePath && route.sourcePath) {
302
205
  config.basePath = dirname(route.sourcePath);
303
206
  }
@@ -310,12 +213,5 @@ async function resolveClassPrototype(
310
213
  ...projectContext.sections,
311
214
  };
312
215
  config._document = { route, state };
313
-
314
- // 7. Instantiate and resolve. Trust boundary: external classes contractually
315
- // Return JSON-serializable data (the result is baked into the compiled page).
316
- const instance = new ExportedClass(config);
317
- if (isResolvingInstance(instance)) {
318
- return await instance.resolve();
319
- }
320
- return instance;
216
+ return config;
321
217
  }
@@ -32,10 +32,11 @@ export const SERVICE_WORKER_PATH = "sw.js";
32
32
  /**
33
33
  * The one path family safe to serve cache-first.
34
34
  *
35
- * It is the build's only content-addressed output — `variantFilename()` embeds a digest of the
36
- * source bytes, so a changed image is a changed URL and a cached one can never be wrong. Everything
37
- * else is named after what it contains rather than after its content (`_headers` says the same in
38
- * `NEVER_IMMUTABLE`), so caching it first would serve edited components from a stale entry.
35
+ * It is the build's only content-addressed output — a variant's file name embeds a digest of the
36
+ * source bytes and the settings they were encoded with, so a changed image or a changed quality is
37
+ * a changed URL and a cached one can never be wrong. Everything else is named after what it
38
+ * contains rather than after its content (`_headers` says the same in `NEVER_IMMUTABLE`), so
39
+ * caching it first would serve edited components from a stale entry.
39
40
  */
40
41
  export const CACHE_FIRST_PREFIX = "/images/_optimized/";
41
42