@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,306 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { parseSync } from "rolldown/utils";
|
|
4
|
+
import { resolveSpecifier } from "./fragment.ts";
|
|
5
|
+
import type { ImportMap, BarrelIndex } from "../schema.ts";
|
|
6
|
+
import { CANONICAL_CANDIDATES, NPM_PREFIX, specifierKind } from "./module-utils.ts";
|
|
7
|
+
import { moduleFormat, packageOf, type TracedFile } from "./trace.ts";
|
|
8
|
+
|
|
9
|
+
type ModuleRecord = ReturnType<typeof parseSync>["module"];
|
|
10
|
+
|
|
11
|
+
/** What a module imports and exports, reduced to what barrel resolution needs. */
|
|
12
|
+
export type ModuleShape = {
|
|
13
|
+
/** Local binding → the module request it comes from and the name imported there (`*` for a namespace). */
|
|
14
|
+
imports: Map<string, { from: string; name: string }>;
|
|
15
|
+
/** Exported name → the request and name it forwards, or only a local name for a binding defined here. */
|
|
16
|
+
exports: Map<string, { from?: string; name: string }>;
|
|
17
|
+
/** Requests of `export * from`. */
|
|
18
|
+
stars: string[];
|
|
19
|
+
/** Requests imported only for their side effects (`import "x"`). */
|
|
20
|
+
sideEffectImports: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type BarrelLocation = { url: string; name: string };
|
|
24
|
+
|
|
25
|
+
type StaticImportRecord = ModuleRecord["staticImports"][number];
|
|
26
|
+
type StaticExportEntryRecord = ModuleRecord["staticExports"][number]["entries"][number];
|
|
27
|
+
|
|
28
|
+
function importedName(entry: StaticImportRecord["entries"][number]): string {
|
|
29
|
+
const kind = entry.importName.kind;
|
|
30
|
+
return kind === "NamespaceObject" ? "*" : kind === "Default" ? "default" : (entry.importName.name ?? "");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* oxc folds `import X from "m"; export { X as Y }` into an export entry placed at the import statement, and names
|
|
35
|
+
* X's local binding as the imported name. The import entry the export points into gives the name `m` exports.
|
|
36
|
+
*/
|
|
37
|
+
function forwardedName(entry: StaticExportEntryRecord, declaration: StaticImportRecord | undefined): string {
|
|
38
|
+
if (entry.importName.kind === "All") return "*";
|
|
39
|
+
if (!declaration) return entry.importName.name ?? "";
|
|
40
|
+
const start = entry.importName.start;
|
|
41
|
+
const binding = declaration.entries.find((candidate) => candidate.localName.start === start || candidate.importName.start === start);
|
|
42
|
+
if (!binding) throw new Error(`export ${entry.exportName.name} folded from the import at ${declaration.start} names no binding of that import`);
|
|
43
|
+
return importedName(binding);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function shapeOf(module: ModuleRecord): ModuleShape {
|
|
47
|
+
const imports = new Map<string, { from: string; name: string }>();
|
|
48
|
+
const declarations = new Map<number, StaticImportRecord>();
|
|
49
|
+
const sideEffectImports: string[] = [];
|
|
50
|
+
for (const item of module.staticImports) {
|
|
51
|
+
declarations.set(item.start, item);
|
|
52
|
+
if (item.entries.length === 0) sideEffectImports.push(item.moduleRequest.value);
|
|
53
|
+
for (const entry of item.entries) {
|
|
54
|
+
if (!entry.isType) imports.set(entry.localName.value, { from: item.moduleRequest.value, name: importedName(entry) });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const exports = new Map<string, { from?: string; name: string }>();
|
|
58
|
+
const stars: string[] = [];
|
|
59
|
+
for (const item of module.staticExports) {
|
|
60
|
+
const declaration = declarations.get(item.start);
|
|
61
|
+
for (const entry of item.entries) {
|
|
62
|
+
if (entry.isType) continue;
|
|
63
|
+
const request = entry.moduleRequest?.value;
|
|
64
|
+
if (entry.importName.kind === "AllButDefault") {
|
|
65
|
+
if (request) stars.push(request);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const exported = entry.exportName.kind === "Default" ? "default" : entry.exportName.name;
|
|
69
|
+
if (!exported) continue;
|
|
70
|
+
// A local export, `export default <expression>` included, is defined here.
|
|
71
|
+
const local = entry.localName.kind === "Name" ? (entry.localName.name ?? "default") : "default";
|
|
72
|
+
exports.set(exported, request ? { from: request, name: forwardedName(entry, declaration) } : { name: local });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { imports, exports, stars, sideEffectImports };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function forwards(shape: ModuleShape): boolean {
|
|
79
|
+
return shape.stars.length > 0 || [...shape.exports.values()].some((entry) => entry.from !== undefined);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type BarrelIndexInput = {
|
|
83
|
+
/** Candidate barrels. */
|
|
84
|
+
urls: string[];
|
|
85
|
+
shape: (url: string) => ModuleShape | null;
|
|
86
|
+
/** The URL a module request in `url` loads, or null when it leaves the indexed files. */
|
|
87
|
+
resolve: (url: string, specifier: string) => string | null;
|
|
88
|
+
/** Whether the module's package declares it free of side effects, so a page may skip evaluating it. */
|
|
89
|
+
sideEffectFree: (url: string) => boolean;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type BuiltBarrelIndex = {
|
|
93
|
+
index: BarrelIndex;
|
|
94
|
+
/** Modules declared side-effect-free that still cannot be skipped, with the reason. */
|
|
95
|
+
kept: Array<{ url: string; reason: string }>;
|
|
96
|
+
/** Forwarding modules whose package does not declare them side-effect-free. */
|
|
97
|
+
blocked: string[];
|
|
98
|
+
names: number;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Follows every forwarding module's exports to the module that defines each name, the way a bundler honouring
|
|
103
|
+
* `sideEffects` skips re-export modules. A hop goes through a module only when that module may be skipped. A name the
|
|
104
|
+
* index cannot place exactly (a namespace, an ambiguous or unresolvable `export *`) stops at the module where the
|
|
105
|
+
* browser's own resolution would continue, which is always safe to import from.
|
|
106
|
+
*/
|
|
107
|
+
export function buildBarrelIndex(input: BarrelIndexInput): BuiltBarrelIndex {
|
|
108
|
+
const kept = new Map<string, string>();
|
|
109
|
+
const blocked = new Set<string>();
|
|
110
|
+
const skippable = (url: string): boolean => {
|
|
111
|
+
const shape = input.shape(url);
|
|
112
|
+
if (!shape) return false;
|
|
113
|
+
if (!input.sideEffectFree(url)) {
|
|
114
|
+
if (forwards(shape)) blocked.add(url);
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
if (shape.sideEffectImports.length > 0) {
|
|
118
|
+
kept.set(url, `imports ${shape.sideEffectImports.join(", ")} for its side effects`);
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const memo = new Map<string, BarrelLocation | null>();
|
|
125
|
+
const active = new Set<string>();
|
|
126
|
+
const locate = (url: string, name: string): BarrelLocation | null => {
|
|
127
|
+
const key = `${url}#${name}`;
|
|
128
|
+
if (memo.has(key)) return memo.get(key) ?? null;
|
|
129
|
+
if (active.has(key)) return null;
|
|
130
|
+
active.add(key);
|
|
131
|
+
const location = find(url, name);
|
|
132
|
+
active.delete(key);
|
|
133
|
+
memo.set(key, location);
|
|
134
|
+
return location;
|
|
135
|
+
};
|
|
136
|
+
const find = (url: string, name: string): BarrelLocation | null => {
|
|
137
|
+
const shape = input.shape(url);
|
|
138
|
+
if (!shape) return null;
|
|
139
|
+
const here = { url, name };
|
|
140
|
+
const forward = shape.exports.get(name);
|
|
141
|
+
if (forward) {
|
|
142
|
+
if (forward.from === undefined || forward.name === "*" || !skippable(url)) return here;
|
|
143
|
+
const target = input.resolve(url, forward.from);
|
|
144
|
+
return (target && locate(target, forward.name)) || here;
|
|
145
|
+
}
|
|
146
|
+
if (name === "default" || shape.stars.length === 0) return null;
|
|
147
|
+
const found = new Map<string, BarrelLocation>();
|
|
148
|
+
let unresolved = false;
|
|
149
|
+
for (const star of shape.stars) {
|
|
150
|
+
const target = input.resolve(url, star);
|
|
151
|
+
if (!target || !input.shape(target)) {
|
|
152
|
+
unresolved = true;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const location = locate(target, name);
|
|
156
|
+
if (location) found.set(`${location.url}#${location.name}`, location);
|
|
157
|
+
}
|
|
158
|
+
if (unresolved || found.size > 1) return here;
|
|
159
|
+
const [only] = found.values();
|
|
160
|
+
if (!only) return null;
|
|
161
|
+
return skippable(url) ? only : here;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const namesMemo = new Map<string, Set<string>>();
|
|
165
|
+
const stack = new Set<string>();
|
|
166
|
+
const exportNames = (url: string): Set<string> => {
|
|
167
|
+
const known = namesMemo.get(url);
|
|
168
|
+
if (known) return known;
|
|
169
|
+
const shape = input.shape(url);
|
|
170
|
+
const names = new Set(shape?.exports.keys() ?? []);
|
|
171
|
+
if (!shape || stack.has(url)) return names;
|
|
172
|
+
stack.add(url);
|
|
173
|
+
for (const star of shape.stars) {
|
|
174
|
+
const target = input.resolve(url, star);
|
|
175
|
+
for (const name of target ? exportNames(target) : []) if (name !== "default") names.add(name);
|
|
176
|
+
}
|
|
177
|
+
stack.delete(url);
|
|
178
|
+
namesMemo.set(url, names);
|
|
179
|
+
return names;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const index: BarrelIndex = { modules: [], barrels: {} };
|
|
183
|
+
const positions = new Map<string, number>();
|
|
184
|
+
let names = 0;
|
|
185
|
+
for (const url of input.urls) {
|
|
186
|
+
const shape = input.shape(url);
|
|
187
|
+
if (!shape || !forwards(shape) || !skippable(url)) continue;
|
|
188
|
+
const entries: Record<string, number | [number, string]> = {};
|
|
189
|
+
for (const name of exportNames(url)) {
|
|
190
|
+
const location = locate(url, name);
|
|
191
|
+
if (!location || location.url === url) continue;
|
|
192
|
+
let position = positions.get(location.url);
|
|
193
|
+
if (position === undefined) {
|
|
194
|
+
position = index.modules.push(location.url) - 1;
|
|
195
|
+
positions.set(location.url, position);
|
|
196
|
+
}
|
|
197
|
+
entries[name] = location.name === name ? position : [position, location.name];
|
|
198
|
+
names += 1;
|
|
199
|
+
}
|
|
200
|
+
if (Object.keys(entries).length > 0) index.barrels[url] = entries;
|
|
201
|
+
}
|
|
202
|
+
return { index, kept: [...kept].map(([url, reason]) => ({ url, reason })), blocked: [...blocked], names };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Converts a `sideEffects` glob to a RegExp over package-relative paths, with webpack's matching rules. */
|
|
206
|
+
function sideEffectsPattern(pattern: string, id: string): RegExp {
|
|
207
|
+
const glob = pattern.replace(/^\.\//, "");
|
|
208
|
+
const full = glob.includes("/") ? glob : `**/${glob}`;
|
|
209
|
+
let source = "";
|
|
210
|
+
let braces = 0;
|
|
211
|
+
for (let i = 0; i < full.length; i += 1) {
|
|
212
|
+
const char = full[i] ?? "";
|
|
213
|
+
if (char === "*" && full[i + 1] === "*") {
|
|
214
|
+
const slash = full[i + 2] === "/";
|
|
215
|
+
source += slash ? "(?:.*/)?" : ".*";
|
|
216
|
+
i += slash ? 2 : 1;
|
|
217
|
+
} else if (char === "*") source += "[^/]*";
|
|
218
|
+
else if (char === "?") source += "[^/]";
|
|
219
|
+
else if (char === "{") {
|
|
220
|
+
braces += 1;
|
|
221
|
+
source += "(?:";
|
|
222
|
+
} else if (char === "}" && braces > 0) {
|
|
223
|
+
braces -= 1;
|
|
224
|
+
source += ")";
|
|
225
|
+
} else if (char === "," && braces > 0) source += "|";
|
|
226
|
+
else if (char === "[" || char === "]") throw new Error(`${id}: sideEffects pattern ${pattern} uses a character class, which the index does not support`);
|
|
227
|
+
else source += char.replace(/[.+^$()|\\]/g, "\\$&");
|
|
228
|
+
}
|
|
229
|
+
return new RegExp(`^${source}$`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Whether a package's `sideEffects` declaration lets a bundler skip the file at a package-relative path. */
|
|
233
|
+
export function sideEffectsRule(declaration: unknown, id: string): (path: string) => boolean {
|
|
234
|
+
if (declaration === false) return () => true;
|
|
235
|
+
if (declaration === undefined || declaration === true) return () => false;
|
|
236
|
+
if (Array.isArray(declaration) && declaration.every((item) => typeof item === "string")) {
|
|
237
|
+
const patterns = declaration.map((item: string) => sideEffectsPattern(item, id));
|
|
238
|
+
return (path) => !patterns.some((pattern) => pattern.test(path));
|
|
239
|
+
}
|
|
240
|
+
throw new Error(`${id} declares sideEffects as ${JSON.stringify(declaration)}, which is neither a boolean nor a list of globs`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export type LibraryBarrelOptions = {
|
|
244
|
+
files: Map<string, TracedFile>;
|
|
245
|
+
remapped: Set<string>;
|
|
246
|
+
/** A composed import map; the index never follows a hop into converted runtime files. */
|
|
247
|
+
map: ImportMap;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
export type LibraryBarrelIndex = BuiltBarrelIndex & {
|
|
251
|
+
/** Forwarding modules each package does not declare side-effect-free, by `name@version`. */
|
|
252
|
+
undeclared: Record<string, number>;
|
|
253
|
+
ms: number;
|
|
254
|
+
bytes: number;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/** Builds the barrel index the libraries would publish, over every ESM file of a library set. */
|
|
258
|
+
export function libraryBarrelIndex(options: LibraryBarrelOptions): LibraryBarrelIndex {
|
|
259
|
+
const started = performance.now();
|
|
260
|
+
const shapes = new Map<string, ModuleShape | null>();
|
|
261
|
+
const shape = (url: string): ModuleShape | null => {
|
|
262
|
+
if (shapes.has(url)) return shapes.get(url) ?? null;
|
|
263
|
+
const file = options.files.get(url);
|
|
264
|
+
const converted = url.includes("/dist/runtime/");
|
|
265
|
+
const value = file && file.kind === "esm" && !converted ? shapeOf(moduleFormat(file.path).module) : null;
|
|
266
|
+
shapes.set(url, value);
|
|
267
|
+
return value;
|
|
268
|
+
};
|
|
269
|
+
const known = (url: string) => options.files.has(url) || options.remapped.has(url);
|
|
270
|
+
const resolve = (url: string, specifier: string): string | null => {
|
|
271
|
+
const kind = specifierKind(specifier);
|
|
272
|
+
if (kind === "relative") {
|
|
273
|
+
const path = new URL(specifier, `https://runtime.invalid${NPM_PREFIX}${url}`).pathname;
|
|
274
|
+
if (!path.startsWith(NPM_PREFIX)) return null;
|
|
275
|
+
const resolved = path.slice(NPM_PREFIX.length);
|
|
276
|
+
return CANONICAL_CANDIDATES.map((suffix) => `${resolved}${suffix}`).find(known) ?? null;
|
|
277
|
+
}
|
|
278
|
+
if (kind !== "bare") return null;
|
|
279
|
+
const target = resolveSpecifier(options.map, specifier, `${NPM_PREFIX}${url}`);
|
|
280
|
+
return target?.startsWith(NPM_PREFIX) ? target.slice(NPM_PREFIX.length) : null;
|
|
281
|
+
};
|
|
282
|
+
const rules = new Map<string, (path: string) => boolean>();
|
|
283
|
+
const owner = (url: string) => {
|
|
284
|
+
const file = options.files.get(url);
|
|
285
|
+
if (!file) throw new Error(`${url} is not in the library set`);
|
|
286
|
+
return packageOf(file.path);
|
|
287
|
+
};
|
|
288
|
+
const sideEffectFree = (url: string): boolean => {
|
|
289
|
+
const pkg = owner(url);
|
|
290
|
+
let rule = rules.get(pkg.dir);
|
|
291
|
+
if (!rule) {
|
|
292
|
+
const manifest = JSON.parse(readFileSync(join(pkg.dir, "package.json"), "utf8")) as { sideEffects?: unknown };
|
|
293
|
+
rule = sideEffectsRule(manifest.sideEffects, `${pkg.name}@${pkg.version}`);
|
|
294
|
+
rules.set(pkg.dir, rule);
|
|
295
|
+
}
|
|
296
|
+
return rule(url.slice(`${pkg.name}@${pkg.version}/`.length));
|
|
297
|
+
};
|
|
298
|
+
const built = buildBarrelIndex({ urls: [...options.files.keys()].filter((url) => shape(url) !== null), shape, resolve, sideEffectFree });
|
|
299
|
+
const undeclared: Record<string, number> = {};
|
|
300
|
+
for (const url of built.blocked) {
|
|
301
|
+
const pkg = owner(url);
|
|
302
|
+
const id = `${pkg.name}@${pkg.version}`;
|
|
303
|
+
undeclared[id] = (undeclared[id] ?? 0) + 1;
|
|
304
|
+
}
|
|
305
|
+
return { ...built, undeclared, ms: Math.round(performance.now() - started), bytes: Buffer.byteLength(JSON.stringify(built.index)) };
|
|
306
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export const BASE_PACKAGES = ["react", "react-dom", "scheduler", "@tanstack/react-query", "jotai"];
|
|
2
|
+
export const BASE_ENTRIES = ["react", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom", "react-dom/client", "react-dom/server", "scheduler", "@tanstack/react-query", "jotai"];
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { BASE_PACKAGES } from "./base.ts";
|
|
4
|
+
import { convertCommonJs } from "./convert-commonjs.ts";
|
|
5
|
+
import { CommonJsConversionError, NodeBuiltinError } from "./errors.ts";
|
|
6
|
+
import { fragmentOf } from "./fragment.ts";
|
|
7
|
+
import { assertTrace } from "./library-runtime.ts";
|
|
8
|
+
import { type RuntimeExport } from "./runtime-layer.ts";
|
|
9
|
+
import { ClosureTracer, EMPTY_MODULE, packageName } from "./trace.ts";
|
|
10
|
+
|
|
11
|
+
export async function buildBrowserRuntimeExports(options: { root: string; entries: Record<string, RuntimeExport>; outDir: string; runtimeBase: string; inherited: string[] }) {
|
|
12
|
+
const { root, entries, outDir, runtimeBase, inherited } = options;
|
|
13
|
+
const inherits = [...new Set([...BASE_PACKAGES, ...inherited])];
|
|
14
|
+
const candidates = Object.entries(entries).map(([specifier, entry]) => ({ specifier, path: entry.browser }));
|
|
15
|
+
function trace(selected: typeof candidates) {
|
|
16
|
+
return new ClosureTracer({ name: "Facet template runtime", resolveFrom: root, runtimeBase, entries: selected, topLevel: [], inherits }).trace();
|
|
17
|
+
}
|
|
18
|
+
const verify = async (selected: typeof candidates) => {
|
|
19
|
+
const tracer = trace(selected);
|
|
20
|
+
assertTrace(tracer);
|
|
21
|
+
try { await convertCommonJs(tracer, outDir); }
|
|
22
|
+
catch (error) { assertTrace(tracer); throw error; }
|
|
23
|
+
assertTrace(tracer);
|
|
24
|
+
return tracer;
|
|
25
|
+
};
|
|
26
|
+
const selectBrowser = async (selected: typeof candidates): Promise<typeof candidates> => {
|
|
27
|
+
try { await verify(selected); return selected; }
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (!(error instanceof NodeBuiltinError) && !(error instanceof CommonJsConversionError)) throw error;
|
|
30
|
+
if (selected.length <= 1) return [];
|
|
31
|
+
const middle = Math.floor(selected.length / 2);
|
|
32
|
+
return [...await selectBrowser(selected.slice(0, middle)), ...await selectBrowser(selected.slice(middle))];
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
let tracer: ClosureTracer;
|
|
36
|
+
try { tracer = await verify(candidates); }
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (!(error instanceof NodeBuiltinError) && !(error instanceof CommonJsConversionError)) throw error;
|
|
39
|
+
const middle = Math.floor(candidates.length / 2);
|
|
40
|
+
const selected = candidates.length <= 1 ? [] : [...await selectBrowser(candidates.slice(0, middle)), ...await selectBrowser(candidates.slice(middle))];
|
|
41
|
+
tracer = await verify(selected);
|
|
42
|
+
}
|
|
43
|
+
const fragment = fragmentOf(tracer);
|
|
44
|
+
if (fragment.integrity[`${runtimeBase}empty.js`]) {
|
|
45
|
+
await mkdir(outDir, { recursive: true });
|
|
46
|
+
const path = join(outDir, "empty.js");
|
|
47
|
+
await writeFile(path, EMPTY_MODULE);
|
|
48
|
+
tracer.files.get(`${runtimeBase}empty.js`)!.path = path;
|
|
49
|
+
}
|
|
50
|
+
const versions = Object.fromEntries(Object.keys(fragment.imports).map(specifier => [packageName(specifier), entries[specifier]!.version]));
|
|
51
|
+
return { fragment, versions, packages: Object.fromEntries(tracer.packages), files: Object.fromEntries([...tracer.files].map(([url, file]) => [url, file.path])) };
|
|
52
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Fragment } from "../schema.ts";
|
|
4
|
+
import { composeImportMap, resolveSpecifier } from "./fragment.ts";
|
|
5
|
+
import { librarySpec } from "./library-runtime.ts";
|
|
6
|
+
import { specifierKind } from "./module-utils.ts";
|
|
7
|
+
import { traceRecipeDependencies } from "./recipe-dependencies.ts";
|
|
8
|
+
import { ClosureTracer, integrityOf, moduleFormat, packageName } from "./trace.ts";
|
|
9
|
+
|
|
10
|
+
export async function checkFragment(options: { libraryDir: string; base?: Fragment }): Promise<string[]> {
|
|
11
|
+
const fragment = JSON.parse(readFileSync(join(options.libraryDir, "dist/runtime/importmap.json"), "utf8")) as Fragment;
|
|
12
|
+
const spec = librarySpec(options);
|
|
13
|
+
spec.inherits = [...new Set(fragment.inherits.map(packageName))];
|
|
14
|
+
const tracer = new ClosureTracer(spec).trace();
|
|
15
|
+
await traceRecipeDependencies(tracer);
|
|
16
|
+
const failures = tracer.failures.map(({ name, detail }) => `${name}: ${detail}`);
|
|
17
|
+
const fragments = options.base ? [options.base, fragment] : [{ ...fragment, inherits: [] }];
|
|
18
|
+
const composed = composeImportMap(fragments, "/npm/");
|
|
19
|
+
failures.push(...composed.failures.map(({ detail }) => detail));
|
|
20
|
+
for (const file of tracer.files.values()) {
|
|
21
|
+
if (file.kind === "commonjs" && fragment.remaps[file.url]) continue;
|
|
22
|
+
if (fragment.integrity[file.url] !== file.integrity) failures.push(`${file.url}: missing or mismatched integrity`);
|
|
23
|
+
for (const specifier of file.bareImports) {
|
|
24
|
+
if (!resolveSpecifier(composed.map, specifier, `/npm/${file.url}`) && !fragment.inherits.includes(specifier)) failures.push(`${file.url}: unmapped import ${specifier}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
for (const entry of tracer.commonJs.values()) {
|
|
28
|
+
if (!Object.values(fragment.imports).includes(entry.url) && !Object.values(fragment.remaps).includes(entry.url) && !Object.values(fragment.scopes).some((table) => Object.values(table).includes(entry.url))) failures.push(`${entry.specifier}: unconverted CommonJS`);
|
|
29
|
+
}
|
|
30
|
+
const prefix = tracer.spec.runtimeBase;
|
|
31
|
+
if (!prefix) throw new Error(`${fragment.name}: missing runtime base`);
|
|
32
|
+
for (const [url, integrity] of Object.entries(fragment.integrity)) {
|
|
33
|
+
if (!url.startsWith(prefix)) continue;
|
|
34
|
+
const path = join(options.libraryDir, "dist/runtime", url.slice(prefix.length));
|
|
35
|
+
if (integrityOf(readFileSync(path)) !== integrity) failures.push(`${url}: integrity mismatch`);
|
|
36
|
+
const { module } = moduleFormat(path);
|
|
37
|
+
const map = composed.map;
|
|
38
|
+
for (const item of module.staticImports) {
|
|
39
|
+
const specifier = item.moduleRequest.value;
|
|
40
|
+
if (specifierKind(specifier) === "builtin" && !resolveSpecifier(map, specifier, `/npm/${url}`)) failures.push(`${url}: Node built-in ${specifier}`);
|
|
41
|
+
if (specifierKind(specifier) === "bare" && !resolveSpecifier(map, specifier, `/npm/${url}`) && !fragment.inherits.includes(specifier)) failures.push(`${url}: unmapped import ${specifier}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return failures;
|
|
45
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Reads a JSON array of CommonJS module paths on stdin and prints each module's export names (or the error
|
|
2
|
+
// loading it threw) under the NODE_ENV the parent set.
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
6
|
+
|
|
7
|
+
const paths = isMainThread ? JSON.parse(readFileSync(0, "utf8")) : workerData;
|
|
8
|
+
if (!Array.isArray(paths)) throw new Error("stdin must be a JSON array of module paths");
|
|
9
|
+
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
11
|
+
const result = {};
|
|
12
|
+
for (const path of paths) {
|
|
13
|
+
try {
|
|
14
|
+
const value = require(path);
|
|
15
|
+
const exportsObject = value !== null && (typeof value === "object" || typeof value === "function");
|
|
16
|
+
result[path] = { names: exportsObject ? Object.keys(value) : [] };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
result[path] = { error: String(error instanceof Error ? error.message : error).split("\n")[0] };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (isMainThread) process.stdout.write(JSON.stringify(result));
|
|
22
|
+
else parentPort.postMessage(result);
|
|
23
|
+
// Some modules start timers when loaded; the names are all that is needed.
|
|
24
|
+
process.exit(0);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
|
|
3
|
+
export type CommonJsExports = Record<string, { names?: string[]; error?: string }>;
|
|
4
|
+
|
|
5
|
+
export async function commonJsExportNames(paths: string[]): Promise<CommonJsExports> {
|
|
6
|
+
if (!paths.length) return {};
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const worker = new Worker(new URL("./cjs-export-names.mjs", import.meta.url), { workerData: paths, env: { ...process.env, NODE_ENV: "development" }, stdout: true, stderr: true });
|
|
9
|
+
worker.stdout.resume();
|
|
10
|
+
worker.stderr.resume();
|
|
11
|
+
const timeout = setTimeout(() => { reject(new Error("Timed out enumerating CommonJS runtime exports")); void worker.terminate(); }, 30_000);
|
|
12
|
+
let result: CommonJsExports | undefined;
|
|
13
|
+
worker.once("message", (message: CommonJsExports) => { result = message; });
|
|
14
|
+
worker.once("error", reject);
|
|
15
|
+
worker.once("exit", code => {
|
|
16
|
+
clearTimeout(timeout);
|
|
17
|
+
if (code !== 0 || !result) { reject(new Error(`CommonJS export worker exited with code ${code} before returning exports`)); return; }
|
|
18
|
+
for (const path of paths) {
|
|
19
|
+
if (!result[path]?.names || result[path]?.error) { reject(new Error(`Cannot enumerate CommonJS exports of ${path}: ${result[path]?.error}`)); return; }
|
|
20
|
+
}
|
|
21
|
+
resolve(result);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { dirname, extname, isAbsolute, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { rolldown, type OutputAsset, type OutputChunk, type Plugin, type PreRenderedChunk } from "rolldown";
|
|
5
|
+
import { CommonJsConversionError } from "./errors.ts";
|
|
6
|
+
import { specifierKind } from "./module-utils.ts";
|
|
7
|
+
import { type ClosureTracer, type CommonJsEntry, createResolver, integrityOf, moduleFormat, packageName, packageOf, REQUIRE_CONDITIONS, resolveBrowser } from "./trace.ts";
|
|
8
|
+
|
|
9
|
+
export type ConversionStats = { entries: number; chunks: number; bytes: number; ms: number };
|
|
10
|
+
|
|
11
|
+
type ExportNames = Record<string, { names?: string[]; error?: string }>;
|
|
12
|
+
|
|
13
|
+
const ENTRY = "\0runtime-entry:";
|
|
14
|
+
const REQUIRE_EXTERNAL = "\0runtime-require:";
|
|
15
|
+
const EMPTY = "\0runtime-empty";
|
|
16
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
17
|
+
const JS_EXTENSIONS = new Set([".js", ".mjs", ".cjs"]);
|
|
18
|
+
// rolldown turns a require it cannot resolve into a call to its __require shim, which throws in a browser.
|
|
19
|
+
const LEFTOVER_REQUIRE = /(?<![\w$.])__require\s*\(/;
|
|
20
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
21
|
+
|
|
22
|
+
function exportNames(entries: CommonJsEntry[]): ExportNames {
|
|
23
|
+
const output = execFileSync(process.execPath, [join(here, "cjs-export-names.mjs")], {
|
|
24
|
+
input: JSON.stringify(entries.map((entry) => entry.path)),
|
|
25
|
+
env: { ...process.env, NODE_ENV: "development" },
|
|
26
|
+
encoding: "utf8",
|
|
27
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
28
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
29
|
+
timeout: 30_000,
|
|
30
|
+
});
|
|
31
|
+
const result = JSON.parse(output) as ExportNames;
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
const item = result[entry.path];
|
|
34
|
+
if (!item?.names || item.error) throw new CommonJsConversionError(`${entry.pkg.name}: listing ${entry.specifier} exports threw: ${item?.error ?? "no export list returned"}`);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The ESM face of one CommonJS entry: its `module.exports` as the default export plus an explicit named-export list. */
|
|
40
|
+
function entrySource(entry: CommonJsEntry, names: string[]): string {
|
|
41
|
+
const exported = names.filter((name) => name !== "default" && name !== "__esModule");
|
|
42
|
+
const lines = [`import * as ns from ${JSON.stringify(entry.path)};`];
|
|
43
|
+
lines.push("export default ns.default;");
|
|
44
|
+
exported.forEach((name, index) => lines.push(`const __e${index} = ns[${JSON.stringify(name)}];`));
|
|
45
|
+
if (exported.length > 0) {
|
|
46
|
+
const specifiers = exported.map((name, index) => `__e${index} as ${IDENTIFIER.test(name) ? name : JSON.stringify(name)}`);
|
|
47
|
+
lines.push(`export { ${specifiers.join(", ")} };`);
|
|
48
|
+
}
|
|
49
|
+
return `${lines.join("\n")}\n`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Resolves cross-package `require`s through a CommonJS adapter that imports the shared ESM copy,
|
|
54
|
+
* preserving module.exports identity instead of converting an ESM namespace back to CommonJS.
|
|
55
|
+
*/
|
|
56
|
+
function runtimeSetPlugin(tracer: ClosureTracer, names: ExportNames): Plugin {
|
|
57
|
+
const { runtimeBase, inherits, topLevel } = tracer.spec;
|
|
58
|
+
if (!runtimeBase) throw new Error(`${tracer.spec.name} has no runtime set to convert CommonJS into`);
|
|
59
|
+
const requireResolver = createResolver(REQUIRE_CONDITIONS);
|
|
60
|
+
const external = (options: { source: string; kind: string; path?: string; owner?: string }) =>
|
|
61
|
+
options.kind === "require-call" ? `${REQUIRE_EXTERNAL}${JSON.stringify(options)}` : { id: options.source, external: true };
|
|
62
|
+
return {
|
|
63
|
+
name: "page-runtime-set",
|
|
64
|
+
resolveId(source, importer, { kind }) {
|
|
65
|
+
if (source === EMPTY || source.startsWith(ENTRY) || source.startsWith(REQUIRE_EXTERNAL)) return source;
|
|
66
|
+
if (!importer || importer.startsWith(ENTRY)) return null;
|
|
67
|
+
if (importer.startsWith(REQUIRE_EXTERNAL)) return { id: source, external: true };
|
|
68
|
+
const from = packageOf(importer);
|
|
69
|
+
const resolved = resolveBrowser({ resolver: kind === "require-call" ? requireResolver : tracer.resolver, fromDir: dirname(importer), specifier: source });
|
|
70
|
+
if (resolved.empty) return EMPTY;
|
|
71
|
+
if (resolved.builtin || (specifierKind(source) === "builtin" && !resolved.path)) {
|
|
72
|
+
tracer.fail(from.name, `CommonJS code in ${from.name}@${from.version} requires Node built-in ${resolved.builtin?.resolved ?? source}`);
|
|
73
|
+
return { id: source, external: true };
|
|
74
|
+
}
|
|
75
|
+
if (specifierKind(source) === "relative") return null;
|
|
76
|
+
const name = packageName(source);
|
|
77
|
+
if (inherits.includes(name)) {
|
|
78
|
+
tracer.inherit(source, runtimeBase);
|
|
79
|
+
return external({ source, kind, ...(resolved.path ? { path: resolved.path } : {}) });
|
|
80
|
+
}
|
|
81
|
+
if (topLevel.includes(name)) {
|
|
82
|
+
const url = tracer.provideTopLevel(source);
|
|
83
|
+
if (!url) throw new Error(`cannot resolve base-set entry ${source}`);
|
|
84
|
+
return external({ source, kind, ...(resolved.path ? { path: resolved.path } : {}) });
|
|
85
|
+
}
|
|
86
|
+
if (!resolved.path) {
|
|
87
|
+
tracer.fail(name, `CommonJS code in ${from.name}@${from.version} requires ${source}, which does not resolve (${resolved.error})`);
|
|
88
|
+
return { id: source, external: true };
|
|
89
|
+
}
|
|
90
|
+
if (!JS_EXTENSIONS.has(extname(resolved.path))) return resolved.path;
|
|
91
|
+
const url = tracer.target(resolved.path, source, "bare");
|
|
92
|
+
const owner = `${from.name}@${from.version}`;
|
|
93
|
+
if (url) tracer.mapInScope(`${runtimeBase}${owner}/`, source, url);
|
|
94
|
+
return external({ source, kind, path: resolved.path, owner });
|
|
95
|
+
},
|
|
96
|
+
load(id) {
|
|
97
|
+
if (id === EMPTY) return "module.exports = {};";
|
|
98
|
+
if (id.startsWith(ENTRY)) {
|
|
99
|
+
const entry = tracer.commonJs.get(id.slice(ENTRY.length));
|
|
100
|
+
if (!entry) throw new Error(`unknown runtime-set entry ${id}`);
|
|
101
|
+
const exported = names[entry.path]?.names;
|
|
102
|
+
if (!exported) throw new CommonJsConversionError(`${entry.specifier}: missing explicit export list`);
|
|
103
|
+
return entrySource(entry, exported);
|
|
104
|
+
}
|
|
105
|
+
if (id.startsWith(REQUIRE_EXTERNAL)) {
|
|
106
|
+
const { source, path } = JSON.parse(id.slice(REQUIRE_EXTERNAL.length)) as { source: string; path?: string };
|
|
107
|
+
const specifier = JSON.stringify(source);
|
|
108
|
+
const value = path && moduleFormat(path).format === "commonjs" ? "ns.default" : "ns";
|
|
109
|
+
return `import * as ns from ${specifier};\nmodule.exports = ${value};\n`;
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function chunkFileName(chunk: PreRenderedChunk): string {
|
|
117
|
+
const owners = new Set<string>();
|
|
118
|
+
for (const id of chunk.moduleIds) {
|
|
119
|
+
if (id.startsWith(REQUIRE_EXTERNAL)) {
|
|
120
|
+
const { owner } = JSON.parse(id.slice(REQUIRE_EXTERNAL.length)) as { owner?: string };
|
|
121
|
+
if (owner) owners.add(owner);
|
|
122
|
+
} else if (isAbsolute(id) && JS_EXTENSIONS.has(extname(id))) {
|
|
123
|
+
const pkg = packageOf(id);
|
|
124
|
+
owners.add(`${pkg.name}@${pkg.version}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (owners.size > 1) throw new CommonJsConversionError(`shared chunk ${chunk.name} combines dependency scopes ${[...owners].join(", ")}`);
|
|
128
|
+
const [owner] = owners;
|
|
129
|
+
return `${owner ? `${owner}/` : ""}_chunks/[name]-[hash].js`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function build(tracer: ClosureTracer, names: ExportNames, outDir: string | null) {
|
|
133
|
+
const entries = [...tracer.commonJs.values()];
|
|
134
|
+
const bundle = await rolldown({
|
|
135
|
+
input: Object.fromEntries(entries.map((entry) => [entry.name, `${ENTRY}${entry.name}`])),
|
|
136
|
+
plugins: [runtimeSetPlugin(tracer, names)],
|
|
137
|
+
platform: "browser",
|
|
138
|
+
transform: { define: { "process.env.NODE_ENV": JSON.stringify("development") } },
|
|
139
|
+
logLevel: "silent",
|
|
140
|
+
});
|
|
141
|
+
const options = { format: "esm", entryFileNames: "[name].js", chunkFileNames: chunkFileName } as const;
|
|
142
|
+
try {
|
|
143
|
+
return (outDir ? await bundle.write({ ...options, dir: outDir }) : await bundle.generate(options)).output;
|
|
144
|
+
} finally {
|
|
145
|
+
await bundle.close();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function register(tracer: ClosureTracer, outDir: string, output: Array<OutputChunk | OutputAsset>): number {
|
|
150
|
+
const fileNames = new Set(output.map((item) => item.fileName));
|
|
151
|
+
let bytes = 0;
|
|
152
|
+
for (const item of output) {
|
|
153
|
+
if (item.type !== "chunk") throw new Error(`converting CommonJS emitted an asset: ${item.fileName}`);
|
|
154
|
+
const url = `${tracer.spec.runtimeBase}${item.fileName}`;
|
|
155
|
+
const leftover = item.code.split("\n").find((line) => LEFTOVER_REQUIRE.test(line));
|
|
156
|
+
if (leftover) {
|
|
157
|
+
const owners = [...new Set(item.moduleIds.filter((id) => !id.startsWith("\0")).map((id) => packageOf(id).name))];
|
|
158
|
+
tracer.fail(owners.join(", "), `${url} still calls require through rolldown's shim: ${leftover.trim().slice(0, 160)}`);
|
|
159
|
+
}
|
|
160
|
+
const bareImports = [...item.imports, ...item.dynamicImports].filter((id) => !fileNames.has(id));
|
|
161
|
+
tracer.files.set(url, { url, path: join(outDir, item.fileName), kind: "esm", integrity: integrityOf(item.code), bareImports });
|
|
162
|
+
bytes += Buffer.byteLength(item.code);
|
|
163
|
+
}
|
|
164
|
+
return bytes;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Converts every CommonJS-only entry the tracer found into the development runtime set. Converting
|
|
169
|
+
* can reach ESM packages, whose imports can reach more CommonJS entries, so discovery repeats until it is stable.
|
|
170
|
+
*/
|
|
171
|
+
export async function convertCommonJs(tracer: ClosureTracer, outDir: string): Promise<ConversionStats[]> {
|
|
172
|
+
if (tracer.commonJs.size === 0) return [];
|
|
173
|
+
for (let known = -1; known !== tracer.commonJs.size; ) {
|
|
174
|
+
known = tracer.commonJs.size;
|
|
175
|
+
await build(tracer, exportNames([...tracer.commonJs.values()]), null);
|
|
176
|
+
tracer.drain();
|
|
177
|
+
}
|
|
178
|
+
const started = performance.now();
|
|
179
|
+
const entries = [...tracer.commonJs.values()];
|
|
180
|
+
const output = await build(tracer, exportNames(entries), outDir);
|
|
181
|
+
const bytes = register(tracer, outDir, output);
|
|
182
|
+
return [{ entries: entries.length, chunks: output.length, bytes, ms: Math.round(performance.now() - started) }];
|
|
183
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { buildDependencyRuntime, buildInstalledDependencyRuntime, type DependencyRuntime, type DependencyRuntimeOptions } from "./dependency-runtime.ts";
|
|
2
|
+
export { ensureDependencyRuntime, type CachedDependencyRuntime } from "./dependency-cache.ts";
|
|
3
|
+
export { dependencyRuntimePlugin } from "./dependency-plugin.ts";
|
|
4
|
+
export { runtimeEntries } from "./runtime-entries.ts";
|
|
5
|
+
export { discoverRuntimeExports, runtimeExportPins, type RuntimeExport } from "./runtime-layer.ts";
|
|
6
|
+
export { buildBrowserRuntimeExports } from "./browser-runtime-exports.ts";
|