@flanksource/page-runtime 0.0.0-stage → 0.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.
- package/LICENSE +17 -0
- package/README.md +494 -2
- package/dist/build/README.md +96 -0
- package/dist/build/cjs-export-names.mjs +24 -0
- package/dist/build/dependencies.mjs +279 -0
- package/dist/build/dependencies.mjs.map +1 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs +2130 -0
- package/dist/build/dependency-cache-Zg-FGasE.mjs.map +1 -0
- package/dist/build/index.mjs +42 -0
- package/dist/build/index.mjs.map +1 -0
- package/dist/build/package.json +19 -0
- package/dist/build/types/activity-schema.d.ts +62 -0
- package/dist/build/types/build/barrels.d.ts +70 -0
- package/dist/build/types/build/base.d.ts +2 -0
- package/dist/build/types/build/browser-runtime-exports.d.ts +19 -0
- package/dist/build/types/build/check-fragment.d.ts +5 -0
- package/dist/build/types/build/commonjs-exports.d.ts +5 -0
- package/dist/build/types/build/convert-commonjs.d.ts +12 -0
- package/dist/build/types/build/dependencies.d.ts +6 -0
- package/dist/build/types/build/dependency-barrel-index.d.ts +5 -0
- package/dist/build/types/build/dependency-barrels.d.ts +7 -0
- package/dist/build/types/build/dependency-cache.d.ts +7 -0
- package/dist/build/types/build/dependency-optional.d.ts +4 -0
- package/dist/build/types/build/dependency-plugin.d.ts +8 -0
- package/dist/build/types/build/dependency-runtime.d.ts +20 -0
- package/dist/build/types/build/dependency-workers.d.ts +8 -0
- package/dist/build/types/build/errors.d.ts +9 -0
- package/dist/build/types/build/fragment.d.ts +13 -0
- package/dist/build/types/build/index.d.ts +7 -0
- package/dist/build/types/build/library-runtime.d.ts +21 -0
- package/dist/build/types/build/module-utils.d.ts +3 -0
- package/dist/build/types/build/recipe-dependencies.d.ts +2 -0
- package/dist/build/types/build/runtime-entries.d.ts +4 -0
- package/dist/build/types/build/runtime-layer.d.ts +17 -0
- package/dist/build/types/build/trace.d.ts +140 -0
- package/dist/build/types/design-schema.d.ts +98 -0
- package/dist/build/types/host/agent-source.d.ts +2 -0
- package/dist/build/types/host/agent-validation.d.ts +3 -0
- package/dist/build/types/host/design-validation.d.ts +2 -0
- package/dist/build/types/host/message-values.d.ts +8 -0
- package/dist/build/types/host/review/validation.d.ts +5 -0
- package/dist/build/types/host/validation.d.ts +6 -0
- package/dist/build/types/link/page-sources.d.ts +31 -0
- package/dist/build/types/link/types.d.ts +62 -0
- package/dist/build/types/link/validation.d.ts +9 -0
- package/dist/build/types/markers.d.ts +10 -0
- package/dist/build/types/review-schema.d.ts +60 -0
- package/dist/build/types/schema.d.ts +319 -0
- package/dist/build/types/sw/barrels.d.ts +9 -0
- package/dist/build/types/sw/compiler-plugins.d.ts +6 -0
- package/dist/build/types/sw/composition.d.ts +8 -0
- package/dist/build/types/sw/module-transform.d.ts +68 -0
- package/dist/build/types/sw/profile.d.ts +7 -0
- package/dist/build/types/sw/source-provider.d.ts +7 -0
- package/dist/build/types/sw/versions.d.ts +10 -0
- package/dist/node/catalog.mjs +1 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs +229 -0
- package/dist/node/chunks/publication-RchcQvxD.mjs.map +1 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs +12 -0
- package/dist/node/chunks/schema-CaRTfg2x.mjs.map +1 -0
- package/dist/node/dev.mjs +410 -0
- package/dist/node/dev.mjs.map +1 -0
- package/dist/node/publication/cli.mjs +13 -0
- package/dist/node/publication/cli.mjs.map +1 -0
- package/dist/node/publication.mjs +1 -0
- package/dist/node/schema.mjs +1 -0
- package/dist/node/styles.mjs +49 -0
- package/dist/node/styles.mjs.map +1 -0
- package/dist/static/boot.js +40938 -0
- package/dist/static/boot.js.map +1 -0
- package/dist/static/bootstrap.html +1 -0
- package/dist/static/devtools-hook.js +118 -0
- package/dist/static/document-bundle.js +1 -0
- package/dist/static/document.js +2621 -0
- package/dist/static/editing.js +37 -0
- package/dist/static/export-compiler.js +81521 -0
- package/dist/static/export-compiler.js.map +1 -0
- package/dist/static/page-agent.js +17193 -0
- package/dist/static/page-agent.js.map +1 -0
- package/dist/static/sw.js +86112 -0
- package/dist/static/sw.js.map +1 -0
- package/package.json +110 -3
- package/scripts/build-builder.ts +27 -0
- package/scripts/build-library-runtime.ts +9 -0
- package/scripts/build-node.ts +26 -0
- package/scripts/build-static.ts +86 -0
- package/scripts/build.ts +7 -0
- package/scripts/check-fragment.ts +12 -0
- package/scripts/local-workspaces.ts +55 -0
- package/scripts/react-externals.ts +18 -0
- package/scripts/release-version.ts +47 -0
- package/scripts/run-package-build.ts +8 -0
- package/scripts/serve-packages.ts +8 -0
- package/src/activity-schema.ts +92 -0
- package/src/build/README.md +96 -0
- package/src/build/barrels.ts +306 -0
- package/src/build/base.ts +2 -0
- package/src/build/browser-runtime-exports.ts +52 -0
- package/src/build/check-fragment.ts +45 -0
- package/src/build/cjs-export-names.mjs +24 -0
- package/src/build/commonjs-exports.ts +24 -0
- package/src/build/convert-commonjs.ts +183 -0
- package/src/build/dependencies.ts +6 -0
- package/src/build/dependency-barrel-index.ts +48 -0
- package/src/build/dependency-barrels.ts +80 -0
- package/src/build/dependency-cache.ts +40 -0
- package/src/build/dependency-optional.ts +15 -0
- package/src/build/dependency-plugin.ts +58 -0
- package/src/build/dependency-runtime.ts +182 -0
- package/src/build/dependency-workers.ts +41 -0
- package/src/build/errors.ts +9 -0
- package/src/build/fragment.ts +89 -0
- package/src/build/index.ts +7 -0
- package/src/build/library-runtime.ts +101 -0
- package/src/build/module-utils.ts +11 -0
- package/src/build/recipe-dependencies.ts +14 -0
- package/src/build/runtime-entries.ts +10 -0
- package/src/build/runtime-layer.ts +99 -0
- package/src/build/trace.ts +431 -0
- package/src/design-schema.ts +25 -0
- package/src/dev/README.md +78 -0
- package/src/dev/catalog.ts +79 -0
- package/src/dev/cli.ts +25 -0
- package/src/dev/index.ts +118 -0
- package/src/dev/runtime-origin.ts +63 -0
- package/src/editing.ts +25 -0
- package/src/form/entry-source.ts +68 -0
- package/src/form/form-page.ts +63 -0
- package/src/form/index.ts +2 -0
- package/src/form/source-update.ts +17 -0
- package/src/frame/activity.browser.ts +34 -0
- package/src/frame/activity.ts +52 -0
- package/src/frame/agent/README.md +47 -0
- package/src/frame/agent/agent.browser.ts +127 -0
- package/src/frame/agent/design.ts +62 -0
- package/src/frame/agent/frame-layout.ts +54 -0
- package/src/frame/agent/index.ts +151 -0
- package/src/frame/agent/overlay.ts +104 -0
- package/src/frame/agent/owner.ts +61 -0
- package/src/frame/agent/provider.tsx +14 -0
- package/src/frame/agent/react-override.ts +55 -0
- package/src/frame/agent/review.browser.ts +65 -0
- package/src/frame/agent/review.ts +108 -0
- package/src/frame/agent/testing/callsite.tsx +5 -0
- package/src/frame/agent/testing/client.ts +99 -0
- package/src/frame/agent/testing/library.ts +3 -0
- package/src/frame/agent/testing/modal.tsx +5 -0
- package/src/frame/agent/testing/review-client.ts +43 -0
- package/src/frame/agent/testing/review-server.ts +31 -0
- package/src/frame/agent/testing/server.ts +72 -0
- package/src/frame/agent/testing/vocabulary-host.ts +20 -0
- package/src/frame/agent/testing/vocabulary.tsx +10 -0
- package/src/frame/agent/vitest.browser.config.ts +6 -0
- package/src/frame/agent/vocabulary.browser.ts +30 -0
- package/src/frame/agent/vocabulary.ts +13 -0
- package/src/frame/agent.ts +3 -0
- package/src/frame/boot-styles.ts +50 -0
- package/src/frame/boot.ts +269 -0
- package/src/frame/bridge.ts +27 -0
- package/src/frame/devtools-hook.ts +1 -0
- package/src/frame/document-assets.ts +76 -0
- package/src/frame/document-entry.ts +68 -0
- package/src/frame/document-modules.ts +113 -0
- package/src/frame/document-mount.ts +32 -0
- package/src/frame/entry.ts +4 -0
- package/src/frame/export-compiler.ts +18 -0
- package/src/frame/export-page.ts +61 -0
- package/src/frame/export.ts +89 -0
- package/src/frame/index.ts +8 -0
- package/src/frame/local-runtime.browser.ts +36 -0
- package/src/frame/mount-page.ts +36 -0
- package/src/frame/page-agent.ts +2 -0
- package/src/frame/readiness.ts +51 -0
- package/src/frame/render-job.ts +101 -0
- package/src/frame/review-integration.browser.ts +48 -0
- package/src/frame/runtime.browser.ts +90 -0
- package/src/frame/tailwind/README.md +49 -0
- package/src/frame/tailwind/boot-styles.browser.ts +18 -0
- package/src/frame/tailwind/cache.ts +20 -0
- package/src/frame/tailwind/load.ts +75 -0
- package/src/frame/tailwind/recipe.ts +76 -0
- package/src/frame/tailwind/runtime.ts +113 -0
- package/src/frame/tailwind/store.ts +55 -0
- package/src/frame/tailwind/stylesheets.ts +42 -0
- package/src/frame/tailwind/tailwind.browser.ts +71 -0
- package/src/frame/tailwind/testing/client.ts +133 -0
- package/src/frame/tailwind/testing/compare.ts +91 -0
- package/src/frame/tailwind/testing/pages.ts +14 -0
- package/src/frame/tailwind/testing/server.ts +89 -0
- package/src/frame/tailwind/vitest.browser.config.ts +7 -0
- package/src/frame/testing/boot-layout.ts +3 -0
- package/src/frame/testing/boot-page.ts +3 -0
- package/src/frame/testing/host.ts +78 -0
- package/src/frame/testing/local-host.tsx +33 -0
- package/src/frame/testing/server.ts +135 -0
- package/src/host/BuildLog.tsx +28 -0
- package/src/host/DEBUG_CONSOLE.md +13 -0
- package/src/host/PageForm.tsx +63 -0
- package/src/host/PageFrame.tsx +49 -0
- package/src/host/RuntimeActivity.tsx +77 -0
- package/src/host/RuntimeDebugPanel.tsx +18 -0
- package/src/host/activity-state.ts +69 -0
- package/src/host/agent-source.ts +14 -0
- package/src/host/agent-validation.ts +73 -0
- package/src/host/bridge.ts +56 -0
- package/src/host/build-log.ts +29 -0
- package/src/host/clear-cache.ts +66 -0
- package/src/host/debug-runtime.tsx +17 -0
- package/src/host/design-validation.ts +96 -0
- package/src/host/index.ts +12 -0
- package/src/host/link/index.ts +66 -0
- package/src/host/link/transport.ts +68 -0
- package/src/host/link/watch.ts +62 -0
- package/src/host/message-values.ts +55 -0
- package/src/host/origin.ts +7 -0
- package/src/host/review/README.md +32 -0
- package/src/host/review/index.ts +43 -0
- package/src/host/review/validation.ts +55 -0
- package/src/host/runtime-diagnostics.ts +41 -0
- package/src/host/validation.ts +148 -0
- package/src/link/README.md +115 -0
- package/src/link/barrels.ts +5 -0
- package/src/link/build-cli.ts +12 -0
- package/src/link/build.ts +99 -0
- package/src/link/commonjs.ts +39 -0
- package/src/link/examples/server.ts +18 -0
- package/src/link/index.ts +6 -0
- package/src/link/link.browser.ts +66 -0
- package/src/link/local-relay.browser.ts +22 -0
- package/src/link/overrides.ts +69 -0
- package/src/link/page-sources.ts +69 -0
- package/src/link/source.ts +25 -0
- package/src/link/storage.ts +32 -0
- package/src/link/testing/client.ts +96 -0
- package/src/link/testing/folder.ts +19 -0
- package/src/link/testing/local-client.ts +30 -0
- package/src/link/testing/local-server.ts +26 -0
- package/src/link/testing/local-worker.ts +17 -0
- package/src/link/testing/server.ts +131 -0
- package/src/link/testing/worker.ts +32 -0
- package/src/link/testing-cache.ts +20 -0
- package/src/link/testing-fixtures.ts +16 -0
- package/src/link/types.ts +27 -0
- package/src/link/validation.ts +44 -0
- package/src/link/vitest.browser.config.ts +3 -0
- package/src/markers.ts +18 -0
- package/src/publication/build.ts +27 -0
- package/src/publication/fixtures/build.mjs +2 -0
- package/src/publication/index.ts +3 -0
- package/src/publication/lock.ts +32 -0
- package/src/publication/manifest.ts +14 -0
- package/src/publication/publish.ts +80 -0
- package/src/publication/runtime.ts +28 -0
- package/src/publication/schema.ts +13 -0
- package/src/review-schema.ts +17 -0
- package/src/schema.ts +175 -0
- package/src/storage/db.ts +64 -0
- package/src/styles.ts +40 -0
- package/src/sw/activity.ts +66 -0
- package/src/sw/barrels.ts +44 -0
- package/src/sw/candidates.ts +14 -0
- package/src/sw/compile.ts +92 -0
- package/src/sw/compiler-columns.ts +44 -0
- package/src/sw/compiler-internals.d.ts +8 -0
- package/src/sw/compiler-plugins.ts +18 -0
- package/src/sw/compiler.ts +93 -0
- package/src/sw/composition.ts +86 -0
- package/src/sw/content-types.ts +28 -0
- package/src/sw/converted.browser.ts +31 -0
- package/src/sw/converted.ts +64 -0
- package/src/sw/editable-sites.ts +42 -0
- package/src/sw/errors.ts +30 -0
- package/src/sw/esm-sh-fixtures/browser-client.ts +18 -0
- package/src/sw/esm-sh-fixtures/browser-server.ts +104 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.headers +13 -0
- package/src/sw/esm-sh-fixtures/fixtures/copy-to-clipboard-module.mjs.txt +142 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.headers +15 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/react-copy-to-clipboard-module.mjs.txt +222 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.headers +14 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-entry.mjs.txt +3 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.headers +11 -0
- package/src/sw/esm-sh-fixtures/fixtures/toggle-selection-module.mjs.txt +76 -0
- package/src/sw/esm-sh-fixtures/fixtures.ts +54 -0
- package/src/sw/esm-sh-fixtures/redact.ts +1 -0
- package/src/sw/index.ts +7 -0
- package/src/sw/integrity.ts +10 -0
- package/src/sw/legacy-storage.ts +18 -0
- package/src/sw/link-activity.ts +21 -0
- package/src/sw/link-cache.ts +19 -0
- package/src/sw/link-compiler.ts +120 -0
- package/src/sw/link-folder.ts +29 -0
- package/src/sw/link-relay.ts +40 -0
- package/src/sw/link-route.ts +239 -0
- package/src/sw/link-source.ts +41 -0
- package/src/sw/markers.ts +128 -0
- package/src/sw/module-transform.ts +364 -0
- package/src/sw/page-clients.ts +45 -0
- package/src/sw/profile.ts +90 -0
- package/src/sw/resolver.ts +224 -0
- package/src/sw/router.ts +360 -0
- package/src/sw/runtime-exports.ts +39 -0
- package/src/sw/runtime-module.ts +13 -0
- package/src/sw/source-hash.ts +37 -0
- package/src/sw/source-provider.ts +20 -0
- package/src/sw/versions.ts +96 -0
- package/src/sw/worker.ts +91 -0
- package/static/README.md +15 -0
- package/static/profile.example.json +15 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type { BarrelIndex, DependencyPolicy, FolderManifest, Fragment, PageLock, RuntimePolicy, RuntimeProfile } from "../schema.ts";
|
|
2
|
+
import { BASE_PACKAGES, composeFragments, mergeBarrels, packageName } from "./composition.ts";
|
|
3
|
+
import { chooseVersion, satisfiesVersion } from "./versions.ts";
|
|
4
|
+
import { validateProfile } from "./profile.ts";
|
|
5
|
+
import { guardedBarrels } from "./barrels.ts";
|
|
6
|
+
import { digest } from "./integrity.ts";
|
|
7
|
+
import { CONVERTED_ENTRY, crawlConvertedPackage } from "./converted.ts";
|
|
8
|
+
import type { LibraryLink } from "../link/types.ts";
|
|
9
|
+
import { assertLinksAllowed, validateLink } from "../link/validation.ts";
|
|
10
|
+
import { composeLinkOverrides } from "../link/overrides.ts";
|
|
11
|
+
import { applyRuntimeExports } from "./runtime-exports.ts";
|
|
12
|
+
|
|
13
|
+
export type PackageManifest = { name: string; version: string; type?: string; main?: string; module?: string; exports?: unknown; dependencies?: Record<string, string>; peerDependencies?: Record<string, string>; sideEffects?: boolean | string[] };
|
|
14
|
+
type Metadata = { versions: Record<string, PackageManifest>; time: Record<string, string> };
|
|
15
|
+
export type ResolveOptions = { page: string; profile: RuntimeProfile; manifest: FolderManifest; lock?: PageLock; fetch?: typeof fetch; now?: number; links?: readonly LibraryLink[]; developerOverrides?: boolean; runtimeExportsUrl?: string };
|
|
16
|
+
class CommonJsOnlyError extends Error {}
|
|
17
|
+
|
|
18
|
+
export async function fetchJson<T>(fetcher: typeof fetch, url: string): Promise<T> {
|
|
19
|
+
const response = await fetcher(url, { credentials: "omit", mode: "cors" });
|
|
20
|
+
if (!response.ok) throw new Error(`fetch ${url}: HTTP ${response.status}`);
|
|
21
|
+
return response.json() as Promise<T>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function checkPeers(options: { manifest: PackageManifest; versions: Record<string, string>; declaration: string }): void {
|
|
25
|
+
for (const [name, range] of Object.entries(options.manifest.peerDependencies ?? {})) {
|
|
26
|
+
if (!BASE_PACKAGES.includes(name)) continue;
|
|
27
|
+
const chosen = options.versions[name];
|
|
28
|
+
if (!chosen || !satisfiesVersion(chosen, range)) throw new Error(`${options.manifest.name}@${options.manifest.version} peer ${name} ${range} (package.json) rejects ${chosen ?? "missing"} (${options.declaration})`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function esmEntries(manifest: PackageManifest): Record<string, string> {
|
|
33
|
+
const target = (value: unknown): string | null => {
|
|
34
|
+
if (typeof value === "string") return value;
|
|
35
|
+
if (value === null) return null;
|
|
36
|
+
if (Array.isArray(value)) throw new Error(`${manifest.name}: export arrays are not supported`);
|
|
37
|
+
if (typeof value !== "object") throw new Error(`${manifest.name}: invalid exports target`);
|
|
38
|
+
for (const [condition, item] of Object.entries(value)) if (["browser", "import", "default"].includes(condition)) return target(item);
|
|
39
|
+
return null;
|
|
40
|
+
};
|
|
41
|
+
const entries: Record<string, string> = {};
|
|
42
|
+
if (manifest.exports !== undefined) {
|
|
43
|
+
const subpaths = typeof manifest.exports === "object" && manifest.exports !== null && Object.keys(manifest.exports).some((k) => k.startsWith("."));
|
|
44
|
+
for (const [key, value] of Object.entries(subpaths ? manifest.exports as Record<string, unknown> : { ".": manifest.exports })) {
|
|
45
|
+
const path = target(value);
|
|
46
|
+
if (path) entries[`${manifest.name}${key.slice(1)}`] = path;
|
|
47
|
+
}
|
|
48
|
+
} else if (manifest.module || manifest.type === "module") entries[manifest.name] = manifest.module ?? manifest.main ?? "./index.js";
|
|
49
|
+
else throw new CommonJsOnlyError(`${manifest.name}@${manifest.version} is CommonJS-only; additional packages must ship ESM`);
|
|
50
|
+
if (!Object.keys(entries).length) throw new Error(`${manifest.name}: no browser ESM exports`);
|
|
51
|
+
return entries;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Node's rule per entry: `.mjs` is ESM, `.cjs` is CommonJS, and `.js` follows the nearest package.json `type`
|
|
56
|
+
* at or above the file (yaml@2 marks its `browser/` build with a nested `{"type":"module"}`). A `module` field or an
|
|
57
|
+
* `import` export condition is the bundler convention that also marks ESM.
|
|
58
|
+
*/
|
|
59
|
+
export async function assertEsmEntries(options: { manifest: PackageManifest; entries: Record<string, string>; files: ReadonlySet<string>; readType: (dir: string) => Promise<string | undefined> }): Promise<void> {
|
|
60
|
+
const { manifest } = options;
|
|
61
|
+
const bundlerEsm = Boolean(manifest.module) || JSON.stringify(manifest.exports ?? null).includes('"import"');
|
|
62
|
+
const nearestType = async (file: string): Promise<string | undefined> => {
|
|
63
|
+
const dirs = file.split("/").slice(0, -1);
|
|
64
|
+
for (let depth = dirs.length; depth > 0; depth--) {
|
|
65
|
+
const dir = dirs.slice(0, depth).join("/");
|
|
66
|
+
if (options.files.has(`/${dir}/package.json`)) return options.readType(dir);
|
|
67
|
+
}
|
|
68
|
+
return manifest.type;
|
|
69
|
+
};
|
|
70
|
+
for (const path of Object.values(options.entries)) {
|
|
71
|
+
const file = path.replace(/^\.\//, "").split("*")[0]!;
|
|
72
|
+
// JSON and CSS entries (e.g. "./package.json") are served as JSON and stylesheet modules, not judged as scripts.
|
|
73
|
+
if (path.endsWith(".mjs") || /\.(json|css)$/.test(path)) continue;
|
|
74
|
+
if (!path.endsWith(".cjs") && (bundlerEsm || await nearestType(file) === "module")) continue;
|
|
75
|
+
throw new CommonJsOnlyError(`${manifest.name}: ${path} is CommonJS-only; additional packages must ship ESM`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A declared package that `policy` rejects; `package` and `policy` let hosts offer a fix. */
|
|
80
|
+
export class DependencyPolicyError extends Error {
|
|
81
|
+
constructor(readonly page: string, readonly package_: string, readonly policy: DependencyPolicy) {
|
|
82
|
+
super(`${page}: package ${package_} is not allowed by dependency policy ${policy}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function allowsDependency(policy: RuntimePolicy, name: string): boolean {
|
|
87
|
+
return policy.dependencies === "any" || (policy.allow ?? []).some((pattern) => new RegExp(`^${pattern.split("*").map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`).test(name));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function resolvePage(options: ResolveOptions): Promise<PageLock> {
|
|
91
|
+
const profile = validateProfile(options.profile);
|
|
92
|
+
const links = [...(options.links ?? [])];
|
|
93
|
+
if (links.length) {
|
|
94
|
+
assertLinksAllowed({ profile, developerOverrides: options.developerOverrides === true });
|
|
95
|
+
for (const link of links) validateLink(link);
|
|
96
|
+
if (new Set(links.map(link => link.build.library)).size !== links.length) throw new Error("Duplicate local package overrides");
|
|
97
|
+
}
|
|
98
|
+
if (options.lock) {
|
|
99
|
+
if (options.lock.lock !== 2 || options.lock.page !== options.page) throw new Error(`${options.page}: lock does not match page`);
|
|
100
|
+
return options.lock;
|
|
101
|
+
}
|
|
102
|
+
const fetcher = options.fetch ?? fetch; const now = options.now ?? Date.now();
|
|
103
|
+
const requests = { ...profile.managed, ...profile.dependencies, ...options.manifest.dependencies, ...options.manifest.pageRuntime?.pages?.[options.page] };
|
|
104
|
+
if (profile.runtimeExports) Object.assign(requests, profile.managed);
|
|
105
|
+
const versions: Record<string, string> = {}; const manifests: PackageManifest[] = []; const fragments: Fragment[] = []; const indices: BarrelIndex[] = [];
|
|
106
|
+
const required = ["@flanksource/clicky-ui", "@flanksource/facet"];
|
|
107
|
+
for (const name of [...required, ...Object.keys(profile.managed).filter(name => !required.includes(name)).sort()]) {
|
|
108
|
+
if (!requests[name]) throw new Error(`${options.page}: missing managed range for ${name}`);
|
|
109
|
+
const local = links.find(link => link.build.library === name);
|
|
110
|
+
if (local) {
|
|
111
|
+
versions[name] = local.build.version;
|
|
112
|
+
manifests.push({ name, version: local.build.version, ...local.build.package });
|
|
113
|
+
fragments.push(local.build.fragment); indices.push(local.build.barrels);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const metadata = await fetchJson<Metadata>(fetcher, `${profile.registry.replace(/\/$/, "")}/${encodeURIComponent(name)}`);
|
|
117
|
+
const chosen = chooseVersion({ name, range: requests[name], times: metadata.time, ageDays: profile.minReleaseAgeDays, now });
|
|
118
|
+
const manifest = metadata.versions[chosen];
|
|
119
|
+
if (!manifest) throw new Error(`${name}: metadata missing ${chosen}`);
|
|
120
|
+
versions[name] = chosen; manifests.push(manifest);
|
|
121
|
+
fragments.push(await fetchJson<Fragment>(fetcher, `${profile.packageOrigin.replace(/\/$/, "")}/${name}@${chosen}/dist/runtime/importmap.json`));
|
|
122
|
+
const index = await fetchJson<BarrelIndex>(fetcher, `${profile.packageOrigin.replace(/\/$/, "")}/${name}@${chosen}/dist/runtime/barrels.json`);
|
|
123
|
+
indices.push(guardedBarrels({ index, name, version: chosen, ...(manifest.sideEffects !== undefined ? { sideEffects: manifest.sideEffects } : {}) }));
|
|
124
|
+
}
|
|
125
|
+
const composed = composeFragments({ fragments });
|
|
126
|
+
for (const name of BASE_PACKAGES) {
|
|
127
|
+
const mapped = composed.map.imports[name];
|
|
128
|
+
const found = mapped?.match(new RegExp(`${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}@([^/]+)/`));
|
|
129
|
+
if (found?.[1]) versions[name] = found[1];
|
|
130
|
+
}
|
|
131
|
+
const facet = manifests[1]!;
|
|
132
|
+
const facetRange = facet.dependencies?.["@flanksource/clicky-ui"] ?? facet.peerDependencies?.["@flanksource/clicky-ui"];
|
|
133
|
+
if (!facetRange || !satisfiesVersion(versions["@flanksource/clicky-ui"]!, facetRange)) throw new Error(`${facet.name}@${facet.version} declares @flanksource/clicky-ui ${facetRange ?? "missing"} (package.json), rejects ${versions["@flanksource/clicky-ui"]} (folder/page override)`);
|
|
134
|
+
const pinned = profile.runtimeExports ? applyRuntimeExports(await fetchJson(fetcher, options.runtimeExportsUrl ?? new URL("/runtime-exports.json", profile.packageOrigin).href), composed, versions) : {};
|
|
135
|
+
const additional = Object.entries(requests).filter(([name]) => !Object.hasOwn(pinned, name) && !Object.hasOwn(profile.managed, name) && !manifests.some((m) => m.name === name) && !links.some(link => link.build.library === name));
|
|
136
|
+
const listings: Record<string, string> = {};
|
|
137
|
+
for (const [name, range] of additional) {
|
|
138
|
+
if (BASE_PACKAGES.includes(name)) throw new Error(`${options.page}: ${name} is part of the shared runtime set and cannot be declared as a dependency`);
|
|
139
|
+
if (!allowsDependency(profile.policy, name)) throw new DependencyPolicyError(options.page, name, profile.policy.dependencies);
|
|
140
|
+
const imports = await addEsmPackage({ name, range, profile, now, fetcher, versions, composed, listings, visiting: new Set(), links });
|
|
141
|
+
Object.assign(composed.map.imports, imports);
|
|
142
|
+
}
|
|
143
|
+
const lock: PageLock = { lock: 2, packageOrigin: profile.packageOrigin, page: options.page, versions, ...composed, barrels: mergeBarrels(indices), ...(additional.length ? { listings } : {}) };
|
|
144
|
+
for (const link of links) checkPeers({ manifest: { name: link.build.library, version: link.build.version, ...link.build.package }, versions, declaration: "local checkout" });
|
|
145
|
+
return links.length ? composeLinkOverrides({ lock, links, profile, developerOverrides: true }) : lock;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
type AdditionalOptions = { name: string; range: string; profile: RuntimeProfile; now: number; fetcher: typeof fetch; versions: Record<string, string>; composed: ReturnType<typeof composeFragments>; listings: Record<string, string>; visiting: Set<string>; links: LibraryLink[] };
|
|
149
|
+
|
|
150
|
+
async function addEsmPackage(options: AdditionalOptions): Promise<Record<string, string>> {
|
|
151
|
+
const { name, range, profile, fetcher, versions, composed, now } = options;
|
|
152
|
+
const local = options.links.find(link => link.build.library === name);
|
|
153
|
+
if (local) {
|
|
154
|
+
versions[name] = local.build.version;
|
|
155
|
+
return Object.fromEntries(Object.entries(local.build.entries).map(([specifier, path]) => [specifier, `/link/${local.id}/${path}`]));
|
|
156
|
+
}
|
|
157
|
+
const metadata = await fetchJson<Metadata>(fetcher, `${profile.registry.replace(/\/$/, "")}/${encodeURIComponent(name)}`);
|
|
158
|
+
const chosen = chooseVersion({ name, range, times: metadata.time, ageDays: profile.minReleaseAgeDays, now });
|
|
159
|
+
const manifest = metadata.versions[chosen];
|
|
160
|
+
if (!manifest) throw new Error(`${name}: missing manifest ${chosen}`);
|
|
161
|
+
const root = `${name}@${chosen}`;
|
|
162
|
+
const origin = `${profile.packageOrigin.replace(/\/$/, "")}/${root}`;
|
|
163
|
+
const convertOrThrow = (error: unknown) => {
|
|
164
|
+
if (!(error instanceof CommonJsOnlyError) || !profile.convert) throw error;
|
|
165
|
+
checkPeers({ manifest, versions, declaration: "composed base set" });
|
|
166
|
+
return addConvertedPackage({ ...options, manifest });
|
|
167
|
+
};
|
|
168
|
+
let entries: Record<string, string>;
|
|
169
|
+
try { entries = esmEntries(manifest); }
|
|
170
|
+
catch (error) { return convertOrThrow(error); }
|
|
171
|
+
checkPeers({ manifest, versions, declaration: "composed base set" });
|
|
172
|
+
const listing = await fetchJson<{ files: Array<{ path: string; integrity: string }> }>(fetcher, `${origin}/?meta`);
|
|
173
|
+
try { await assertEsmEntries({ manifest, entries, files: new Set(listing.files.map(file => file.path)), readType: async dir => (await fetchJson<{ type?: string }>(fetcher, `${origin}/${dir}/package.json`)).type }); }
|
|
174
|
+
catch (error) { return convertOrThrow(error); }
|
|
175
|
+
options.listings[root] = await digest(new TextEncoder().encode(JSON.stringify(listing)));
|
|
176
|
+
for (const file of listing.files) {
|
|
177
|
+
if (!file.integrity) throw new Error(`${root}${file.path}: file listing has no integrity`);
|
|
178
|
+
composed.integrity[`${root}/${file.path.replace(/^\//, "")}`] = file.integrity;
|
|
179
|
+
}
|
|
180
|
+
const paths = Object.keys(composed.integrity).filter((p) => p.startsWith(`${root}/`));
|
|
181
|
+
const imports: Record<string, string> = {};
|
|
182
|
+
for (const [specifier, path] of Object.entries(entries)) {
|
|
183
|
+
if (specifier.includes("*")) {
|
|
184
|
+
const [prefix, suffix = ""] = path.replace(/^\.\//, "").split("*");
|
|
185
|
+
for (const file of paths) {
|
|
186
|
+
const relative = file.slice(root.length + 1);
|
|
187
|
+
if (relative.startsWith(prefix!) && relative.endsWith(suffix)) imports[specifier.replaceAll("*", () => relative.slice(prefix!.length, relative.length - suffix.length))] = `/npm/${file}`;
|
|
188
|
+
}
|
|
189
|
+
} else imports[specifier] = `/npm/${root}/${path.replace(/^\.\//, "")}`;
|
|
190
|
+
}
|
|
191
|
+
// Without an exports field every file is importable (icon sets import "<pkg>/<icon>"); the compiler finishes extensionless targets against the listing.
|
|
192
|
+
if (manifest.exports === undefined) imports[`${name}/`] = `/npm/${root}/`;
|
|
193
|
+
return addPackageDependencies({ ...options, manifest, imports, prefix: `/npm/${root}/` });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function addConvertedPackage(options: AdditionalOptions & { manifest: PackageManifest }): Promise<Record<string, string>> {
|
|
197
|
+
const { manifest, profile, composed, visiting } = options;
|
|
198
|
+
const root = `${manifest.name}@${manifest.version}`;
|
|
199
|
+
const imports = { [manifest.name]: `/esm/${root}/${CONVERTED_ENTRY}` };
|
|
200
|
+
if (!profile.convert) throw new Error(`${root}: converter is not configured`);
|
|
201
|
+
if (!visiting.has(root) && !Object.hasOwn(options.listings, `esm/${root}`)) {
|
|
202
|
+
const result = await crawlConvertedPackage({ origin: profile.convert.origin, root, fetcher: options.fetcher });
|
|
203
|
+
Object.assign(composed.integrity, result.integrity);
|
|
204
|
+
options.listings[`esm/${root}`] = result.listing;
|
|
205
|
+
}
|
|
206
|
+
return addPackageDependencies({ ...options, imports, prefix: `/esm/${root}/` });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function addPackageDependencies(options: AdditionalOptions & { manifest: PackageManifest; imports: Record<string, string>; prefix: string }): Promise<Record<string, string>> {
|
|
210
|
+
const { manifest, versions, composed, visiting, imports } = options;
|
|
211
|
+
const root = `${manifest.name}@${manifest.version}`;
|
|
212
|
+
if (visiting.has(root)) return imports;
|
|
213
|
+
visiting.add(root);
|
|
214
|
+
const scope = composed.map.scopes[options.prefix] ??= {};
|
|
215
|
+
Object.assign(scope, imports);
|
|
216
|
+
for (const [dependency, dependencyRange] of Object.entries(manifest.dependencies ?? {})) {
|
|
217
|
+
if (BASE_PACKAGES.includes(packageName(dependency))) {
|
|
218
|
+
if (!composed.map.imports[dependency]) throw new Error(`${root}: unmapped base-set dependency ${dependency}`);
|
|
219
|
+
if (!satisfiesVersion(versions[dependency]!, dependencyRange)) throw new Error(`${root}: dependency ${dependency} ${dependencyRange} rejects base-set ${versions[dependency]}`);
|
|
220
|
+
} else Object.assign(scope, await addEsmPackage({ ...options, name: dependency, range: dependencyRange }));
|
|
221
|
+
}
|
|
222
|
+
if (!versions[manifest.name]) versions[manifest.name] = manifest.version;
|
|
223
|
+
return imports;
|
|
224
|
+
}
|
package/src/sw/router.ts
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import type { FrameConfig, HostMessage, PageLock, RuntimeError, RuntimePolicy, RuntimeProfile } from "../schema.ts";
|
|
2
|
+
import { validateHostMessage, validateSourcePath, validateLock } from "../host/validation.ts";
|
|
3
|
+
import { compilePage, moduleUrl, requestModuleUrl, rewriteImports } from "./compiler.ts";
|
|
4
|
+
import { fetchSource } from "./source-provider.ts";
|
|
5
|
+
import type { MdxPlugins } from "./compile.ts";
|
|
6
|
+
import { COMPILER_REVISION, DEV_SHIM, DEV_SHIM_URL } from "./compile.ts";
|
|
7
|
+
import { CONTENT_TYPES, extensionOf } from "./content-types.ts";
|
|
8
|
+
import { runtimeError, RuntimeFailure } from "./errors.ts";
|
|
9
|
+
import { keys, permitsNetwork, record, validateProfile } from "./profile.ts";
|
|
10
|
+
import { resolvePage } from "./resolver.ts";
|
|
11
|
+
import { stylesheetModule } from "./module-transform.ts";
|
|
12
|
+
import { digest, verifyIntegrity } from "./integrity.ts";
|
|
13
|
+
import { createLinkRoutes } from "./link-route.ts";
|
|
14
|
+
import { RUNTIME_MODULES, runtimeModuleSource } from "./runtime-module.ts";
|
|
15
|
+
import type { WorkerActivity } from "../activity-schema.ts";
|
|
16
|
+
import { activityResponse, applyLinkActivity, byteLength, createRequestActivity } from "./activity.ts";
|
|
17
|
+
import { convertedFile, converterUrl, rewriteConvertedImports } from "./converted.ts";
|
|
18
|
+
import { candidatesForPage, lazyRuntimeDb, putCandidates, tailwindCacheName } from "../storage/db.ts";
|
|
19
|
+
export { digest, verifyIntegrity } from "./integrity.ts";
|
|
20
|
+
|
|
21
|
+
export type RouterOptions = { origin: string; version: string; profile: RuntimeProfile; plugins: MdxPlugins; caches: CacheStorage; indexedDB?: IDBFactory; fetch?: typeof fetch; onActivity?: (event: { request: Request; record: WorkerActivity }) => void };
|
|
22
|
+
type StoredPage = { lock: PageLock; files: Record<string, string>; sourceProvider?: import("../schema.ts").SourceProvider; layout?: string; manifest: Extract<HostMessage, { type: "open" }>["manifest"]; policy?: RuntimePolicy };
|
|
23
|
+
const sourcePaths = (saved: StoredPage) => {
|
|
24
|
+
const prefix = saved.lock.page.slice(0, saved.lock.page.indexOf("/") + 1);
|
|
25
|
+
return [...new Set([...Object.keys(saved.files), ...(saved.sourceProvider?.paths ?? []).map(path => prefix + path)])];
|
|
26
|
+
};
|
|
27
|
+
const JS = { "content-type": "text/javascript; charset=utf-8" };
|
|
28
|
+
const serial = (value: unknown) => JSON.stringify(value).replaceAll("<", "\\u003c");
|
|
29
|
+
const frameMetadata = new WeakMap<FrameConfig, { map: string; config: string }>();
|
|
30
|
+
|
|
31
|
+
export function frameDocument(options: { config?: FrameConfig; preload?: Iterable<string>; error?: RuntimeError } = {}): { html: string; nonce: string } {
|
|
32
|
+
const { config } = options;
|
|
33
|
+
const error = options.error ? `<script type="application/json" id="page-runtime-error">${serial(options.error)}</script>` : "";
|
|
34
|
+
const nonce = crypto.randomUUID();
|
|
35
|
+
let metadata = config ? frameMetadata.get(config) : undefined;
|
|
36
|
+
if (config && !metadata) {
|
|
37
|
+
const map = { imports: Object.fromEntries(Object.entries(config.lock.map.imports).map(([k, v]) => [k, moduleUrl(v)])), scopes: Object.fromEntries(Object.entries(config.lock.map.scopes).map(([scope, table]) => [scope, Object.fromEntries(Object.entries(table).map(([k, v]) => [k, moduleUrl(v)]))])) };
|
|
38
|
+
metadata = { map: serial(map), config: serial(config) }; frameMetadata.set(config, metadata);
|
|
39
|
+
}
|
|
40
|
+
const preload = [...(options.preload ?? [])].map((url) => `<link rel="modulepreload" href="${url.replaceAll("&", "&").replaceAll('"', """)}">`).join("");
|
|
41
|
+
return { nonce, html: `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script src="/devtools-hook.js"></script>${metadata ? `<script type="importmap" nonce="${nonce}">${metadata.map}</script><script type="application/json" id="page-runtime-config">${metadata.config}</script>` : ""}${error}${preload}</head><body><div id="root"></div><script type="module" nonce="${nonce}" src="/boot.js"></script></body></html>` };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function contentSecurityPolicy(profile: RuntimeProfile, nonce: string): string {
|
|
45
|
+
const directives: Record<string, string[]> = { "script-src": ["'self'", `'nonce-${nonce}'`], "style-src": ["'self'", "'unsafe-inline'"], "img-src": ["'self'", "data:", "blob:"], "connect-src": ["'self'", profile.packageOrigin, profile.registry, ...profile.network.allow.map((v) => new URL(v).origin)], "frame-ancestors": profile.embedders };
|
|
46
|
+
if (profile.renderJobs) {
|
|
47
|
+
Object.assign(directives, { "default-src": ["'none'"], "base-uri": ["'self'"], "form-action": ["'none'"], "worker-src": ["'self'"] });
|
|
48
|
+
directives["connect-src"]!.push("blob:");
|
|
49
|
+
}
|
|
50
|
+
if (profile.convert) directives["connect-src"]!.push(profile.convert.origin);
|
|
51
|
+
if (profile.csp.wasm) directives["script-src"]!.push("'wasm-unsafe-eval'");
|
|
52
|
+
for (const [name, values] of Object.entries(profile.csp.add)) directives[name] = [...(directives[name] ?? []), ...values];
|
|
53
|
+
return Object.entries(directives).map(([name, values]) => `${name} ${values.join(" ")}`).join("; ");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createRouter(options: RouterOptions) {
|
|
57
|
+
const profile = validateProfile(options.profile); const fetcher = options.fetch ?? fetch;
|
|
58
|
+
const store = options.caches.open(`page-runtime-${options.version}-pages`);
|
|
59
|
+
const output = options.caches.open(`page-runtime-${options.version}-compiled`);
|
|
60
|
+
const transpiled = profile.renderJobs ? options.caches.open(`page-runtime-${options.version}-transpiled`) : undefined;
|
|
61
|
+
const packages = options.caches.open(`page-runtime-${options.version}-packages`);
|
|
62
|
+
const pages = new Map<string, Promise<StoredPage>>();
|
|
63
|
+
const modules = new WeakMap<PageLock, Map<string, Promise<{ response: Response; activity: WorkerActivity }>>>();
|
|
64
|
+
const moduleGraph = new WeakMap<PageLock, Set<string>>();
|
|
65
|
+
const frameConfigs = new WeakMap<PageLock, FrameConfig>();
|
|
66
|
+
// Export compiles the frame ran with library compiler plugins, by page and source path; held only for the export.
|
|
67
|
+
const exportModules = new Map<string, Map<string, string>>();
|
|
68
|
+
const rememberModule = (url: URL, lock: PageLock) => {
|
|
69
|
+
let graph = moduleGraph.get(lock);
|
|
70
|
+
if (!graph) { graph = new Set(); moduleGraph.set(lock, graph); }
|
|
71
|
+
graph.add(requestModuleUrl(url));
|
|
72
|
+
};
|
|
73
|
+
const tailwind = options.caches.open(tailwindCacheName(options.version));
|
|
74
|
+
const database = lazyRuntimeDb(options.indexedDB ? { factory: options.indexedDB } : {});
|
|
75
|
+
const linkRoute = createLinkRoutes({ ...options, load, database });
|
|
76
|
+
const key = (page: string) => `${options.origin}/__runtime/pages/${encodeURIComponent(page)}`;
|
|
77
|
+
const sourceOwnerKey = (namespace: string) => `${options.origin}/__runtime/render-owner/${namespace}`;
|
|
78
|
+
async function load(page: string): Promise<StoredPage> {
|
|
79
|
+
let pending = pages.get(page);
|
|
80
|
+
if (!pending) {
|
|
81
|
+
pending = (async () => {
|
|
82
|
+
const response = await (await store).match(key(page));
|
|
83
|
+
if (!response) throw new RuntimeFailure({ phase: "resolve", file: page, message: `page ${page} has not been opened by its host` });
|
|
84
|
+
const saved = await response.json() as StoredPage;
|
|
85
|
+
if (saved.lock.lock !== 2) {
|
|
86
|
+
if (!saved.policy) throw new RuntimeFailure({ phase: "resolve", file: page, message: `${page} was stored without its host policy, so it cannot be re-resolved without guessing one (the served profile policy is not the host's); reopen the page from its host, or clear the page runtime cache and try again` });
|
|
87
|
+
saved.lock = await resolvePage({ page, profile: { ...profile, policy: saved.policy }, manifest: saved.manifest, fetch: fetcher });
|
|
88
|
+
await (await store).put(key(page), Response.json(saved));
|
|
89
|
+
}
|
|
90
|
+
validateLock(saved.lock);
|
|
91
|
+
return saved;
|
|
92
|
+
})();
|
|
93
|
+
pages.set(page, pending);
|
|
94
|
+
void pending.catch(() => { if (pages.get(page) === pending) pages.delete(page); });
|
|
95
|
+
}
|
|
96
|
+
return pending;
|
|
97
|
+
}
|
|
98
|
+
async function message(value: unknown): Promise<FrameConfig> {
|
|
99
|
+
const m = validateHostMessage(value);
|
|
100
|
+
if (m.type !== "open") throw new Error("worker requires open message");
|
|
101
|
+
validateSourcePath(m.page);
|
|
102
|
+
const namespace = profile.renderJobs ? m.page.split('/')[0]! : undefined;
|
|
103
|
+
if (namespace && !/^[a-f0-9]{64}$/.test(namespace)) throw new Error("render source requires a content namespace");
|
|
104
|
+
const previous = await (await store).match(key(m.page));
|
|
105
|
+
const saved = previous ? await previous.json() as StoredPage : undefined;
|
|
106
|
+
const policy = m.policy ?? profile.policy;
|
|
107
|
+
const existing = m.lock ?? (saved?.lock.lock === 2 && serial(saved.manifest) === serial(m.manifest) && saved.policy && serial(saved.policy) === serial(policy) ? saved.lock : undefined);
|
|
108
|
+
const lock = await resolvePage({ page: m.page, profile: { ...profile, policy }, manifest: m.manifest, ...(existing ? { lock: existing } : {}), fetch: fetcher });
|
|
109
|
+
if (m.sourceProvider && new URL(m.sourceProvider.url).origin !== options.origin) throw new Error("source provider must use the runtime origin");
|
|
110
|
+
const savedPage: StoredPage = { lock, files: m.files, ...(m.sourceProvider ? { sourceProvider: m.sourceProvider } : {}), ...(m.layout ? { layout: m.layout } : {}), manifest: m.manifest, policy };
|
|
111
|
+
await (await store).put(key(m.page), Response.json(savedPage));
|
|
112
|
+
if (namespace) await (await store).put(sourceOwnerKey(namespace), new Response(m.page));
|
|
113
|
+
pages.set(m.page, Promise.resolve(savedPage));
|
|
114
|
+
return { page: m.page, entry: moduleUrl(`/src/${m.page}`), ...(m.layout ? { layout: moduleUrl(`/src/${m.layout}`) } : {}), lock, profile, runtimeVersion: options.version };
|
|
115
|
+
}
|
|
116
|
+
async function update(page: string, value: unknown): Promise<void> {
|
|
117
|
+
const m = validateHostMessage(value);
|
|
118
|
+
if (m.type !== "sources") throw new Error("worker requires sources message");
|
|
119
|
+
const saved = await load(page);
|
|
120
|
+
for (const [path, code] of Object.entries(m.files)) if (code === null) delete saved.files[path]; else saved.files[path] = code;
|
|
121
|
+
await (await store).put(key(page), Response.json(saved));
|
|
122
|
+
}
|
|
123
|
+
/** Registers the frame's export compile of a Markdown source, served as `/src/<path>?export` until the next one. */
|
|
124
|
+
async function exportModule(page: string, value: unknown): Promise<void> {
|
|
125
|
+
const m = record(value, "export-module");
|
|
126
|
+
keys(m, ["type", "path", "code"], "export-module");
|
|
127
|
+
if (typeof m.path !== "string" || typeof m.code !== "string") throw new Error("export-module: expected path and code strings");
|
|
128
|
+
validateSourcePath(m.path);
|
|
129
|
+
if (!/\.mdx?$/.test(m.path)) throw new Error(`export-module: ${m.path} is not a Markdown source`);
|
|
130
|
+
const saved = await load(page);
|
|
131
|
+
if (saved.files[m.path] === undefined) throw new RuntimeFailure({ phase: "fetch", file: m.path, message: `source ${m.path} does not exist` });
|
|
132
|
+
exportModules.set(page, new Map([[m.path, m.code]]));
|
|
133
|
+
}
|
|
134
|
+
async function exported(url: URL, saved: StoredPage, activity: WorkerActivity): Promise<Response> {
|
|
135
|
+
const path = decodeURIComponent(url.pathname.slice("/src/".length));
|
|
136
|
+
const code = exportModules.get(saved.lock.page)?.get(path);
|
|
137
|
+
if (code === undefined) throw new RuntimeFailure({ phase: "fetch", file: path, message: `no export compile is registered for ${path}; export the page again` });
|
|
138
|
+
activity.source = "compiled"; activity.generated = "export module"; activity.decodedBytes = byteLength(code);
|
|
139
|
+
const linked = await rewriteImports({ code, path: `${url.pathname}${url.search}`, lock: saved.lock, sources: sourcePaths(saved), activity });
|
|
140
|
+
activity.outputBytes = byteLength(linked);
|
|
141
|
+
return new Response(linked, { headers: JS });
|
|
142
|
+
}
|
|
143
|
+
async function compiled(url: URL, saved: StoredPage, activity: WorkerActivity): Promise<Response> {
|
|
144
|
+
const path = decodeURIComponent(url.pathname.slice("/src/".length)); validateSourcePath(path);
|
|
145
|
+
let code = saved.files[path];
|
|
146
|
+
if (code === undefined && saved.sourceProvider) {
|
|
147
|
+
const prefix = saved.lock.page.slice(0, saved.lock.page.indexOf("/") + 1);
|
|
148
|
+
const response = await fetchSource({ provider: saved.sourceProvider, path: path.startsWith(prefix) ? path.slice(prefix.length) : path, fetch: fetcher });
|
|
149
|
+
if (!url.searchParams.has("module") && !url.searchParams.has("raw") && !url.searchParams.has("url") && !/\.(tsx?|jsx?|mdx?|mjs|css|json)$/.test(path)) return response;
|
|
150
|
+
code = await response.text();
|
|
151
|
+
}
|
|
152
|
+
if (code === undefined) throw new RuntimeFailure({ phase: "fetch", file: path, message: `source ${path} does not exist` });
|
|
153
|
+
activity.decodedBytes = byteLength(code); activity.source = "compiled";
|
|
154
|
+
const asModule = url.searchParams.has("module") || /\.(tsx?|jsx?|mdx?|mjs)$/.test(path) || url.searchParams.has("raw") || url.searchParams.has("url");
|
|
155
|
+
if (!asModule) { activity.outputBytes = activity.decodedBytes; return new Response(code, { headers: { "content-type": CONTENT_TYPES[extensionOf(path)] ?? "application/octet-stream" } }); }
|
|
156
|
+
const paths = sourcePaths(saved);
|
|
157
|
+
const hash = await digest(new TextEncoder().encode(serial({ compiler: COMPILER_REVISION, code, lock: saved.lock, query: [...url.searchParams], paths })));
|
|
158
|
+
const cacheKey = `${options.origin}/__runtime/compiled/${encodeURIComponent(hash)}`;
|
|
159
|
+
const jobModule = !!transpiled && url.searchParams.has("revision");
|
|
160
|
+
const hit = jobModule ? undefined : await (await output).match(cacheKey);
|
|
161
|
+
if (hit) { activity.source = "cache"; activity.cache = "storage"; activity.outputBytes = hit.headers.has("content-length") ? Number(hit.headers.get("content-length")) : (await hit.clone().arrayBuffer()).byteLength; return hit; }
|
|
162
|
+
let result;
|
|
163
|
+
const transpile = jobModule ? async (compile: () => Promise<string>) => {
|
|
164
|
+
const sourceKey = await digest(new TextEncoder().encode(serial({ compiler: COMPILER_REVISION, path, code })));
|
|
165
|
+
const url = `${options.origin}/__runtime/transpiled/${encodeURIComponent(sourceKey)}`;
|
|
166
|
+
const cache = await transpiled!;
|
|
167
|
+
const cached = await cache.match(url);
|
|
168
|
+
if (cached) return cached.text();
|
|
169
|
+
const source = await compile();
|
|
170
|
+
await cache.put(url, new Response(source));
|
|
171
|
+
return source;
|
|
172
|
+
} : undefined;
|
|
173
|
+
try { result = await compilePage({ path: `${url.pathname}${url.search}`, code, lock: saved.lock, sources: paths, plugins: options.plugins, activity, ...(transpile ? { transpile } : {}) }); }
|
|
174
|
+
catch (error) { throw error instanceof RuntimeFailure ? error : new RuntimeFailure(runtimeError({ error, phase: "compile", file: path })); }
|
|
175
|
+
activity.outputBytes = byteLength(result.code);
|
|
176
|
+
if (/\.(css|json)$/.test(path) || url.searchParams.has("raw") || url.searchParams.has("url")) { activity.source = "generated"; activity.generated = extensionOf(path) + " module"; }
|
|
177
|
+
const response = new Response(result.code, { headers: { ...JS, "content-length": String(activity.outputBytes), "x-page-candidates": encodeURIComponent(JSON.stringify(result.candidates)) } });
|
|
178
|
+
if (!jobModule) await (await output).put(cacheKey, response.clone());
|
|
179
|
+
await putCandidates(await database(), { page: saved.lock.page, module: url.pathname, sourceHash: hash, candidates: result.candidates });
|
|
180
|
+
return response;
|
|
181
|
+
}
|
|
182
|
+
async function packageFile(options_: { url: URL; saved: StoredPage; request: Request; activity: WorkerActivity }): Promise<Response> {
|
|
183
|
+
const { url, saved, request, activity } = options_;
|
|
184
|
+
const converted = url.pathname.startsWith("/esm/");
|
|
185
|
+
const path = decodeURIComponent(converted ? url.pathname.slice(1) : url.pathname.slice("/npm/".length));
|
|
186
|
+
const conversion = converted ? convertedFile(path) : undefined;
|
|
187
|
+
if (conversion && !profile.convert) throw new RuntimeFailure({ phase: "fetch", file: path, message: `${conversion.root}: converter is not configured` });
|
|
188
|
+
const expected = saved.lock.integrity[path];
|
|
189
|
+
if (!expected) throw new RuntimeFailure({ phase: "fetch", file: path, message: `${path} is not part of the page's library set` });
|
|
190
|
+
const upstream = conversion ? converterUrl({ ...conversion, origin: profile.convert!.origin }) : `${saved.lock.packageOrigin.replace(/\/$/, "")}/${path}`;
|
|
191
|
+
const cacheKey = `${options.origin}/__runtime/package/${encodeURIComponent(expected)}/${conversion ? `${encodeURIComponent(profile.convert!.origin)}/` : ""}${path}`;
|
|
192
|
+
let original = await (await packages).match(cacheKey);
|
|
193
|
+
activity.cache = original ? "storage" : "miss"; activity.source = original ? "cache" : "network";
|
|
194
|
+
activity.origin = upstream;
|
|
195
|
+
let bytes: Uint8Array<ArrayBuffer>;
|
|
196
|
+
if (!original) {
|
|
197
|
+
const fetching = performance.now();
|
|
198
|
+
try {
|
|
199
|
+
original = await fetcher(activity.origin, { mode: "cors", credentials: "omit", redirect: "error" });
|
|
200
|
+
activity.transferredBytes = original.headers.has("content-length") ? Number(original.headers.get("content-length")) : null;
|
|
201
|
+
if (!original.ok) throw new RuntimeFailure({ phase: "fetch", file: path, message: `${conversion ? "converter" : "package origin"} returned HTTP ${original.status} for ${path}` });
|
|
202
|
+
bytes = new Uint8Array(await original.clone().arrayBuffer()); activity.decodedBytes = bytes.byteLength;
|
|
203
|
+
} finally { activity.fetchMs = performance.now() - fetching; }
|
|
204
|
+
const checking = performance.now();
|
|
205
|
+
try { await verifyIntegrity(bytes, expected, path); }
|
|
206
|
+
catch (error) {
|
|
207
|
+
if (!conversion || !(error instanceof RuntimeFailure)) throw error;
|
|
208
|
+
throw new RuntimeFailure({ phase: "fetch", file: path, message: `${conversion.root}: integrity mismatch for ${path}; re-resolve the page's lock, or pin the converter to a fixed self-hosted esm.sh image` });
|
|
209
|
+
} finally { activity.integrityMs = performance.now() - checking; }
|
|
210
|
+
await (await packages).put(cacheKey, original.clone());
|
|
211
|
+
} else bytes = new Uint8Array(await original.arrayBuffer());
|
|
212
|
+
activity.decodedBytes = bytes.byteLength;
|
|
213
|
+
const ext = extensionOf(path); const text = new TextDecoder().decode(bytes);
|
|
214
|
+
const respond = (code: string, generated?: string) => {
|
|
215
|
+
activity.outputBytes = byteLength(code); if (generated) activity.generated = generated;
|
|
216
|
+
const headers = new Headers(original.headers); headers.delete("content-encoding"); headers.set("content-type", JS["content-type"]); headers.set("content-length", String(activity.outputBytes)); headers.set("x-page-integrity", expected);
|
|
217
|
+
return new Response(code, { headers });
|
|
218
|
+
};
|
|
219
|
+
if (url.searchParams.has("raw")) return respond(`export default ${JSON.stringify(text)};`, "raw module");
|
|
220
|
+
if (url.searchParams.has("url")) return respond(`export default ${JSON.stringify(moduleUrl(url.pathname))};`, "URL module");
|
|
221
|
+
if ([".js", ".mjs"].includes(ext)) {
|
|
222
|
+
const code = conversion ? await rewriteConvertedImports({ code: text, ...conversion }) : text;
|
|
223
|
+
return respond(await rewriteImports({ code, path: url.pathname, lock: saved.lock, sources: sourcePaths(saved), activity }));
|
|
224
|
+
}
|
|
225
|
+
if (url.searchParams.has("module") || request.destination === "script") {
|
|
226
|
+
if (ext === ".json") return respond(`export default ${JSON.stringify(JSON.parse(text))};`, "JSON module");
|
|
227
|
+
if (ext === ".css") return respond(stylesheetModule(text, moduleUrl(url.pathname)), "stylesheet module");
|
|
228
|
+
throw new Error(`${path}: cannot serve ${ext} as module`);
|
|
229
|
+
}
|
|
230
|
+
activity.outputBytes = bytes.byteLength;
|
|
231
|
+
const headers = new Headers(original.headers); headers.delete("content-encoding"); headers.set("content-length", String(bytes.byteLength)); headers.set("content-type", CONTENT_TYPES[ext] ?? "application/octet-stream"); headers.set("x-page-integrity", expected);
|
|
232
|
+
return new Response(bytes, { headers });
|
|
233
|
+
}
|
|
234
|
+
async function serve(request: Request, activity: WorkerActivity, onError?: (error: ReturnType<typeof runtimeError>) => void): Promise<Response> {
|
|
235
|
+
const url = new URL(request.url);
|
|
236
|
+
let page = url.searchParams.get("page") ?? (url.pathname.startsWith("/frame/") ? decodeURIComponent(url.pathname.slice(7)) : null);
|
|
237
|
+
try {
|
|
238
|
+
if (profile.renderJobs && url.pathname.startsWith("/src/")) {
|
|
239
|
+
const namespace = url.pathname.split('/')[2]!;
|
|
240
|
+
const owner = /^[a-f0-9]{64}$/.test(namespace) ? await (await store).match(sourceOwnerKey(namespace)) : undefined;
|
|
241
|
+
if (!owner) throw new Error(`${url.pathname}: render source is not registered`);
|
|
242
|
+
page = await owner.text();
|
|
243
|
+
}
|
|
244
|
+
if (activity.kind === "npm" && !activity.package) throw new Error(`invalid npm request: ${url.pathname}`);
|
|
245
|
+
if (url.origin !== options.origin) {
|
|
246
|
+
if (!permitsNetwork(profile, url.href)) { activity.error = { phase: "fetch", message: `egress denied: ${url.href}` }; activity.outputBytes = byteLength(activity.error.message); return new Response(activity.error.message, { status: 403 }); }
|
|
247
|
+
return await networkResponse(request, activity);
|
|
248
|
+
}
|
|
249
|
+
const linked = await linkRoute(request);
|
|
250
|
+
if (linked) {
|
|
251
|
+
activity.source = activity.kind === "frame" ? "generated" : linked.headers.get("x-link-compiled") === "0" ? "cache" : activity.kind === "npm" ? "network" : "compiled";
|
|
252
|
+
activity.cache = activity.source === "cache" ? "memory" : "miss";
|
|
253
|
+
activity.outputBytes = linked.headers.has("content-length") ? Number(linked.headers.get("content-length")) : (await linked.clone().arrayBuffer()).byteLength;
|
|
254
|
+
if (activity.kind === "frame") { activity.generated = "frame + import map"; activity.decodedBytes = activity.outputBytes; }
|
|
255
|
+
else if (!applyLinkActivity({ response: linked, record: activity })) {
|
|
256
|
+
activity.unavailable = ["fetch", "integrity", "compile", "rewrite", "cache-layer"];
|
|
257
|
+
if (activity.kind === "npm" && page) activity.origin = `${(await load(page)).lock.packageOrigin.replace(/\/$/, "")}/${decodeURIComponent(url.pathname.slice(5))}`;
|
|
258
|
+
activity.transferredBytes = null;
|
|
259
|
+
}
|
|
260
|
+
return linked;
|
|
261
|
+
}
|
|
262
|
+
if (url.pathname.startsWith("/frame/")) {
|
|
263
|
+
const exists = await (await store).match(key(page!));
|
|
264
|
+
const saved = exists ? await load(page!) : undefined;
|
|
265
|
+
let config = saved ? frameConfigs.get(saved.lock) : undefined;
|
|
266
|
+
if (saved && !config) { config = { page: page!, entry: moduleUrl(`/src/${page}`), ...(saved.layout ? { layout: moduleUrl(`/src/${saved.layout}`) } : {}), lock: saved.lock, profile: { ...profile, packageOrigin: saved.lock.packageOrigin }, runtimeVersion: options.version }; frameConfigs.set(saved.lock, config); }
|
|
267
|
+
const document = frameDocument({ ...(config ? { config } : {}), ...(saved ? { preload: moduleGraph.get(saved.lock) ?? [] } : {}) });
|
|
268
|
+
activity.generated = "frame + import map"; activity.outputBytes = byteLength(document.html); activity.decodedBytes = activity.outputBytes;
|
|
269
|
+
return new Response(document.html, { headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": contentSecurityPolicy(config?.profile ?? profile, document.nonce) } });
|
|
270
|
+
}
|
|
271
|
+
if (["/boot.js", "/devtools-hook.js", "/page-agent.js", "/profile.json"].includes(url.pathname)) {
|
|
272
|
+
return await networkResponse(request, activity);
|
|
273
|
+
}
|
|
274
|
+
if (/^\/__runtime\/tailwind\/[a-f0-9]{64}\.css$/.test(url.pathname)) {
|
|
275
|
+
const hit = await (await tailwind).match(`${options.origin}${url.pathname}`);
|
|
276
|
+
if (!hit) {
|
|
277
|
+
const message = `no generated stylesheet is cached for ${url.pathname}`;
|
|
278
|
+
activity.error = { phase: "fetch", message }; activity.outputBytes = byteLength(message);
|
|
279
|
+
return new Response(message, { status: 404, headers: { "x-page-runtime-error": "fetch" } });
|
|
280
|
+
}
|
|
281
|
+
activity.source = "cache"; activity.cache = "storage"; activity.generated = "Tailwind stylesheet";
|
|
282
|
+
activity.outputBytes = hit.headers.has("content-length") ? Number(hit.headers.get("content-length")) : (await hit.clone().arrayBuffer()).byteLength; activity.decodedBytes = activity.outputBytes;
|
|
283
|
+
return hit;
|
|
284
|
+
}
|
|
285
|
+
if (!page) throw new Error(`${url.pathname}: missing page context`);
|
|
286
|
+
const saved = await load(page);
|
|
287
|
+
if (Object.hasOwn(RUNTIME_MODULES, url.pathname) || url.pathname === DEV_SHIM_URL) {
|
|
288
|
+
const started = performance.now();
|
|
289
|
+
const file = RUNTIME_MODULES[url.pathname];
|
|
290
|
+
const original = file ? await runtimeModuleSource({ origin: options.origin, fetch: fetcher, file }) : DEV_SHIM;
|
|
291
|
+
if (file) { activity.fetchMs = performance.now() - started; activity.origin = `${options.origin}/${file}`; activity.source = "network"; activity.transferredBytes = null; }
|
|
292
|
+
else activity.generated = "JSX development shim";
|
|
293
|
+
const code = await rewriteImports({ code: original, path: url.pathname, lock: saved.lock, sources: [], activity });
|
|
294
|
+
activity.decodedBytes = byteLength(original); activity.outputBytes = byteLength(code);
|
|
295
|
+
return new Response(code, { headers: JS });
|
|
296
|
+
}
|
|
297
|
+
if (url.pathname === "/__runtime/candidates") {
|
|
298
|
+
const candidates = await candidatesForPage(await database(), page);
|
|
299
|
+
const body = JSON.stringify([...new Set(candidates.flatMap((record) => record.candidates))]); activity.outputBytes = byteLength(body); activity.decodedBytes = activity.outputBytes; activity.generated = "source candidates";
|
|
300
|
+
return new Response(body, { headers: { "content-type": "application/json" } });
|
|
301
|
+
}
|
|
302
|
+
if (url.pathname.startsWith("/src/") && url.searchParams.has("export")) return await exported(url, saved, activity);
|
|
303
|
+
if (url.pathname.startsWith("/src/")) {
|
|
304
|
+
const response = await compiled(url, saved, activity);
|
|
305
|
+
if (response.headers.get("content-type")?.startsWith("text/javascript")) rememberModule(url, saved.lock);
|
|
306
|
+
return response;
|
|
307
|
+
}
|
|
308
|
+
if (url.pathname.startsWith("/npm/") || url.pathname.startsWith("/esm/")) {
|
|
309
|
+
let table = modules.get(saved.lock);
|
|
310
|
+
if (!table) { table = new Map(); modules.set(saved.lock, table); }
|
|
311
|
+
const id = `${url.href}:${request.destination}`;
|
|
312
|
+
let pending = table.get(id);
|
|
313
|
+
const hit = Boolean(pending);
|
|
314
|
+
if (!pending) { pending = packageFile({ url, saved, request, activity }).then((response) => ({ response, activity })); table.set(id, pending); void pending.catch(() => table.delete(id)); }
|
|
315
|
+
const cached = await pending;
|
|
316
|
+
if (hit) { activity.source = "cache"; activity.cache = "memory"; activity.origin = cached.activity.origin; activity.generated = cached.activity.generated; activity.decodedBytes = cached.activity.decodedBytes; activity.outputBytes = cached.activity.outputBytes; }
|
|
317
|
+
const response = cached.response.clone();
|
|
318
|
+
if (response.headers.get("content-type")?.startsWith("text/javascript")) rememberModule(url, saved.lock);
|
|
319
|
+
return response;
|
|
320
|
+
}
|
|
321
|
+
activity.outputBytes = byteLength("unknown runtime route");
|
|
322
|
+
activity.error = { phase: "fetch", message: `unknown runtime route: ${url.pathname}` };
|
|
323
|
+
return new Response("unknown runtime route", { status: 404 });
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (error instanceof RuntimeFailure && error.activity) Object.assign(activity, error.activity);
|
|
326
|
+
const detail = runtimeError({ error, phase: "fetch", file: url.pathname });
|
|
327
|
+
activity.error = { phase: detail.phase, message: detail.message.slice(0, 4096) };
|
|
328
|
+
onError?.(detail);
|
|
329
|
+
if (request.mode === "navigate") {
|
|
330
|
+
const document = frameDocument({ error: detail });
|
|
331
|
+
activity.outputBytes = byteLength(document.html);
|
|
332
|
+
return new Response(document.html, { status: 500, headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": contentSecurityPolicy(profile, document.nonce), "x-page-runtime-error": detail.phase } });
|
|
333
|
+
}
|
|
334
|
+
const body = `throw Object.assign(new Error(${serial(detail.message)}), { pageRuntime: ${serial(detail)} });`;
|
|
335
|
+
activity.outputBytes = byteLength(body);
|
|
336
|
+
return new Response(body, { status: 200, headers: { ...JS, "x-page-runtime-error": detail.phase } });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
async function networkResponse(request: Request, activity: WorkerActivity): Promise<Response> {
|
|
340
|
+
const started = performance.now(); activity.source = "network"; activity.origin = request.url;
|
|
341
|
+
try {
|
|
342
|
+
const response = await fetcher(request);
|
|
343
|
+
activity.transferredBytes = response.headers.has("content-length") ? Number(response.headers.get("content-length")) : null;
|
|
344
|
+
if (response.type === "opaque" || response.type === "opaqueredirect") return response;
|
|
345
|
+
if (!response.ok) activity.error = { phase: "fetch", message: `HTTP ${response.status}: ${request.url}` };
|
|
346
|
+
const body = await response.arrayBuffer(); activity.decodedBytes = body.byteLength; activity.outputBytes = body.byteLength;
|
|
347
|
+
const headers = new Headers(response.headers); headers.delete("content-encoding"); headers.set("content-length", String(body.byteLength));
|
|
348
|
+
return new Response([204, 205, 304].includes(response.status) || request.method === "HEAD" ? null : body, { status: response.status, statusText: response.statusText, headers });
|
|
349
|
+
} finally { activity.fetchMs = performance.now() - started; }
|
|
350
|
+
}
|
|
351
|
+
async function route(request: Request, callbacks: { onError?: (error: ReturnType<typeof runtimeError>) => void } = {}): Promise<Response> {
|
|
352
|
+
const start = performance.now(); const activity = createRequestActivity(request.url);
|
|
353
|
+
const response = activityResponse({ response: await serve(request, activity, callbacks.onError), record: activity, start });
|
|
354
|
+
options.onActivity?.({ request, record: activity });
|
|
355
|
+
return response;
|
|
356
|
+
}
|
|
357
|
+
return { route, message, update, exportModule };
|
|
358
|
+
}
|
|
359
|
+
export type RuntimeRouter = ReturnType<typeof createRouter>;
|
|
360
|
+
export type OpenPageMessage = Extract<HostMessage, { type: "open" }>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { RuntimeExports } from "../schema.ts";
|
|
2
|
+
import { packageName, type composeFragments } from "./composition.ts";
|
|
3
|
+
import { record, validateDependencies } from "./profile.ts";
|
|
4
|
+
|
|
5
|
+
function packagePath(path: string): boolean {
|
|
6
|
+
return /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+@[a-z0-9.+_-]+\//i.test(path)
|
|
7
|
+
&& !/[\\?#%\s]/.test(path) && !path.split("/").some(part => part === "." || part === "..");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function applyRuntimeExports(value: unknown, composed: ReturnType<typeof composeFragments>, versions: Record<string, string>): RuntimeExports["versions"] {
|
|
11
|
+
const catalog = record(value, "runtime exports");
|
|
12
|
+
const exported = validateDependencies(catalog.versions, "runtime exports versions");
|
|
13
|
+
for (const [path, integrity] of Object.entries(record(catalog.integrity, "runtime exports integrity"))) {
|
|
14
|
+
if (!packagePath(path) || typeof integrity !== "string" || !/^sha384-[A-Za-z\d+/]{64}$/.test(integrity)) throw new Error(`Invalid runtime export integrity for ${path}`);
|
|
15
|
+
if (composed.integrity[path] && composed.integrity[path] !== integrity) throw new Error(`Conflicting runtime export integrity for ${path}`);
|
|
16
|
+
composed.integrity[path] = integrity;
|
|
17
|
+
}
|
|
18
|
+
const url = (target: unknown) => {
|
|
19
|
+
if (typeof target !== "string" || !Object.hasOwn(composed.integrity, target)) throw new Error(`Runtime export target ${String(target)} has no integrity`);
|
|
20
|
+
return `/npm/${target}`;
|
|
21
|
+
};
|
|
22
|
+
for (const [name, target] of Object.entries(record(catalog.imports, "runtime exports imports"))) {
|
|
23
|
+
if (!Object.hasOwn(exported, packageName(name))) throw new Error(`Runtime export ${name} has no version`);
|
|
24
|
+
composed.map.imports[name] ??= url(target);
|
|
25
|
+
}
|
|
26
|
+
for (const [scope, value] of Object.entries(record(catalog.scopes, "runtime exports scopes"))) {
|
|
27
|
+
if (!packagePath(scope) || !scope.endsWith("/")) throw new Error(`Invalid runtime export scope ${scope}`);
|
|
28
|
+
const table = composed.map.scopes[`/npm/${scope}`] ??= {};
|
|
29
|
+
for (const [name, target] of Object.entries(record(value, scope))) table[name] ??= url(target);
|
|
30
|
+
}
|
|
31
|
+
for (const [path, target] of Object.entries(record(catalog.remaps, "runtime exports remaps"))) {
|
|
32
|
+
if (!packagePath(path) || typeof target !== "string") throw new Error(`Invalid runtime export remap ${path}`);
|
|
33
|
+
if (Object.hasOwn(composed.remaps, path)) continue;
|
|
34
|
+
composed.map.imports[`/npm/${path}`] = url(target);
|
|
35
|
+
composed.remaps[path] = target;
|
|
36
|
+
}
|
|
37
|
+
for (const [name, version] of Object.entries(exported)) versions[name] ??= version;
|
|
38
|
+
return exported;
|
|
39
|
+
}
|