@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,54 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import type { Fragment, RuntimeProfile } from "../../schema.ts";
|
|
3
|
+
import type { PackageManifest } from "../resolver.ts";
|
|
4
|
+
|
|
5
|
+
export const CONVERTER = "https://converter.example";
|
|
6
|
+
export const UI = "@flanksource/clicky-ui";
|
|
7
|
+
export const FACET = "@flanksource/facet";
|
|
8
|
+
export const PROFILE: RuntimeProfile = { runtimeDomain: "runtime.example", embedders: ["https://host.example"], packageOrigin: "https://packages.example", registry: "https://registry.example", managed: { [UI]: "^0.3", [FACET]: "^0.1" }, policy: { dependencies: "strict", allow: ["react-copy-to-clipboard"] }, convert: { origin: CONVERTER }, minReleaseAgeDays: 3, network: { allow: [] }, csp: { add: {} }, links: "deny", sources: ["host"], readinessTimeoutMs: 15000 };
|
|
9
|
+
export const MANIFESTS: Record<string, PackageManifest> = {
|
|
10
|
+
[UI]: { name: UI, version: "0.3.0", sideEffects: false },
|
|
11
|
+
[FACET]: { name: FACET, version: "0.1.0", sideEffects: false, peerDependencies: { [UI]: "^0.3" } },
|
|
12
|
+
"react-copy-to-clipboard": { name: "react-copy-to-clipboard", version: "5.1.1", main: "lib/index.js", dependencies: { "copy-to-clipboard": "^3.3.1" }, peerDependencies: { react: "^15.3.0 || 16 || 17 || 18 || 19" } },
|
|
13
|
+
"copy-to-clipboard": { name: "copy-to-clipboard", version: "3.3.3", main: "index.js", dependencies: { "toggle-selection": "^1.0.6" } },
|
|
14
|
+
"toggle-selection": { name: "toggle-selection", version: "1.0.6", main: "index.js" },
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export async function recordedModules(): Promise<Map<string, string>> {
|
|
18
|
+
const modules = new Map<string, string>();
|
|
19
|
+
for (const name of ["react-copy-to-clipboard", "copy-to-clipboard", "toggle-selection"]) {
|
|
20
|
+
const root = `${name}@${MANIFESTS[name]!.version}`;
|
|
21
|
+
modules.set(`/*${root}?dev&target=es2022`, await readFile(new URL(`./fixtures/${name}-entry.mjs.txt`, import.meta.url), "utf8"));
|
|
22
|
+
modules.set(`/*${root}/es2022/${name}.development.mjs`, await readFile(new URL(`./fixtures/${name}-module.mjs.txt`, import.meta.url), "utf8"));
|
|
23
|
+
}
|
|
24
|
+
return modules;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function registryResponse(name: string, manifests = MANIFESTS): Response {
|
|
28
|
+
const manifest = manifests[name];
|
|
29
|
+
if (!manifest) throw new Error(`fixture has no manifest for ${name}`);
|
|
30
|
+
return Response.json({ time: { [manifest.version]: "2026-01-01T00:00:00Z" }, versions: { [manifest.version]: manifest } });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function fragment(name: string): Fragment {
|
|
34
|
+
const root = `${name}@${MANIFESTS[name]!.version}`;
|
|
35
|
+
return { fragment: 1, name, imports: { [name]: `${root}/index.js`, ...(name === UI ? { react: "react@18.3.1/index.js" } : {}) }, scopes: { [`${root}/`]: {} }, remaps: {}, aliases: {}, inherits: [], integrity: { [`${root}/index.js`]: "sha384-fixture", ...(name === UI ? { "react@18.3.1/index.js": "sha384-react" } : {}) } };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function conversionFixture(options: { manifests?: Record<string, PackageManifest> } = {}) {
|
|
39
|
+
const modules = await recordedModules();
|
|
40
|
+
const calls: string[] = [];
|
|
41
|
+
const fetcher: typeof fetch = async (input) => {
|
|
42
|
+
const url = String(input); calls.push(url);
|
|
43
|
+
if (url.startsWith(`${PROFILE.registry}/`)) return registryResponse(decodeURIComponent(url.slice(PROFILE.registry.length + 1)), options.manifests);
|
|
44
|
+
if (url.endsWith("barrels.json")) return Response.json({ modules: [], barrels: {} });
|
|
45
|
+
if (url.endsWith("importmap.json")) return Response.json(fragment(url.includes(UI) ? UI : FACET));
|
|
46
|
+
if (url.startsWith(CONVERTER)) {
|
|
47
|
+
const source = modules.get(url.slice(CONVERTER.length));
|
|
48
|
+
if (source === undefined) throw new Error(`unrecorded converter URL ${url}`);
|
|
49
|
+
return new Response(source);
|
|
50
|
+
}
|
|
51
|
+
throw new Error(`unexpected fixture URL ${url}`);
|
|
52
|
+
};
|
|
53
|
+
return { modules, calls, fetcher };
|
|
54
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function redact() { return () => undefined; }
|
package/src/sw/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { createRouter, frameDocument, verifyIntegrity, type RouterOptions, type RuntimeRouter } from "./router.ts";
|
|
2
|
+
export { resolvePage, checkPeers, esmEntries, allowsDependency, DependencyPolicyError, type ResolveOptions } from "./resolver.ts";
|
|
3
|
+
export { validateVersionRange } from "./versions.ts";
|
|
4
|
+
export { chooseVersion, satisfiesVersion } from "./versions.ts";
|
|
5
|
+
export { composeFragments, resolveSpecifier } from "./composition.ts";
|
|
6
|
+
export { validateProfile, validateDependencies, validatePolicy, permitsNetwork } from "./profile.ts";
|
|
7
|
+
export { compilePage, rewriteImports, BASE_PLUGINS, moduleUrl } from "./compiler.ts";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { RuntimeFailure } from "./errors.ts";
|
|
2
|
+
|
|
3
|
+
export async function digest(bytes: Uint8Array<ArrayBuffer>, algorithm = "SHA-384"): Promise<string> {
|
|
4
|
+
return `${algorithm.toLowerCase().replace("-", "")}-${btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest(algorithm, bytes))))}`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function verifyIntegrity(bytes: Uint8Array<ArrayBuffer>, expected: string, path: string): Promise<void> {
|
|
8
|
+
const algorithm = /^(sha256|sha384|sha512)-/.exec(expected)?.[1];
|
|
9
|
+
if (!algorithm || await digest(bytes, algorithm.toUpperCase().replace("SHA", "SHA-")) !== expected) throw new RuntimeFailure({ phase: "fetch", file: path, message: `integrity mismatch for ${path}` });
|
|
10
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { tailwindCacheName } from "../storage/db.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Removes what earlier runtimes kept in Cache Storage: the v2 Tailwind cache, other versions' Tailwind caches (their
|
|
5
|
+
* IndexedDB records are cleared when the current library key first writes), and per-module candidate entries, which
|
|
6
|
+
* now live in IndexedDB.
|
|
7
|
+
*/
|
|
8
|
+
export async function cleanupLegacyStorage(options: { caches: CacheStorage; origin: string; version: string }): Promise<void> {
|
|
9
|
+
const current = tailwindCacheName(options.version);
|
|
10
|
+
const names = await options.caches.keys();
|
|
11
|
+
await Promise.all(names.map(async (name) => {
|
|
12
|
+
if (name === "page-runtime-tailwind-v2" || (/^page-runtime-.+-tailwind$/.test(name) && name !== current)) { await options.caches.delete(name); return; }
|
|
13
|
+
if (!/^page-runtime-.+-compiled$/.test(name)) return;
|
|
14
|
+
const cache = await options.caches.open(name);
|
|
15
|
+
const legacy = `${options.origin}/__runtime/candidates/`;
|
|
16
|
+
await Promise.all((await cache.keys()).filter((request) => request.url.startsWith(legacy)).map((request) => cache.delete(request)));
|
|
17
|
+
}));
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { WorkerActivity } from "../activity-schema.ts";
|
|
2
|
+
|
|
3
|
+
export type LinkActivity = Pick<WorkerActivity, "source" | "cache" | "origin" | "generated" | "transferredBytes" | "decodedBytes" | "outputBytes" | "fetchMs" | "integrityMs" | "compileMs" | "rewriteMs" | "unavailable">;
|
|
4
|
+
|
|
5
|
+
export function createLinkActivity(): LinkActivity {
|
|
6
|
+
return { source: "compiled", cache: "miss", origin: null, generated: null, transferredBytes: 0, decodedBytes: null, outputBytes: null, fetchMs: 0, integrityMs: 0, compileMs: 0, rewriteMs: 0, unavailable: [] };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function linkActivityResponse(options: { response: Response; metrics: LinkActivity }): Response {
|
|
10
|
+
options.response.headers.set("x-link-activity", encodeURIComponent(JSON.stringify(options.metrics)));
|
|
11
|
+
if (options.metrics.outputBytes !== null) options.response.headers.set("content-length", String(options.metrics.outputBytes));
|
|
12
|
+
return options.response;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function cachedLinkActivity(options: { response: Response; layer: "memory" | "storage"; metrics: LinkActivity }): void {
|
|
16
|
+
const size = options.response.headers.get("x-link-source-bytes");
|
|
17
|
+
const output = options.response.headers.get("content-length");
|
|
18
|
+
if (size === null || output === null) throw new Error("Linked cache entry is missing its source/output size");
|
|
19
|
+
Object.assign(options.metrics, { source: "cache", cache: options.layer, decodedBytes: Number(size), outputBytes: Number(output) });
|
|
20
|
+
}
|
|
21
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function createLinkCache(persistent: Promise<Cache>) {
|
|
2
|
+
const memory = new Map<string, { bytes: ArrayBuffer; headers: Array<[string, string]> }>();
|
|
3
|
+
return {
|
|
4
|
+
async match(key: string): Promise<{ response: Response; layer: "memory" | "storage" } | undefined> {
|
|
5
|
+
const stored = memory.get(key);
|
|
6
|
+
if (stored) return { response: new Response(stored.bytes, { headers: stored.headers }), layer: "memory" };
|
|
7
|
+
const response = await (await persistent).match(key);
|
|
8
|
+
if (response) memory.set(key, { bytes: await response.clone().arrayBuffer(), headers: [...response.headers] });
|
|
9
|
+
return response ? { response, layer: "storage" } : undefined;
|
|
10
|
+
},
|
|
11
|
+
async put(key: string, response: Response): Promise<void> {
|
|
12
|
+
const bytes = await response.clone().arrayBuffer();
|
|
13
|
+
await (await persistent).put(key, response);
|
|
14
|
+
memory.set(key, { bytes, headers: [...response.headers] });
|
|
15
|
+
},
|
|
16
|
+
async keys(): Promise<readonly Request[]> { return (await persistent).keys(); },
|
|
17
|
+
async delete(key: Request): Promise<boolean> { memory.delete(key.url); return (await persistent).delete(key); },
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { compile } from "@mdx-js/mdx";
|
|
2
|
+
import { init, parse } from "es-module-lexer";
|
|
3
|
+
import type { StoredLink } from "../link/types.ts";
|
|
4
|
+
import { linkUrl } from "../link/validation.ts";
|
|
5
|
+
import { mountLinkTarget } from "../link/overrides.ts";
|
|
6
|
+
import { compileSource, compileCommonJsSource, DEV_SHIM_URL, type MdxPlugins } from "./compile.ts";
|
|
7
|
+
import { BASE_PACKAGES, packageName, resolveSpecifier } from "./composition.ts";
|
|
8
|
+
import { CANONICAL_CANDIDATES, defineNodeEnv, parseClause, stylesheetModule } from "./module-transform.ts";
|
|
9
|
+
import { moduleUrl } from "./compiler.ts";
|
|
10
|
+
import { pageSourceModule, pageSourcePath, validatePageSourceLinks, type PageSourceLock } from "../link/page-sources.ts";
|
|
11
|
+
import type { LinkActivity } from "./link-activity.ts";
|
|
12
|
+
import { RUNTIME_MODULES } from "./runtime-module.ts";
|
|
13
|
+
|
|
14
|
+
type Context = { path: string; lock: PageSourceLock; links: StoredLink[]; sources: string[]; revision?: string };
|
|
15
|
+
const SOURCE_SUFFIXES = ["", ".tsx", ".ts", ".jsx", ".js", ".mdx", ".md", "/index.tsx", "/index.ts", "/index.js"];
|
|
16
|
+
|
|
17
|
+
function resolveLinked(specifier: string, options: Context): string {
|
|
18
|
+
const owner = options.links.find((link) => options.path.startsWith(`/link/${link.id}/`));
|
|
19
|
+
const path = owner ? decodeURIComponent(options.path.slice(`/link/${owner.id}/`.length)) : undefined;
|
|
20
|
+
const resolution = path ? owner?.build.modules[path]?.resolutions[specifier] : undefined;
|
|
21
|
+
const replacement = options.links.find(link => link.build.library === packageName(specifier));
|
|
22
|
+
if (replacement && !Object.hasOwn(replacement.build.entries, specifier)) throw new Error(`${replacement.build.library}: local checkout does not expose ${specifier}; rebuild link metadata`);
|
|
23
|
+
let target = replacement ? linkUrl(replacement.id, replacement.build.entries[specifier]!) : BASE_PACKAGES.includes(packageName(specifier)) ? resolveSpecifier({ imports: options.lock.map.imports, scopes: {} }, specifier, options.path) : resolution ? (resolution.startsWith("/npm/") ? mountLinkTarget(owner!, resolution) : linkUrl(owner!.id, resolution)) : specifier.startsWith(".") || specifier.startsWith("/") ? new URL(specifier, `https://runtime.invalid${options.path}`).pathname : resolveSpecifier(options.lock.map, specifier, options.path);
|
|
24
|
+
if (!target || /^(?:node:|https?:|data:|blob:)/.test(target)) throw new Error(`${options.path}: import ${specifier} is outside the library set; allowed packages: ${Object.keys(options.lock.versions).join(", ")}`);
|
|
25
|
+
if (target.startsWith("/src/") && options.lock.pageSources) target = pageSourceModule({ page: decodeURIComponent(target.slice(5)), roots: options.lock.pageSources }) ?? target;
|
|
26
|
+
if (target === DEV_SHIM_URL || Object.hasOwn(RUNTIME_MODULES, target)) return target;
|
|
27
|
+
const parsed = new URL(target, "https://runtime.invalid");
|
|
28
|
+
const linked = options.links.find((link) => parsed.pathname.startsWith(`/link/${link.id}/`));
|
|
29
|
+
const prefix = linked ? `/link/${linked.id}/` : parsed.pathname.startsWith("/src/") ? "/src/" : "/npm/";
|
|
30
|
+
if (!parsed.pathname.startsWith(prefix)) throw new Error(`${options.path}: unsupported module URL ${target}`);
|
|
31
|
+
const relative = decodeURIComponent(parsed.pathname.slice(prefix.length));
|
|
32
|
+
const listing = linked ? Object.keys(linked.build.modules).concat(Object.keys(linked.build.generated), Object.keys(linked.build.fragment.integrity).filter((key) => key.startsWith(`${linked.build.library}@${linked.build.version}/`)).map((key) => key.slice(`${linked.build.library}@${linked.build.version}/`.length))) : prefix === "/src/" ? options.sources : Object.keys(options.lock.integrity);
|
|
33
|
+
const found = (prefix === "/npm/" ? CANONICAL_CANDIDATES : SOURCE_SUFFIXES).map((suffix) => relative + suffix).find((candidate) => listing.includes(candidate) || (prefix === "/npm/" && options.lock.remaps[candidate] !== undefined));
|
|
34
|
+
if (!found) throw new Error(`${options.path}: cannot resolve ${specifier}; rebuild link metadata with buildLinkRuntime when adding imports`);
|
|
35
|
+
target = linked ? linkUrl(linked.id, found) : `${prefix}${prefix === "/npm/" ? options.lock.remaps[found] ?? found : found}`;
|
|
36
|
+
if (target.startsWith("/npm/")) for (const link of options.links) target = mountLinkTarget(link, target);
|
|
37
|
+
const query = new URL(specifier, "https://runtime.invalid").searchParams;
|
|
38
|
+
if (query.has("raw")) target += "?raw";
|
|
39
|
+
else if (query.has("url")) target += "?url";
|
|
40
|
+
else if (/\.(css|json)$/.test(found)) target += "?module";
|
|
41
|
+
const revised = new URL(target, "https://runtime.invalid");
|
|
42
|
+
if (options.revision && revised.pathname.startsWith("/src/")) revised.searchParams.set("revision", options.revision);
|
|
43
|
+
return moduleUrl(revised.href);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function rewriteLinkImports(options: Context & { code: string }): Promise<string> {
|
|
47
|
+
await init();
|
|
48
|
+
let output = options.code;
|
|
49
|
+
for (const item of [...parse(options.code)[0]].reverse()) {
|
|
50
|
+
if (item.type === "import-meta") continue;
|
|
51
|
+
if (!item.specifier) throw new Error(`${options.path}: dynamic imports must name a literal module`);
|
|
52
|
+
const target = resolveLinked(item.specifier, options);
|
|
53
|
+
const key = new URL(target, "https://runtime.invalid").pathname;
|
|
54
|
+
const entries = options.lock.barrels.barrels[key] ?? options.lock.barrels.barrels[key.replace(/^\/npm\//, "")];
|
|
55
|
+
const head = item.type === "static" ? /^import\s+([\s\S]+?)\s+from\s*$/.exec(options.code.slice(item.importStart, item.start - 1)) : null;
|
|
56
|
+
const clause = head ? parseClause(head[1] ?? "") : null;
|
|
57
|
+
if (entries && clause && !clause.namespace && clause.bindings.every((binding) => entries[binding.imported] !== undefined)) {
|
|
58
|
+
const statements = clause.bindings.map((binding) => {
|
|
59
|
+
const entry = entries[binding.imported]!;
|
|
60
|
+
const [position, name] = typeof entry === "number" ? [entry, binding.imported] : entry;
|
|
61
|
+
const location = options.lock.barrels.modules[position];
|
|
62
|
+
if (!location) throw new Error(`Missing barrel module ${position}`);
|
|
63
|
+
const url = resolveLinked(location.startsWith("/") ? location : `/npm/${location}`, options);
|
|
64
|
+
return `import { ${name}${name === binding.local ? "" : ` as ${binding.local}`} } from ${JSON.stringify(url)};`;
|
|
65
|
+
});
|
|
66
|
+
const end = options.code[item.importEnd] === ";" ? item.importEnd + 1 : item.importEnd;
|
|
67
|
+
output = `${output.slice(0, item.importStart)}${statements.join(" ")}${output.slice(end)}`;
|
|
68
|
+
} else {
|
|
69
|
+
const quoted = /^["'`]/.test(options.code.slice(item.start, item.end));
|
|
70
|
+
output = `${output.slice(0, item.start)}${quoted ? JSON.stringify(target) : target}${output.slice(item.end)}`;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return defineNodeEnv(output).code;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type LinkCompileOptions = Context & { code: string; query: URLSearchParams; plugins: MdxPlugins; metrics?: LinkActivity };
|
|
77
|
+
|
|
78
|
+
export async function compileLinkModule(options: LinkCompileOptions): Promise<string> {
|
|
79
|
+
const compiled = await compileLinkSource(options);
|
|
80
|
+
const revision = options.query.get("revision");
|
|
81
|
+
return compiled.imports ? await rewriteLinkModule({ ...options, ...(revision ? { revision } : {}), code: compiled.code }) : compiled.code;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function rewriteLinkModule(options: Context & { code: string; metrics?: LinkActivity }): Promise<string> {
|
|
85
|
+
const start = performance.now();
|
|
86
|
+
try { return await rewriteLinkImports(options); }
|
|
87
|
+
finally { if (options.metrics) options.metrics.rewriteMs += performance.now() - start; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Compiles a linked module up to, but not including, the rewrite of its imports. For a library module the
|
|
92
|
+
* result does not depend on the page, so it can be cached for every page; `imports` says whether the
|
|
93
|
+
* result still needs rewriteLinkModule.
|
|
94
|
+
*/
|
|
95
|
+
export async function compileLinkSource(options: LinkCompileOptions): Promise<{ code: string; imports: boolean }> {
|
|
96
|
+
validatePageSourceLinks(options);
|
|
97
|
+
const sourcePath = pageSourcePath({ path: options.path, roots: options.lock.pageSources ?? [] });
|
|
98
|
+
const extension = options.path.slice(options.path.lastIndexOf("."));
|
|
99
|
+
if (options.query.has("raw")) return { code: `export default ${JSON.stringify(options.code)};`, imports: false };
|
|
100
|
+
if (options.query.has("url")) return { code: `export default ${JSON.stringify(moduleUrl(options.path))};`, imports: false };
|
|
101
|
+
if (extension === ".json") return { code: `export default ${JSON.stringify(JSON.parse(options.code))};`, imports: false };
|
|
102
|
+
if (extension === ".css") {
|
|
103
|
+
const stylesheet = new URL(options.path, "https://runtime.invalid");
|
|
104
|
+
const revision = options.query.get("revision");
|
|
105
|
+
if (revision) stylesheet.searchParams.set("revision", revision);
|
|
106
|
+
return { code: stylesheetModule(options.code, moduleUrl(stylesheet.href)), imports: false };
|
|
107
|
+
}
|
|
108
|
+
const owner = options.links.find((link) => options.path.startsWith(`/link/${link.id}/`));
|
|
109
|
+
const commonjs = owner?.build.commonjs?.[decodeURIComponent(options.path.slice(`/link/${owner.id}/`.length))];
|
|
110
|
+
let code = options.code;
|
|
111
|
+
if (commonjs || [".ts", ".tsx", ".jsx", ".mdx", ".md"].includes(extension)) {
|
|
112
|
+
const start = performance.now();
|
|
113
|
+
if (options.metrics) options.metrics.source = "compiled";
|
|
114
|
+
try {
|
|
115
|
+
code = commonjs ? compileCommonJsSource({ path: options.path, code, conversion: { ...commonjs, target: linkUrl(owner!.id, commonjs.target) } }) : await compileSource({ path: options.path, extension, code, ...(sourcePath ? { sourcePath } : {}) }, { compile, plugins: options.plugins });
|
|
116
|
+
} finally { if (options.metrics) options.metrics.compileMs += performance.now() - start; }
|
|
117
|
+
}
|
|
118
|
+
if (owner && !commonjs && Object.hasOwn(owner.build.modules, decodeURIComponent(options.path.slice(`/link/${owner.id}/`.length)))) code = Object.entries(owner.build.defines).map(([name, value]) => `const ${name} = ${JSON.stringify(value)};`).join("\n") + "\n" + code;
|
|
119
|
+
return { code, imports: true };
|
|
120
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { StoredLink } from "../link/types.ts";
|
|
2
|
+
|
|
3
|
+
export function createFolderSourceReader() {
|
|
4
|
+
const channels = new Map<string, BroadcastChannel>();
|
|
5
|
+
const pending = new Map<string, { resolve(data: Uint8Array): void; reject(error: Error): void }>();
|
|
6
|
+
return async (options: { link: StoredLink; path: string }): Promise<Uint8Array> => {
|
|
7
|
+
const { link, path } = options;
|
|
8
|
+
if (link.source.kind !== "folder" || !link.source.session) throw new Error(`${link.id}: folder link has no host source channel; reconnect the host`);
|
|
9
|
+
let channel = channels.get(link.source.session);
|
|
10
|
+
if (!channel) {
|
|
11
|
+
channel = new BroadcastChannel(`page-runtime-link-${link.source.session}`);
|
|
12
|
+
channel.onmessage = (event: MessageEvent<{ type: string; request: string; data?: ArrayBuffer; error?: string }>) => {
|
|
13
|
+
if (event.data.type !== "reply") return;
|
|
14
|
+
const request = pending.get(event.data.request); if (!request) return;
|
|
15
|
+
if (event.data.error) request.reject(new Error(event.data.error));
|
|
16
|
+
else if (event.data.data instanceof ArrayBuffer) request.resolve(new Uint8Array(event.data.data));
|
|
17
|
+
else request.reject(new Error("Folder source reply is missing its bytes"));
|
|
18
|
+
};
|
|
19
|
+
channels.set(link.source.session, channel);
|
|
20
|
+
}
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const id = crypto.randomUUID();
|
|
23
|
+
const finish = () => { clearTimeout(timer); pending.delete(id); };
|
|
24
|
+
const timer = setTimeout(() => { finish(); reject(new Error(`${link.id}: host folder read timed out for ${path}; reconnect the host`)); }, 15000);
|
|
25
|
+
pending.set(id, { resolve(data) { finish(); resolve(data); }, reject(error) { finish(); reject(error); } });
|
|
26
|
+
channel.postMessage({ type: "read", id: link.id, path, request: id });
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// This function is serialized into the runtime-origin relay document. Keep it self-contained.
|
|
2
|
+
function relay(settings: { embedders: string[]; allowed: boolean }) {
|
|
3
|
+
const params = new URLSearchParams(location.hash.slice(1));
|
|
4
|
+
const host = params.get("host"); const session = params.get("session");
|
|
5
|
+
if (!host || !session || !settings.embedders.includes(host) || parent === window) throw new Error("Invalid library link host/session");
|
|
6
|
+
const readers = new Map<string, MessagePort>();
|
|
7
|
+
const channel = new BroadcastChannel(`page-runtime-link-${session}`);
|
|
8
|
+
channel.onmessage = (event: MessageEvent<{ type: string; id: string; request: string; path: string }>) => {
|
|
9
|
+
if (event.data.type !== "read") return;
|
|
10
|
+
const reader = readers.get(event.data.id);
|
|
11
|
+
if (!reader) return;
|
|
12
|
+
reader.postMessage(event.data);
|
|
13
|
+
};
|
|
14
|
+
window.addEventListener("message", (event: MessageEvent) => {
|
|
15
|
+
if (event.source !== parent || event.origin !== host || event.data?.channel !== "page-runtime-link-v1" || event.data.session !== session) return;
|
|
16
|
+
const port = event.ports[0]; if (!port) throw new Error("Link command needs a reply port");
|
|
17
|
+
void (async () => {
|
|
18
|
+
try {
|
|
19
|
+
if (!settings.allowed || event.data.developerOverrides !== true) throw new Error("Library links require links: allow and host developer overrides");
|
|
20
|
+
const command = event.data.command;
|
|
21
|
+
if (command.type === "install" && command.link.source.kind === "folder") {
|
|
22
|
+
const reader = event.ports[1];
|
|
23
|
+
if (!reader || command.link.source.session !== session) throw new Error("Folder link requires a host source channel");
|
|
24
|
+
readers.get(command.link.id)?.close(); readers.set(command.link.id, reader);
|
|
25
|
+
reader.onmessage = (reply: MessageEvent) => channel.postMessage({ type: "reply", ...reply.data });
|
|
26
|
+
}
|
|
27
|
+
if (command.type === "remove") { readers.get(command.id)?.close(); readers.delete(command.id); }
|
|
28
|
+
const response = await fetch("/link/_control", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...event.data, command: command.type === "install" ? { ...command, link: { ...command.link, directory: undefined } } : command }) });
|
|
29
|
+
if (!response.ok) throw new Error(await response.text());
|
|
30
|
+
port.postMessage({ result: await response.json() });
|
|
31
|
+
} catch (error) { port.postMessage({ error: String(error) }); }
|
|
32
|
+
finally { port.close(); }
|
|
33
|
+
})();
|
|
34
|
+
});
|
|
35
|
+
parent.postMessage({ channel: "page-runtime-link-v1", session, ...(settings.allowed ? {} : { error: "Library links are denied by the runtime profile" }) }, host);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function linkRelayDocument(settings: { embedders: string[]; allowed: boolean }): string {
|
|
39
|
+
return `<!doctype html><meta charset="utf-8"><title>Library link connection</title><script>(${relay.toString()})(${JSON.stringify(settings).replaceAll("<", "\\u003c")})</script>`;
|
|
40
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type { FrameConfig } from "../schema.ts";
|
|
2
|
+
import type { StoredLink, LinkCommand } from "../link/types.ts";
|
|
3
|
+
import { assertLinksAllowed, linkUrl, validateLink } from "../link/validation.ts";
|
|
4
|
+
import { linksInLock } from "../link/overrides.ts";
|
|
5
|
+
import { createLinkStore } from "../link/storage.ts";
|
|
6
|
+
import { compileLinkModule, compileLinkSource, rewriteLinkImports, rewriteLinkModule } from "./link-compiler.ts";
|
|
7
|
+
import { DEV_SHIM, DEV_SHIM_URL } from "./compile.ts";
|
|
8
|
+
import { frameDocument, contentSecurityPolicy } from "./router.ts";
|
|
9
|
+
import { moduleUrl, requestModuleUrl } from "./compiler.ts";
|
|
10
|
+
import { createFolderSourceReader } from "./link-folder.ts";
|
|
11
|
+
import { createLinkCache } from "./link-cache.ts";
|
|
12
|
+
import { linkRelayDocument } from "./link-relay.ts";
|
|
13
|
+
import { lazyRuntimeDb, putCandidates } from "../storage/db.ts";
|
|
14
|
+
import { digest } from "./integrity.ts";
|
|
15
|
+
import { CONTENT_TYPES, extensionOf } from "./content-types.ts";
|
|
16
|
+
import { RuntimeFailure } from "./errors.ts";
|
|
17
|
+
import type { RouterOptions } from "./router.ts";
|
|
18
|
+
import { RUNTIME_MODULES, runtimeModuleSource } from "./runtime-module.ts";
|
|
19
|
+
import { sourceCandidates } from "./candidates.ts";
|
|
20
|
+
import { isPageModule, pageSourceModule, validatePageSourceLinks, type PageSourceLock } from "../link/page-sources.ts";
|
|
21
|
+
import { byteLength } from "./activity.ts";
|
|
22
|
+
import { cachedLinkActivity, createLinkActivity, linkActivityResponse, type LinkActivity } from "./link-activity.ts";
|
|
23
|
+
import { readLinkedSource } from "./link-source.ts";
|
|
24
|
+
|
|
25
|
+
type Page = { lock: PageSourceLock; files: Record<string, string> };
|
|
26
|
+
export const LINK_CONTEXT_HEADER = "x-link-context";
|
|
27
|
+
type Options = RouterOptions & { load(page: string): Promise<Page>; store?: ReturnType<typeof createLinkStore>; database?: () => Promise<IDBDatabase> };
|
|
28
|
+
|
|
29
|
+
export function createLinkRoutes(options: Options) {
|
|
30
|
+
const storage = options.store ?? createLinkStore();
|
|
31
|
+
const database = options.database ?? lazyRuntimeDb(options.indexedDB ? { factory: options.indexedDB } : {});
|
|
32
|
+
const output = createLinkCache(options.caches.open(`page-runtime-${options.version}-links-source-sizes`));
|
|
33
|
+
const prefix = `${options.origin}/__runtime/link-cache/`;
|
|
34
|
+
const loadedLinks = new Map<string, Promise<StoredLink>>();
|
|
35
|
+
const contexts = new Map<string, { saved: Page; links: StoredLink[]; config?: FrameConfig }>();
|
|
36
|
+
let contextKeys = new WeakMap<Page, { paths: string; pending: Promise<{ links: StoredLink[]; id: string }> }>();
|
|
37
|
+
const buildDigests = new WeakMap<StoredLink, Promise<string>>();
|
|
38
|
+
const buildDigest = (link: StoredLink) => {
|
|
39
|
+
let pending = buildDigests.get(link);
|
|
40
|
+
if (!pending) { pending = digest(new TextEncoder().encode(JSON.stringify(link.build))); buildDigests.set(link, pending); }
|
|
41
|
+
return pending;
|
|
42
|
+
};
|
|
43
|
+
const moduleGraphs = new Map<string, Set<string>>();
|
|
44
|
+
const usedFiles = new Map<string, Record<string, string>>();
|
|
45
|
+
const readFolder = createFolderSourceReader();
|
|
46
|
+
const getLink = (id: string) => {
|
|
47
|
+
let link = loadedLinks.get(id);
|
|
48
|
+
if (!link) { link = storage.get(id); loadedLinks.set(id, link); void link.catch(() => loadedLinks.delete(id)); }
|
|
49
|
+
return link;
|
|
50
|
+
};
|
|
51
|
+
async function control(request: Request): Promise<Response> {
|
|
52
|
+
if (request.method !== "POST") throw new Error("Link control requires POST");
|
|
53
|
+
if (request.headers.get("origin") && request.headers.get("origin") !== options.origin) throw new Error("Link control requires the runtime origin");
|
|
54
|
+
const body = await request.json() as { developerOverrides: boolean; command: LinkCommand };
|
|
55
|
+
assertLinksAllowed({ profile: options.profile, developerOverrides: body.developerOverrides });
|
|
56
|
+
const command = body.command;
|
|
57
|
+
if (command.type === "install") {
|
|
58
|
+
validateLink(command.link);
|
|
59
|
+
const link = command.link;
|
|
60
|
+
if (link.source.kind === "folder" && !link.source.session) throw new Error("Folder link requires a host source channel");
|
|
61
|
+
await storage.put(link);
|
|
62
|
+
loadedLinks.set(link.id, Promise.resolve(link));
|
|
63
|
+
usedFiles.delete(link.id);
|
|
64
|
+
contexts.clear();
|
|
65
|
+
contextKeys = new WeakMap();
|
|
66
|
+
moduleGraphs.clear();
|
|
67
|
+
await invalidate(link.id);
|
|
68
|
+
} else if (command.type === "files") {
|
|
69
|
+
await getLink(command.id);
|
|
70
|
+
return Response.json({ ok: true, files: usedFiles.get(command.id) ?? {} });
|
|
71
|
+
} else if (command.type === "invalidate") {
|
|
72
|
+
await getLink(command.id);
|
|
73
|
+
for (const path of command.paths) linkUrl(command.id, path);
|
|
74
|
+
await invalidate(command.id, command.paths);
|
|
75
|
+
} else if (command.type === "remove") { await storage.remove(command.id); loadedLinks.delete(command.id); usedFiles.delete(command.id); contexts.clear(); contextKeys = new WeakMap(); moduleGraphs.clear(); await invalidate(command.id); }
|
|
76
|
+
else throw new Error("Unknown link control command");
|
|
77
|
+
return Response.json({ ok: true });
|
|
78
|
+
}
|
|
79
|
+
async function invalidate(id: string, paths?: string[]): Promise<void> {
|
|
80
|
+
linkUrl(id, "package.json");
|
|
81
|
+
const cache = output;
|
|
82
|
+
const starts = paths?.map((path) => `${prefix}${id}/${encodeURIComponent(path)}?`);
|
|
83
|
+
await Promise.all((await cache.keys()).filter((key) => starts ? starts.some((start) => key.url.startsWith(start)) : key.url.startsWith(`${prefix}${id}/`)).map((key) => cache.delete(key)));
|
|
84
|
+
}
|
|
85
|
+
// Page modules are cached whole per page context. Library modules are cached compiled but not yet
|
|
86
|
+
// rewritten, keyed only by their own source and link build, so every page shares them; each page
|
|
87
|
+
// then rewrites the imports through its own import map.
|
|
88
|
+
async function serve({ request, saved, links, contextId, metrics }: { request: Request; saved: Page; links: StoredLink[]; contextId: string; metrics: LinkActivity }): Promise<Response> {
|
|
89
|
+
const url = new URL(request.url);
|
|
90
|
+
const owner = links.find((link) => url.pathname.startsWith(`/link/${link.id}/`));
|
|
91
|
+
const path = owner ? decodeURIComponent(url.pathname.slice(`/link/${owner.id}/`.length)) : decodeURIComponent(url.pathname.slice(5));
|
|
92
|
+
if (owner) linkUrl(owner.id, path);
|
|
93
|
+
if (url.pathname.startsWith("/link/") && !owner) throw new Error(`${url.pathname}: link is not enabled for this page`);
|
|
94
|
+
const query = new URLSearchParams([...url.searchParams].filter(([key]) => key !== "page" && key !== "link-context")).toString();
|
|
95
|
+
const library = !isPageModule({ path: url.pathname, lock: saved.lock });
|
|
96
|
+
const pageSource = !owner && url.pathname.startsWith("/src/");
|
|
97
|
+
const identity = owner ? (library ? `&build=${encodeURIComponent(await buildDigest(owner))}` : "") : `&integrity=${encodeURIComponent(saved.lock.integrity[path] ?? "")}`;
|
|
98
|
+
const scope = library ? "library" : contextId;
|
|
99
|
+
const key = pageSource ? undefined : `${prefix}${owner?.id ?? "page"}/${encodeURIComponent(path)}?context=${encodeURIComponent(scope)}&query=${encodeURIComponent(query)}${identity}`;
|
|
100
|
+
const cache = output;
|
|
101
|
+
const record = (response: Response) => {
|
|
102
|
+
if (owner?.build.modules[path]) {
|
|
103
|
+
const hash = response.headers.get("x-link-source-hash");
|
|
104
|
+
if (!hash) throw new Error(`Linked cache entry ${path} is missing its source hash`);
|
|
105
|
+
const files = usedFiles.get(owner.id) ?? {}; files[path] = hash; usedFiles.set(owner.id, files);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
if (owner?.source.kind === "server") metrics.origin = new URL(path.split("/").map(encodeURIComponent).join("/"), owner.source.url.replace(/\/?$/, "/")).href;
|
|
109
|
+
else if (!owner && !url.pathname.startsWith("/src/")) metrics.origin = `${saved.lock.packageOrigin.replace(/\/$/, "")}/${path}`;
|
|
110
|
+
let entry = key ? await cache.match(key) : undefined;
|
|
111
|
+
let compiledNow = false;
|
|
112
|
+
if (!entry) {
|
|
113
|
+
const bytes = await readLinkedSource({ owner, path, source: url.pathname.startsWith("/src/"), files: saved.files, lock: saved.lock, metrics, fetch: options.fetch ?? fetch, readFolder });
|
|
114
|
+
const module = /\.(tsx?|jsx?|mdx?|mjs|cjs)$/.test(path) || url.searchParams.has("module") || url.searchParams.has("raw") || url.searchParams.has("url") || request.destination === "script";
|
|
115
|
+
const sourceHash = await digest(new Uint8Array(bytes));
|
|
116
|
+
const contentKey = `${options.origin}/__runtime/link-content/${encodeURIComponent(scope)}/${encodeURIComponent(url.pathname)}/${encodeURIComponent(sourceHash)}?query=${encodeURIComponent(query)}${identity}`;
|
|
117
|
+
entry = await cache.match(contentKey);
|
|
118
|
+
if (entry && key) await cache.put(key, entry.response.clone());
|
|
119
|
+
if (!entry) {
|
|
120
|
+
const code = new TextDecoder().decode(bytes);
|
|
121
|
+
const compileOptions = { path: url.pathname, code, lock: saved.lock, sources: Object.keys(saved.files), links, query: url.searchParams, plugins: options.plugins, metrics };
|
|
122
|
+
const result = !module ? { code: bytes, imports: false } : library ? await compileLinkSource(compileOptions) : { code: await compileLinkModule(compileOptions), imports: false };
|
|
123
|
+
const size = typeof result.code === "string" ? byteLength(result.code) : result.code.byteLength;
|
|
124
|
+
const response = new Response(result.code as BodyInit, { headers: { "content-type": module ? "text/javascript; charset=utf-8" : CONTENT_TYPES[extensionOf(path)] ?? "application/octet-stream", "content-length": String(size), "x-link-source-bytes": String(bytes.byteLength), "x-link-imports": result.imports ? "1" : "0", "x-link-source-hash": sourceHash, "x-page-candidates": encodeURIComponent(JSON.stringify(sourceCandidates({ path, code }))) } });
|
|
125
|
+
await cache.put(contentKey, response.clone());
|
|
126
|
+
if (key) await cache.put(key, response.clone());
|
|
127
|
+
entry = { response, layer: "memory" };
|
|
128
|
+
compiledNow = true;
|
|
129
|
+
metrics.outputBytes = size;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
record(entry.response);
|
|
133
|
+
if (!compiledNow) cachedLinkActivity({ ...entry, metrics });
|
|
134
|
+
const headers = new Headers(entry.response.headers); headers.set("x-link-compiled", compiledNow ? "1" : "0");
|
|
135
|
+
const rememberCandidates = async () => {
|
|
136
|
+
if (!url.pathname.startsWith("/src/") && !owner?.build.modules[path]) return;
|
|
137
|
+
const candidates = JSON.parse(decodeURIComponent(headers.get("x-page-candidates")!)) as string[];
|
|
138
|
+
await putCandidates(await database(), { page: saved.lock.page, module: url.pathname, sourceHash: headers.get("x-link-source-hash")!, candidates });
|
|
139
|
+
};
|
|
140
|
+
if (headers.get("x-link-imports") !== "1") { if (compiledNow) await rememberCandidates(); return new Response(entry.response.body, { headers }); }
|
|
141
|
+
const linkedKey = `${options.origin}/__runtime/link-rewritten/${encodeURIComponent(contextId)}/${encodeURIComponent(url.pathname)}/${encodeURIComponent(headers.get("x-link-source-hash")!)}?query=${encodeURIComponent(query)}${identity}`;
|
|
142
|
+
const rewritten = await cache.match(linkedKey);
|
|
143
|
+
if (rewritten) {
|
|
144
|
+
metrics.outputBytes = Number(rewritten.response.headers.get("content-length")); headers.set("content-length", String(metrics.outputBytes));
|
|
145
|
+
return new Response(rewritten.response.body, { headers });
|
|
146
|
+
}
|
|
147
|
+
await rememberCandidates();
|
|
148
|
+
const code = await rewriteLinkModule({ path: url.pathname, code: await entry.response.text(), lock: saved.lock, links, sources: Object.keys(saved.files), metrics });
|
|
149
|
+
metrics.outputBytes = byteLength(code); headers.set("content-length", String(metrics.outputBytes));
|
|
150
|
+
await cache.put(linkedKey, new Response(code, { headers: { "content-length": String(metrics.outputBytes) } }));
|
|
151
|
+
return new Response(code, { headers });
|
|
152
|
+
}
|
|
153
|
+
return async (request: Request): Promise<Response | undefined> => {
|
|
154
|
+
const url = new URL(request.url);
|
|
155
|
+
if (url.pathname === "/frame/__runtime-link-relay" || url.pathname === "/frame/_link-relay") return new Response(linkRelayDocument({ embedders: options.profile.embedders, allowed: options.profile.links === "allow" }), { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
156
|
+
if (url.pathname === "/link/_control") {
|
|
157
|
+
try { return await control(request); } catch (error) { console.error("Link control request rejected", error); return new Response("Link control request rejected", { status: 403 }); }
|
|
158
|
+
}
|
|
159
|
+
const frame = url.pathname.startsWith("/frame/");
|
|
160
|
+
if (!/^\/(src|npm|link|frame)\//.test(url.pathname) && url.pathname !== DEV_SHIM_URL && !Object.hasOwn(RUNTIME_MODULES, url.pathname)) return undefined;
|
|
161
|
+
const page = url.searchParams.get("page") ?? (frame ? decodeURIComponent(url.pathname.slice(7)) : null);
|
|
162
|
+
if (frame && !(await (await options.caches.open(`page-runtime-${options.version}-pages`)).match(`${options.origin}/__runtime/pages/${encodeURIComponent(page!)}`))) return undefined;
|
|
163
|
+
if (!page) { if (url.pathname.startsWith("/link/")) throw new RuntimeFailure({ phase: "link", file: url.pathname, message: "Linked module requires a page context" }); return undefined; }
|
|
164
|
+
const metrics = createLinkActivity();
|
|
165
|
+
try {
|
|
166
|
+
const requested = url.searchParams.get("link-context");
|
|
167
|
+
const saved = await options.load(page);
|
|
168
|
+
const ids = linksInLock(saved.lock);
|
|
169
|
+
if (!ids.length && !url.pathname.startsWith("/link/")) return undefined;
|
|
170
|
+
const paths = JSON.stringify(Object.keys(saved.files).sort());
|
|
171
|
+
let key = contextKeys.get(saved);
|
|
172
|
+
if (!key || key.paths !== paths) {
|
|
173
|
+
const pending = (async () => {
|
|
174
|
+
const links = await Promise.all(ids.map(getLink));
|
|
175
|
+
validatePageSourceLinks({ lock: saved.lock, links });
|
|
176
|
+
return { links, id: await digest(new TextEncoder().encode(JSON.stringify({ lock: { ...saved.lock, integrity: Object.keys(saved.lock.integrity).sort() }, paths, builds: links.map((link) => link.build) }))) };
|
|
177
|
+
})();
|
|
178
|
+
key = { paths, pending };
|
|
179
|
+
contextKeys.set(saved, key);
|
|
180
|
+
void pending.catch(() => { if (contextKeys.get(saved)?.pending === pending) contextKeys.delete(saved); });
|
|
181
|
+
}
|
|
182
|
+
const resolved = await key.pending;
|
|
183
|
+
const contextId = resolved.id;
|
|
184
|
+
if (requested && requested !== contextId) throw new Error("Page link context changed; reload the frame");
|
|
185
|
+
let context = contexts.get(contextId);
|
|
186
|
+
if (!context) { context = { saved, links: resolved.links }; contexts.set(contextId, context); }
|
|
187
|
+
else if (context.saved !== saved) { context.saved = saved; context.links = resolved.links; delete context.config; }
|
|
188
|
+
if (context.saved.lock.page !== page) throw new Error("Link context belongs to a different page");
|
|
189
|
+
assertLinksAllowed({ profile: options.profile, developerOverrides: context.links.length > 0 });
|
|
190
|
+
if (frame) {
|
|
191
|
+
context.config ??= { page, entry: moduleUrl(pageSourceModule({ page, roots: context.saved.lock.pageSources ?? [] }) ?? `/src/${page}`), lock: context.saved.lock, profile: { ...options.profile, packageOrigin: context.saved.lock.packageOrigin }, runtimeVersion: options.version };
|
|
192
|
+
const document = frameDocument({ config: context.config, preload: moduleGraphs.get(contextId) ?? [] });
|
|
193
|
+
return new Response(document.html, { headers: { "content-type": "text/html; charset=utf-8", "content-length": String(byteLength(document.html)), "content-security-policy": contentSecurityPolicy(context.config.profile, document.nonce), [LINK_CONTEXT_HEADER]: contextId } });
|
|
194
|
+
}
|
|
195
|
+
if (url.pathname === DEV_SHIM_URL || Object.hasOwn(RUNTIME_MODULES, url.pathname)) {
|
|
196
|
+
const file = RUNTIME_MODULES[url.pathname];
|
|
197
|
+
metrics.source = "generated"; metrics.generated = file === "page-agent.js" ? "page agent module" : file ? "export compiler module" : "JSX development shim";
|
|
198
|
+
let source = DEV_SHIM;
|
|
199
|
+
if (file) {
|
|
200
|
+
metrics.source = "network"; metrics.origin = `${options.origin}/${file}`; metrics.transferredBytes = null;
|
|
201
|
+
const start = performance.now();
|
|
202
|
+
try { source = await runtimeModuleSource({ origin: options.origin, file, fetch: async (input, init) => {
|
|
203
|
+
const response = await (options.fetch ?? fetch)(input, init);
|
|
204
|
+
metrics.transferredBytes = response.headers.has("content-length") ? Number(response.headers.get("content-length")) : null;
|
|
205
|
+
return response;
|
|
206
|
+
} }); } finally { metrics.fetchMs = performance.now() - start; }
|
|
207
|
+
}
|
|
208
|
+
metrics.decodedBytes = byteLength(source);
|
|
209
|
+
const sourceHash = await digest(new TextEncoder().encode(source));
|
|
210
|
+
const key = `${options.origin}/__runtime/link-generated/${encodeURIComponent(contextId)}/${encodeURIComponent(url.pathname)}/${encodeURIComponent(sourceHash)}`;
|
|
211
|
+
const cached = await output.match(key);
|
|
212
|
+
if (cached) {
|
|
213
|
+
cachedLinkActivity({ ...cached, metrics });
|
|
214
|
+
const headers = new Headers(cached.response.headers); headers.set("x-link-compiled", "0");
|
|
215
|
+
return linkActivityResponse({ response: new Response(cached.response.body, { headers }), metrics });
|
|
216
|
+
}
|
|
217
|
+
const start = performance.now();
|
|
218
|
+
let code: string;
|
|
219
|
+
try { code = await rewriteLinkImports({ code: source, path: url.pathname, lock: context.saved.lock, links: context.links, sources: [] }); }
|
|
220
|
+
finally { metrics.rewriteMs = performance.now() - start; }
|
|
221
|
+
metrics.outputBytes = byteLength(code);
|
|
222
|
+
const response = new Response(code, { headers: { "content-type": "text/javascript; charset=utf-8", "content-length": String(metrics.outputBytes), "x-link-source-bytes": String(metrics.decodedBytes), "x-link-compiled": "1" } });
|
|
223
|
+
await output.put(key, response.clone());
|
|
224
|
+
return linkActivityResponse({ response, metrics });
|
|
225
|
+
}
|
|
226
|
+
const response = await serve({ request, saved: context.saved, links: context.links, contextId, metrics });
|
|
227
|
+
if (response.headers.get("content-type")?.startsWith("text/javascript")) {
|
|
228
|
+
let graph = moduleGraphs.get(contextId);
|
|
229
|
+
if (!graph) { graph = new Set(); moduleGraphs.set(contextId, graph); }
|
|
230
|
+
graph.add(requestModuleUrl(url));
|
|
231
|
+
}
|
|
232
|
+
return linkActivityResponse({ response, metrics });
|
|
233
|
+
} catch (error) {
|
|
234
|
+
const failure = new RuntimeFailure({ phase: "link", file: url.pathname, message: String(error) });
|
|
235
|
+
failure.activity = metrics;
|
|
236
|
+
throw failure;
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { StoredLink } from "../link/types.ts";
|
|
2
|
+
import { readLinkFile } from "../link/source.ts";
|
|
3
|
+
import type { PageLock } from "../schema.ts";
|
|
4
|
+
import type { LinkActivity } from "./link-activity.ts";
|
|
5
|
+
import { verifyIntegrity } from "./integrity.ts";
|
|
6
|
+
|
|
7
|
+
export async function readLinkedSource(options: {
|
|
8
|
+
owner: StoredLink | undefined; path: string; source: boolean; files: Record<string, string>; lock: PageLock;
|
|
9
|
+
metrics: LinkActivity; fetch: typeof fetch; readFolder: (options: { link: StoredLink; path: string }) => Promise<Uint8Array>;
|
|
10
|
+
}): Promise<Uint8Array> {
|
|
11
|
+
const { owner, path, metrics } = options;
|
|
12
|
+
if (!owner && options.source) {
|
|
13
|
+
const code = options.files[path]; if (code === undefined) throw new Error(`Source ${path} does not exist`);
|
|
14
|
+
const bytes = new TextEncoder().encode(code); metrics.decodedBytes = bytes.byteLength; return bytes;
|
|
15
|
+
}
|
|
16
|
+
if (!owner && !options.lock.integrity[path]) throw new Error(`${path} is outside the library set`);
|
|
17
|
+
if (metrics.origin) { metrics.source = "network"; metrics.transferredBytes = null; }
|
|
18
|
+
const fetchSource = options.fetch;
|
|
19
|
+
const fetcher: typeof fetch = async (input, init) => {
|
|
20
|
+
const response = await fetchSource(input, init);
|
|
21
|
+
metrics.transferredBytes = response.headers.has("content-length") ? Number(response.headers.get("content-length")) : null;
|
|
22
|
+
return response;
|
|
23
|
+
};
|
|
24
|
+
const fetching = performance.now();
|
|
25
|
+
let bytes: Uint8Array;
|
|
26
|
+
try {
|
|
27
|
+
if (owner) bytes = owner.source.kind === "folder" ? await options.readFolder({ link: owner, path }) : await readLinkFile({ link: owner, path, fetch: fetcher });
|
|
28
|
+
else {
|
|
29
|
+
const response = await fetcher(metrics.origin!, { mode: "cors", credentials: "omit", redirect: "error" });
|
|
30
|
+
if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`);
|
|
31
|
+
bytes = new Uint8Array(await response.arrayBuffer());
|
|
32
|
+
}
|
|
33
|
+
metrics.decodedBytes = bytes.byteLength;
|
|
34
|
+
} finally { metrics.fetchMs = performance.now() - fetching; }
|
|
35
|
+
if (!owner) {
|
|
36
|
+
const checking = performance.now();
|
|
37
|
+
try { await verifyIntegrity(new Uint8Array(bytes), options.lock.integrity[path]!, path); }
|
|
38
|
+
finally { metrics.integrityMs = performance.now() - checking; }
|
|
39
|
+
}
|
|
40
|
+
return bytes;
|
|
41
|
+
}
|