@jxsuite/compiler 9.0.1 → 10.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/cli.js +269 -254
- package/dist/compiler.js +181 -162
- package/package.json +19 -18
- package/src/cli.ts +13 -3
- package/src/compiler.ts +38 -20
- package/src/shadow.ts +6 -33
- package/src/shared.ts +1850 -283
- package/src/site/base-path.ts +88 -2
- package/src/site/bundler-backend.bun.ts +36 -2
- package/src/site/bundler-backend.node.ts +42 -2
- package/src/site/bundler-backend.ts +12 -0
- package/src/site/bundler.ts +40 -4
- package/src/site/client-runtime.ts +13 -14
- package/src/site/external-class.ts +290 -0
- package/src/site/format-host.ts +49 -10
- package/src/site/headers-emitter.ts +6 -5
- package/src/site/image-cache.ts +34 -3
- package/src/site/image-optimizer.ts +51 -11
- package/src/site/image-transform.ts +219 -88
- package/src/site/pages-discovery.ts +8 -1
- package/src/site/prototype-resolver.ts +91 -195
- package/src/site/service-worker.ts +4 -3
- package/src/site/site-build.ts +425 -105
- package/src/site/site-loader.ts +9 -0
- package/src/targets/compile-class.ts +42 -3
- package/src/targets/compile-client.ts +319 -91
- package/src/targets/compile-element.ts +696 -94
- package/src/targets/compile-pack.ts +234 -0
- package/src/targets/compile-static.ts +33 -83
package/src/site/base-path.ts
CHANGED
|
@@ -32,6 +32,8 @@
|
|
|
32
32
|
*/
|
|
33
33
|
|
|
34
34
|
import { formatSrcset, parseSrcset, withBase } from "@jxsuite/schema/asset-paths";
|
|
35
|
+
import { isMappedArray, isNonNullObject, isString } from "@jxsuite/schema/guards";
|
|
36
|
+
import type { JxDocument, JxElement, JxMutableNode } from "@jxsuite/schema/types";
|
|
35
37
|
|
|
36
38
|
/**
|
|
37
39
|
* Attributes whose value is a single URL.
|
|
@@ -89,8 +91,15 @@ const URL_META_RE =
|
|
|
89
91
|
*/
|
|
90
92
|
const ENTITY_QUOTE_RE = /^("|"|'|')([\s\S]*)\1$/;
|
|
91
93
|
|
|
92
|
-
/**
|
|
93
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Rewrite every `url(...)` in a CSS fragment: a `<style>` block, a `style` attribute, or a
|
|
96
|
+
* stylesheet the build writes as a file of its own.
|
|
97
|
+
*
|
|
98
|
+
* @param {string} css
|
|
99
|
+
* @param {string} base - From `siteBasePath`; `""` returns the text untouched
|
|
100
|
+
* @returns {string}
|
|
101
|
+
*/
|
|
102
|
+
export function rewriteCssUrls(css: string, base: string): string {
|
|
94
103
|
return css.replaceAll(CSS_URL_RE, (match, quote: string, inner: string) => {
|
|
95
104
|
const raw = inner.trim();
|
|
96
105
|
const escaped = ENTITY_QUOTE_RE.exec(raw);
|
|
@@ -173,3 +182,80 @@ export function rewriteHtmlBase(html: string, base: string): string {
|
|
|
173
182
|
return rewrittenAttrs === attrs ? match : `<${tagName}${rewrittenAttrs}>`;
|
|
174
183
|
});
|
|
175
184
|
}
|
|
185
|
+
|
|
186
|
+
/** One element node: its `attributes`, then the element properties written beside `tagName`. */
|
|
187
|
+
function rebaseNode(node: JxElement | JxMutableNode, base: string): void {
|
|
188
|
+
const tag = isString(node.tagName) ? node.tagName.toLowerCase() : "";
|
|
189
|
+
const { attributes } = node;
|
|
190
|
+
if (isNonNullObject(attributes)) {
|
|
191
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
192
|
+
if (isString(value)) {
|
|
193
|
+
attributes[name] = rewriteAttrValue(tag, "", name, value, base);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/* An element property is written under its IDL name (`src`, `formAction`), which lowercases to
|
|
198
|
+
the content attribute it reflects. `style` here is a style object, never CSS text, and its
|
|
199
|
+
rules ship in the component's stylesheet, which is re-rooted as a file. */
|
|
200
|
+
for (const name of Object.keys(node)) {
|
|
201
|
+
const lower = name.toLowerCase();
|
|
202
|
+
const value = node[name];
|
|
203
|
+
if (isString(value) && (URL_ATTRS.has(lower) || SRCSET_ATTRS.has(lower))) {
|
|
204
|
+
node[name] = rewriteAttrValue(tag, "", lower, value, base);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Markup a node carries as text is HTML like any other, optimized pictures included.
|
|
208
|
+
if (isString(node.innerHTML)) {
|
|
209
|
+
node.innerHTML = rewriteHtmlBase(node.innerHTML, base);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** A node, then everything it can render: children, a repeater's template, `$switch` cases. */
|
|
214
|
+
function rebaseTree(def: JxMutableNode[string], base: string): void {
|
|
215
|
+
if (!isNonNullObject(def) || Array.isArray(def)) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (isMappedArray(def)) {
|
|
219
|
+
rebaseTree(def.map, base);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
/* SAFETY: a non-array object in a document's element tree that is not a repeater is an element
|
|
223
|
+
node, which is all the tree holds besides strings. */
|
|
224
|
+
const node = def as JxMutableNode;
|
|
225
|
+
rebaseNode(node, base);
|
|
226
|
+
const { cases, children } = node;
|
|
227
|
+
if (Array.isArray(children)) {
|
|
228
|
+
for (const child of children) {
|
|
229
|
+
rebaseTree(child, base);
|
|
230
|
+
}
|
|
231
|
+
} else {
|
|
232
|
+
rebaseTree(children, base);
|
|
233
|
+
}
|
|
234
|
+
if (isNonNullObject(cases)) {
|
|
235
|
+
for (const caseNode of Object.values(cases)) {
|
|
236
|
+
rebaseTree(caseNode, base);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Re-root every site-absolute URL a document's own markup writes, in place: the document-side
|
|
243
|
+
* counterpart of {@link rewriteHtmlBase}, for a definition compiled into a module.
|
|
244
|
+
*
|
|
245
|
+
* A component's module is JavaScript, which the HTML pass never reads, and it replaces the markup
|
|
246
|
+
* the page prerendered. Left alone it drew `/hero.jpg` over the prerender's `/m/site/hero.jpg`: the
|
|
247
|
+
* picture a visitor had already been shown 404ed the moment the element upgraded. The same
|
|
248
|
+
* attributes are rewritten by the same rule (`href`, `src`, `poster`, `action`, `formaction`,
|
|
249
|
+
* `data`, `srcset`, `imagesrcset` and `url()` in a `style` attribute), on every node the definition
|
|
250
|
+
* can render, so the optimizer's candidate lists are covered with the rest. A `${…}` template that
|
|
251
|
+
* does not open with `/`, and a value that arrives through state, are data and are left as
|
|
252
|
+
* written.
|
|
253
|
+
*
|
|
254
|
+
* @param {JxDocument | JxElement} doc - Mutated
|
|
255
|
+
* @param {string} base - From `siteBasePath`; `""` leaves the document untouched
|
|
256
|
+
*/
|
|
257
|
+
export function rebaseDocument(doc: JxDocument | JxElement, base: string): void {
|
|
258
|
+
if (base !== "") {
|
|
259
|
+
rebaseTree(doc, base);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
* both under one Bun.
|
|
7
7
|
*/
|
|
8
8
|
import { rmSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { join } from "node:path";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
10
|
import type { BuildConfig } from "bun";
|
|
11
|
-
import type { BackendBuild, BundleTargetName } from "./bundler-backend.ts";
|
|
11
|
+
import type { BackendBuild, BackendSplitBuild, BundleTargetName } from "./bundler-backend.ts";
|
|
12
12
|
import { TRANSIENT_ENTRY_PREFIX } from "./bundler-backend.ts";
|
|
13
13
|
import * as esbuildBackend from "./bundler-backend.node.ts";
|
|
14
14
|
|
|
@@ -94,3 +94,37 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
94
94
|
rmSync(entryPath, { force: true });
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Bundle several entries with code splitting into `outdir`, and return the files written. Throws
|
|
100
|
+
* with the backend's diagnostics on failure.
|
|
101
|
+
*/
|
|
102
|
+
export async function buildSplit(request: BackendSplitBuild): Promise<string[]> {
|
|
103
|
+
if (forcedToEsbuild()) {
|
|
104
|
+
return esbuildBackend.buildSplit(request);
|
|
105
|
+
}
|
|
106
|
+
const config: BuildConfig = {
|
|
107
|
+
entrypoints: request.entries,
|
|
108
|
+
external: request.external,
|
|
109
|
+
format: "esm",
|
|
110
|
+
minify: request.minify,
|
|
111
|
+
naming: { chunk: "chunk-[hash].[ext]", entry: "[name].[ext]" },
|
|
112
|
+
outdir: request.outdir,
|
|
113
|
+
plugins: request.plugins,
|
|
114
|
+
splitting: true,
|
|
115
|
+
target: bunTarget(request.target),
|
|
116
|
+
throw: false,
|
|
117
|
+
};
|
|
118
|
+
if (request.conditions) {
|
|
119
|
+
config.conditions = request.conditions;
|
|
120
|
+
}
|
|
121
|
+
if (request.define) {
|
|
122
|
+
config.define = request.define;
|
|
123
|
+
}
|
|
124
|
+
const result = await Bun.build(config);
|
|
125
|
+
if (!result.success) {
|
|
126
|
+
const logs = result.logs.map(String).join("\n");
|
|
127
|
+
throw new Error(`Bun.build failed for ${request.entries.join(", ")}:\n${logs}`);
|
|
128
|
+
}
|
|
129
|
+
return result.outputs.map((output) => resolve(request.outdir, output.path));
|
|
130
|
+
}
|
|
@@ -3,9 +3,15 @@
|
|
|
3
3
|
* runtime that is not Bun bundles with it, and Bun does too under `JX_BUNDLER=esbuild`.
|
|
4
4
|
*/
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
|
-
import {
|
|
6
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
7
8
|
import type { BuildOptions } from "esbuild";
|
|
8
|
-
import type {
|
|
9
|
+
import type {
|
|
10
|
+
BackendBuild,
|
|
11
|
+
BackendSplitBuild,
|
|
12
|
+
BundlePlugin,
|
|
13
|
+
BundleTargetName,
|
|
14
|
+
} from "./bundler-backend.ts";
|
|
9
15
|
|
|
10
16
|
/** Which bundler this backend runs. */
|
|
11
17
|
export function backendName(): "bun" | "esbuild" {
|
|
@@ -79,3 +85,37 @@ export async function build(request: BackendBuild): Promise<string> {
|
|
|
79
85
|
const result = await esbuild.build({ ...options, write: false });
|
|
80
86
|
return result.outputFiles[0]!.text;
|
|
81
87
|
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Bundle several entries with code splitting into `outdir`, and return the files written. Throws
|
|
91
|
+
* with esbuild's diagnostics on failure.
|
|
92
|
+
*/
|
|
93
|
+
export async function buildSplit(request: BackendSplitBuild): Promise<string[]> {
|
|
94
|
+
const esbuild = await import("esbuild");
|
|
95
|
+
const options: BuildOptions = {
|
|
96
|
+
bundle: true,
|
|
97
|
+
chunkNames: "chunk-[hash]",
|
|
98
|
+
entryNames: "[name]",
|
|
99
|
+
entryPoints: request.entries,
|
|
100
|
+
external: request.external,
|
|
101
|
+
format: "esm",
|
|
102
|
+
logLevel: "silent",
|
|
103
|
+
minify: request.minify,
|
|
104
|
+
outdir: request.outdir,
|
|
105
|
+
platform: esbuildPlatform(request.target),
|
|
106
|
+
plugins: request.plugins,
|
|
107
|
+
splitting: true,
|
|
108
|
+
};
|
|
109
|
+
if (request.conditions) {
|
|
110
|
+
options.conditions = request.conditions;
|
|
111
|
+
}
|
|
112
|
+
if (request.define) {
|
|
113
|
+
options.define = request.define;
|
|
114
|
+
}
|
|
115
|
+
const result = await esbuild.build({ ...options, write: false });
|
|
116
|
+
return result.outputFiles.map((file) => {
|
|
117
|
+
mkdirSync(dirname(file.path), { recursive: true });
|
|
118
|
+
writeFileSync(file.path, file.contents);
|
|
119
|
+
return file.path;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
@@ -66,5 +66,17 @@ export interface BackendBuild {
|
|
|
66
66
|
plugins: BundlePlugin[];
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Several entry files bundled in one call with code splitting: each entry becomes `<outdir>/<its
|
|
71
|
+
* base name>.js`, and a module two entries import becomes one shared `<outdir>/chunk-<hash>.js`
|
|
72
|
+
* that both import, so it is one instance on a page that loads both.
|
|
73
|
+
*/
|
|
74
|
+
export interface BackendSplitBuild extends Omit<BackendBuild, "entry"> {
|
|
75
|
+
/** Absolute paths of the entry modules. Their base names must differ. */
|
|
76
|
+
entries: string[];
|
|
77
|
+
/** Absolute path of the directory the output is written to. */
|
|
78
|
+
outdir: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
69
81
|
/** Basename prefix of the throwaway entry the Bun backend writes for a source entry. */
|
|
70
82
|
export const TRANSIENT_ENTRY_PREFIX = ".jx-entry-";
|
package/src/site/bundler.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { rmSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { builtinModules } from "node:module";
|
|
16
17
|
import { tmpdir } from "node:os";
|
|
17
18
|
import { basename, join, resolve } from "node:path";
|
|
18
19
|
import { isNpmSpecifier, NPM_SPECIFIER_PREFIX } from "@jxsuite/schema/asset-paths";
|
|
@@ -150,17 +151,37 @@ function hookPlugins(opts: BundleOptions): BundlePlugin[] {
|
|
|
150
151
|
return [{ name: "jx-bundle-hooks", setup }, ...plugins];
|
|
151
152
|
}
|
|
152
153
|
|
|
154
|
+
/**
|
|
155
|
+
* Node builtins written without the `node:` prefix (`tls`, `diagnostics_channel`, ...). A package
|
|
156
|
+
* may import either spelling — postgres 4's workerd entry reaches `tls` and `diagnostics_channel`
|
|
157
|
+
* through its shared `index.js` — and `nodejs_compat` serves both at runtime.
|
|
158
|
+
*
|
|
159
|
+
* A plugin rather than `external` entries: Bun's browser target substitutes its own polyfill for a
|
|
160
|
+
* bare `os` or `fs` even when listed external, so the import has to be rewritten to `node:<name>`.
|
|
161
|
+
*/
|
|
162
|
+
const bareNodeBuiltins: BundlePlugin = {
|
|
163
|
+
name: "jx-bare-node-builtins",
|
|
164
|
+
setup(build) {
|
|
165
|
+
const names = builtinModules.filter((name) => !name.startsWith("_") && !name.includes(":"));
|
|
166
|
+
const filter = new RegExp(
|
|
167
|
+
`^(${names.map((name) => name.replaceAll("/", String.raw`\/`)).join("|")})$`,
|
|
168
|
+
);
|
|
169
|
+
build.onResolve({ filter }, (args) => ({ external: true, path: `node:${args.path}` }));
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
|
|
153
173
|
/**
|
|
154
174
|
* Per-adapter bundle options for the generated site worker (WinterTC runtimes). Cloudflare resolves
|
|
155
|
-
* with workerd conditions and keeps `cloudflare:*`/`node:*` imports
|
|
156
|
-
* provides node builtins at runtime); node/bun bundle
|
|
157
|
-
* construction.
|
|
175
|
+
* with workerd conditions and keeps `cloudflare:*`/`node:*` imports (and bare node builtins,
|
|
176
|
+
* rewritten to `node:`) external (nodejs_compat provides node builtins at runtime); node/bun bundle
|
|
177
|
+
* platform-native with builtins external by construction.
|
|
158
178
|
*/
|
|
159
179
|
export function workerBundleOptions(adapter: string): BundleOptions {
|
|
160
180
|
if (adapter === "cloudflare-workers" || adapter === "cloudflare-pages") {
|
|
161
181
|
return {
|
|
162
182
|
conditions: ["workerd", "worker"],
|
|
163
183
|
external: ["cloudflare:*", "node:*"],
|
|
184
|
+
plugins: [bareNodeBuiltins],
|
|
164
185
|
target: "workerd",
|
|
165
186
|
};
|
|
166
187
|
}
|
|
@@ -237,6 +258,21 @@ export async function bundleEntry(request: BundleRequest, opts: BundleOptions):
|
|
|
237
258
|
writeFileSync(request.outfile, code, "utf8");
|
|
238
259
|
}
|
|
239
260
|
|
|
261
|
+
/**
|
|
262
|
+
* Bundle several entry modules in one call with code splitting, into `outdir`: each entry is
|
|
263
|
+
* written as `<its base name>.js`, and a module two or more entries import is written once, as a
|
|
264
|
+
* `chunk-<hash>.js` they all import. That is what makes such a module ONE instance on a page that
|
|
265
|
+
* loads two of the entries, where {@link bundleEntry} would give each entry its own copy and its
|
|
266
|
+
* own module state. Returns the files written. Throws with the backend's diagnostics on failure.
|
|
267
|
+
*/
|
|
268
|
+
export async function bundleEntries(
|
|
269
|
+
entryPaths: string[],
|
|
270
|
+
outdir: string,
|
|
271
|
+
opts: BundleOptions,
|
|
272
|
+
): Promise<string[]> {
|
|
273
|
+
return backend.buildSplit({ entries: entryPaths, outdir, ...backendOptions(opts) });
|
|
274
|
+
}
|
|
275
|
+
|
|
240
276
|
/**
|
|
241
277
|
* Bundle one entry module and return the code rather than writing it.
|
|
242
278
|
*
|
|
@@ -323,7 +359,7 @@ export async function bundleWorkerSource(
|
|
|
323
359
|
): Promise<void> {
|
|
324
360
|
const opts = workerBundleOptions(adapter);
|
|
325
361
|
if (plugins !== undefined) {
|
|
326
|
-
opts.plugins = plugins;
|
|
362
|
+
opts.plugins = [...(opts.plugins ?? []), ...plugins];
|
|
327
363
|
}
|
|
328
364
|
await bundleSource(source, { outfile, resolveDir: projectRoot }, opts);
|
|
329
365
|
}
|
|
@@ -117,6 +117,8 @@ export function resolveClientRuntime(resolveDir: string = PACKAGE_DIR): ClientRu
|
|
|
117
117
|
assetPaths.push(mod.assetPath);
|
|
118
118
|
} else {
|
|
119
119
|
imports[mod.specifier] = mod.fallback;
|
|
120
|
+
// The CDN serves the package's subpaths under the same URL, so the prefix key follows it.
|
|
121
|
+
imports[`${mod.specifier}/`] = `${mod.fallback}/`;
|
|
120
122
|
warnings.push(
|
|
121
123
|
`Could not resolve "${mod.specifier}" — the import map falls back to ${mod.fallback}. ` +
|
|
122
124
|
"Interactive pages will load it from a third party, and a `default-src 'self'` policy " +
|
|
@@ -218,13 +220,8 @@ export function importMapAssetsInHtml(html: string): string[] {
|
|
|
218
220
|
return found;
|
|
219
221
|
}
|
|
220
222
|
|
|
221
|
-
|
|
222
|
-
export
|
|
223
|
-
const entries = Object.entries(imports)
|
|
224
|
-
.map(([name, url]) => ` ${JSON.stringify(name)}: ${JSON.stringify(url)}`)
|
|
225
|
-
.join(",\n");
|
|
226
|
-
return `<script type="importmap">\n {\n "imports": {\n${entries}\n }\n }\n </script>`;
|
|
227
|
-
}
|
|
223
|
+
// The renderer lives in `shared.ts`, beside the page-template tiers that also write a map.
|
|
224
|
+
export { renderImportMap } from "../shared.ts";
|
|
228
225
|
|
|
229
226
|
/**
|
|
230
227
|
* True when a bare specifier resolves from `resolveDir` under either backend.
|
|
@@ -251,10 +248,10 @@ const MAX_SUBPATH_PASSES = 10;
|
|
|
251
248
|
*
|
|
252
249
|
* The subpath set cannot be known before the build: it is a property of whichever third-party
|
|
253
250
|
* components a page happens to register. So it is discovered _from the output_ — every emitted
|
|
254
|
-
* `.js`
|
|
255
|
-
* directory its prefix key names, and the
|
|
256
|
-
*
|
|
257
|
-
* rather than once.
|
|
251
|
+
* `.js` file (bundles, compiled component modules, page modules) is scanned for an import of
|
|
252
|
+
* `<runtime package>/<subpath>`, each is bundled to the directory its prefix key names, and the
|
|
253
|
+
* scan repeats over what that produced. Bundling can introduce new subpaths (a directive importing
|
|
254
|
+
* another directive), so the pass runs to closure rather than once.
|
|
258
255
|
*
|
|
259
256
|
* **The subpath itself must be bundled, and only the core kept external.** A package-name external
|
|
260
257
|
* covers the package's subpaths too, so listing `lit-html` in `external` externalises the entry —
|
|
@@ -287,7 +284,6 @@ export async function writeRuntimeSubpaths(
|
|
|
287
284
|
const mirrors = new Map<string, string>();
|
|
288
285
|
/** Runtime package specifier → the core file the bundler resolves it to. */
|
|
289
286
|
const cores = new Map<string, string | undefined>();
|
|
290
|
-
const assetsDir = resolve(outDir, "assets");
|
|
291
287
|
let written = 0;
|
|
292
288
|
|
|
293
289
|
const coreOf = async (mod: RuntimeModule): Promise<string | undefined> => {
|
|
@@ -311,10 +307,13 @@ export async function writeRuntimeSubpaths(
|
|
|
311
307
|
let discovered = 0;
|
|
312
308
|
let files: string[] = [];
|
|
313
309
|
try {
|
|
314
|
-
|
|
310
|
+
/* Every module the build emitted, not only the bundles under `assets/`: a compiled component
|
|
311
|
+
(`components/<tag>.js`) and a page's own module import lit subpaths too, the keyed-list
|
|
312
|
+
directive's `repeat` among them (compiler.md §4.7). */
|
|
313
|
+
files = readdirSync(outDir, { recursive: true })
|
|
315
314
|
.map(String)
|
|
316
315
|
.filter((entry) => entry.endsWith(".js"))
|
|
317
|
-
.map((entry) => join(
|
|
316
|
+
.map((entry) => join(outDir, entry));
|
|
318
317
|
} catch {
|
|
319
318
|
return finish(outDir, mirrors, errors, written);
|
|
320
319
|
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External-class.ts — the classes state entries name, as a site build finds, loads and runs them
|
|
3
|
+
*
|
|
4
|
+
* A state entry whose `$prototype` is not a built-in names an external class (spec.md §12.3,
|
|
5
|
+
* compiler.md §3). This module is everything the build does with one, for both timings: where its
|
|
6
|
+
* `.class.json` is, which class that document means (its `$implementation`'s export, or the class
|
|
7
|
+
* generated from its schema, compiler.md §5.4), how an instance becomes a value, and the module a
|
|
8
|
+
* `timing: "client"` class ships as.
|
|
9
|
+
*
|
|
10
|
+
* @module external-class
|
|
11
|
+
* @docs extending/extensions/classes
|
|
12
|
+
* @docs framework/build
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { tmpdir } from "node:os";
|
|
19
|
+
import { dirname, join, resolve } from "node:path";
|
|
20
|
+
import { pathToFileURL } from "node:url";
|
|
21
|
+
import { isFunction, isString } from "@jxsuite/schema/guards";
|
|
22
|
+
import { parseClassDef } from "@jxsuite/schema/parse";
|
|
23
|
+
import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
|
|
24
|
+
import type {
|
|
25
|
+
JsonObject,
|
|
26
|
+
JsonValue,
|
|
27
|
+
JxClassDef,
|
|
28
|
+
JxDocumentValue,
|
|
29
|
+
JxPrototypeDef,
|
|
30
|
+
JxStateDefinition,
|
|
31
|
+
ProjectConfig,
|
|
32
|
+
} from "@jxsuite/schema/types";
|
|
33
|
+
import { compileClassJson } from "../targets/compile-class.ts";
|
|
34
|
+
import { implementationFile, importImplementation } from "./format-host.ts";
|
|
35
|
+
import type { ProjectSectionData } from "./project-sections.ts";
|
|
36
|
+
|
|
37
|
+
/** The route a document is being resolved for, as far as a class reads it. */
|
|
38
|
+
export interface ClassRoute {
|
|
39
|
+
sourcePath?: string;
|
|
40
|
+
_pathParams?: Record<string, string>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `config._project`: the project config and root, plus every loaded section under its key. */
|
|
44
|
+
export interface ClassProjectContext {
|
|
45
|
+
config: ProjectConfig | null;
|
|
46
|
+
root: string;
|
|
47
|
+
[sectionKey: string]: ProjectSectionData | ProjectConfig | string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `config._document`: the route being built and the document's whole state. */
|
|
51
|
+
export interface ClassDocumentContext {
|
|
52
|
+
route: ClassRoute;
|
|
53
|
+
state: Record<string, JxStateDefinition>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The config an external class is constructed with during a build: the entry's own non-reserved
|
|
58
|
+
* keys, plus the build host's `_project` and `_document` context.
|
|
59
|
+
*/
|
|
60
|
+
export type ExternalClassConfig = Record<
|
|
61
|
+
string,
|
|
62
|
+
JxDocumentValue | ClassProjectContext | ClassDocumentContext | undefined
|
|
63
|
+
>;
|
|
64
|
+
|
|
65
|
+
/** A class instance that computes its value: `resolve()` answers with the JSON to bake in. */
|
|
66
|
+
interface ResolvingInstance {
|
|
67
|
+
resolve: () => JsonValue | Promise<JsonValue>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A class instance that holds its value: a `value` field, or an accessor of that name. */
|
|
71
|
+
interface ValueInstance {
|
|
72
|
+
value: JsonValue;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What an external class constructs (spec.md §12.3): an instance that resolves its value, one that
|
|
77
|
+
* holds it as `value`, or one whose own fields ARE the value.
|
|
78
|
+
*/
|
|
79
|
+
export type ExternalClassInstance = ResolvingInstance | ValueInstance | JsonObject;
|
|
80
|
+
|
|
81
|
+
/** An external class, as its implementation module exports it or as its schema generates it. */
|
|
82
|
+
export type ExternalClassCtor = new (config: ExternalClassConfig) => ExternalClassInstance;
|
|
83
|
+
|
|
84
|
+
/** A state entry's class, found: its descriptor, where that is, and the export that is the class. */
|
|
85
|
+
export interface LocatedClass {
|
|
86
|
+
/** Absolute path of the `.class.json` descriptor. */
|
|
87
|
+
classJsonPath: string;
|
|
88
|
+
classDef: JxClassDef;
|
|
89
|
+
/** The export the class is read by: `$export`, else the descriptor's `title`, else the name. */
|
|
90
|
+
exportName: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Where a state entry's class is looked for. */
|
|
94
|
+
export interface ClassLookup {
|
|
95
|
+
/** The directory of the document that declares the entry; a relative `$src` resolves from it. */
|
|
96
|
+
docDir?: string | null | undefined;
|
|
97
|
+
projectRoot: string;
|
|
98
|
+
/** The document's `imports` map. */
|
|
99
|
+
imports?: Record<string, string> | undefined;
|
|
100
|
+
/** The project's extension registry, whose enabled manifest classes are found by name. */
|
|
101
|
+
registry?: ExtensionRegistry | undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Find the class a state entry names. The descriptor is the entry's `$src`, else the document's
|
|
106
|
+
* `imports` entry for the name, else an enabled extension's manifest class of that name, in that
|
|
107
|
+
* order; `undefined` when none of the three names one.
|
|
108
|
+
*
|
|
109
|
+
* A relative descriptor path resolves against the declaring document's directory, and anything else
|
|
110
|
+
* as a package specifier from the project's own `node_modules`. A descriptor that is named but
|
|
111
|
+
* cannot be read throws, naming the path.
|
|
112
|
+
*
|
|
113
|
+
* @param {JxPrototypeDef} def
|
|
114
|
+
* @param {ClassLookup} where
|
|
115
|
+
* @returns {LocatedClass | undefined}
|
|
116
|
+
*/
|
|
117
|
+
export function locateClass(def: JxPrototypeDef, where: ClassLookup): LocatedClass | undefined {
|
|
118
|
+
const src =
|
|
119
|
+
def.$src ??
|
|
120
|
+
where.imports?.[def.$prototype] ??
|
|
121
|
+
where.registry?.byName(def.$prototype)?.classPath;
|
|
122
|
+
if (!src) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let classJsonPath: string;
|
|
127
|
+
if (src.startsWith("./") || src.startsWith("../")) {
|
|
128
|
+
classJsonPath = resolve(where.docDir ?? where.projectRoot, src);
|
|
129
|
+
} else {
|
|
130
|
+
// A bare specifier or an absolute path: resolved from the project root, walking node_modules.
|
|
131
|
+
const require = createRequire(resolve(where.projectRoot, "package.json"));
|
|
132
|
+
classJsonPath = require.resolve(src);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const classDef = parseClassDef(readFileSync(classJsonPath, "utf8"), classJsonPath);
|
|
136
|
+
return {
|
|
137
|
+
classDef,
|
|
138
|
+
classJsonPath,
|
|
139
|
+
exportName: def.$export ?? classDef.title ?? def.$prototype,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Refuse a self-contained class whose `extends` is a `$ref`. The class generated for it imports its
|
|
145
|
+
* base from the sibling module a direct compile of that document writes (compiler.md §5.2, §5.6),
|
|
146
|
+
* which a site build does not write.
|
|
147
|
+
*
|
|
148
|
+
* @param {LocatedClass} located
|
|
149
|
+
*/
|
|
150
|
+
function refuseDocumentBase(located: LocatedClass): void {
|
|
151
|
+
const base = located.classDef.extends;
|
|
152
|
+
if (base !== undefined && !isString(base)) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`${located.classJsonPath} has no $implementation and extends another class document ` +
|
|
155
|
+
`("${base.$ref}"), which a site build does not compile: give it an $implementation`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Generated classes already loaded by this process, by the hash of their module text. */
|
|
161
|
+
const generatedClasses = new Map<string, Promise<ExternalClassCtor>>();
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Load the class a self-contained descriptor generates: compile it to its ES class module
|
|
165
|
+
* (compiler.md §5.5), write that to a temporary file, import it, and remove the file.
|
|
166
|
+
*
|
|
167
|
+
* The module is named by a hash of its text and kept by that hash, so the same class is loaded once
|
|
168
|
+
* however many documents name it, and a descriptor edited between two builds in one process is a
|
|
169
|
+
* different module.
|
|
170
|
+
*
|
|
171
|
+
* @param {LocatedClass} located
|
|
172
|
+
* @returns {Promise<ExternalClassCtor>}
|
|
173
|
+
*/
|
|
174
|
+
function loadGeneratedClass(located: LocatedClass): Promise<ExternalClassCtor> {
|
|
175
|
+
refuseDocumentBase(located);
|
|
176
|
+
const source = compileClassJson(located.classDef);
|
|
177
|
+
const hash = createHash("sha256").update(source).digest("hex").slice(0, 16);
|
|
178
|
+
let loading = generatedClasses.get(hash);
|
|
179
|
+
if (loading === undefined) {
|
|
180
|
+
const dir = join(tmpdir(), `jx-class-${process.pid}`);
|
|
181
|
+
mkdirSync(dir, { recursive: true });
|
|
182
|
+
const file = join(dir, `${located.classDef.title}-${hash}.mjs`);
|
|
183
|
+
writeFileSync(file, source, "utf8");
|
|
184
|
+
/* SAFETY: the module is `compileClassJson`'s output, which ends `export default <Title>`: a
|
|
185
|
+
class whose constructor takes one config object and reads members off it. */
|
|
186
|
+
loading = (import(pathToFileURL(file).href) as Promise<{ default: ExternalClassCtor }>)
|
|
187
|
+
.then((mod) => mod.default)
|
|
188
|
+
.finally(() => {
|
|
189
|
+
rmSync(file, { force: true });
|
|
190
|
+
});
|
|
191
|
+
generatedClasses.set(hash, loading);
|
|
192
|
+
}
|
|
193
|
+
return loading;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Load a located class in the build host. With an `$implementation`, the module is imported and the
|
|
198
|
+
* class is its export of the located name, or that member of its default export; without one, the
|
|
199
|
+
* class is generated from the descriptor's schema (compiler.md §5.4).
|
|
200
|
+
*
|
|
201
|
+
* @param {LocatedClass} located
|
|
202
|
+
* @returns {Promise<ExternalClassCtor>}
|
|
203
|
+
*/
|
|
204
|
+
export async function loadClass(located: LocatedClass): Promise<ExternalClassCtor> {
|
|
205
|
+
const { classDef, classJsonPath, exportName } = located;
|
|
206
|
+
if (!classDef.$implementation) {
|
|
207
|
+
return loadGeneratedClass(located);
|
|
208
|
+
}
|
|
209
|
+
const mod = await importImplementation(resolve(dirname(classJsonPath), classDef.$implementation));
|
|
210
|
+
/* SAFETY: trust boundary, the external class contract (spec.md §12.3). The export a `.class.json`
|
|
211
|
+
names as its implementation is written as a class taking this config; that it is a function is
|
|
212
|
+
all that can be checked before `new`, which the guard below does, and its instance is read only
|
|
213
|
+
through the optional members `instantiateAndResolve` checks. */
|
|
214
|
+
const exported = (mod[exportName] ?? mod.default?.[exportName]) as
|
|
215
|
+
| ExternalClassCtor
|
|
216
|
+
| null
|
|
217
|
+
| undefined;
|
|
218
|
+
if (!isFunction(exported)) {
|
|
219
|
+
throw new Error(`Module ${classDef.$implementation} does not export "${exportName}"`);
|
|
220
|
+
}
|
|
221
|
+
return exported;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether a constructed instance computes its value through `resolve()`. */
|
|
225
|
+
function isResolvingInstance(instance: ExternalClassInstance): instance is ResolvingInstance {
|
|
226
|
+
return "resolve" in instance && isFunction(instance.resolve);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Whether a constructed instance holds its value as `value`, own or inherited. */
|
|
230
|
+
function isValueInstance(instance: ExternalClassInstance): instance is ValueInstance {
|
|
231
|
+
return "value" in instance;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Construct an external class and take its value, by the order spec.md §12.3 states: `resolve()`
|
|
236
|
+
* when the instance has one, else `value` when it has that, else the instance itself. The browser
|
|
237
|
+
* half of the same rule is `externalClassHelperSource()` (`shared.ts`).
|
|
238
|
+
*
|
|
239
|
+
* @param {ExternalClassCtor} Ctor
|
|
240
|
+
* @param {ExternalClassConfig} config
|
|
241
|
+
* @returns {Promise<{ value: JsonValue; instance: ExternalClassInstance }>}
|
|
242
|
+
*/
|
|
243
|
+
export async function instantiateAndResolve(
|
|
244
|
+
Ctor: ExternalClassCtor,
|
|
245
|
+
config: ExternalClassConfig,
|
|
246
|
+
): Promise<{ value: JsonValue; instance: ExternalClassInstance }> {
|
|
247
|
+
const instance = new Ctor(config);
|
|
248
|
+
if (isResolvingInstance(instance)) {
|
|
249
|
+
return { instance, value: await instance.resolve() };
|
|
250
|
+
}
|
|
251
|
+
if (isValueInstance(instance)) {
|
|
252
|
+
return { instance, value: instance.value };
|
|
253
|
+
}
|
|
254
|
+
return { instance, value: instance };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Whether a class descriptor reads the build host's context (`#/$context/…`): a content
|
|
259
|
+
* collection's types, a connector's connections. A browser cannot supply that, so such a class runs
|
|
260
|
+
* only during the build.
|
|
261
|
+
*
|
|
262
|
+
* @param {JxClassDef} classDef
|
|
263
|
+
* @returns {boolean}
|
|
264
|
+
*/
|
|
265
|
+
export function readsBuildContext(classDef: JxClassDef): boolean {
|
|
266
|
+
return JSON.stringify(classDef).includes('"#/$context/');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The entry module a `timing: "client"` class is bundled from (compiler.md §12): a module whose
|
|
271
|
+
* default export is the class. With an `$implementation` it re-exports that module's class, by the
|
|
272
|
+
* lookup {@link loadClass} makes; without one it is the class generated from the schema.
|
|
273
|
+
*
|
|
274
|
+
* @param {LocatedClass} located
|
|
275
|
+
* @returns {string}
|
|
276
|
+
*/
|
|
277
|
+
export function classEntrySource(located: LocatedClass): string {
|
|
278
|
+
const { classDef, classJsonPath, exportName } = located;
|
|
279
|
+
if (!classDef.$implementation) {
|
|
280
|
+
refuseDocumentBase(located);
|
|
281
|
+
return compileClassJson(classDef);
|
|
282
|
+
}
|
|
283
|
+
const file = implementationFile(resolve(dirname(classJsonPath), classDef.$implementation));
|
|
284
|
+
const name = JSON.stringify(exportName);
|
|
285
|
+
return [
|
|
286
|
+
`import * as m from ${JSON.stringify(file)};`,
|
|
287
|
+
`export default m[${name}] ?? m.default?.[${name}];`,
|
|
288
|
+
"",
|
|
289
|
+
].join("\n");
|
|
290
|
+
}
|