@statewalker/cellb 0.8.8 → 0.9.1
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/README.md +11 -7
- package/dist/adapters/node-sqlite-module.d.ts +6 -0
- package/dist/adapters/node-sqlite-module.js +12 -0
- package/dist/adapters/node-sqlite-module.js.map +1 -1
- package/dist/adapters/node-sqlite.js +3 -3
- package/dist/adapters/node-sqlite.js.map +1 -1
- package/dist/adapters/wasm-sqlite.d.ts +2 -0
- package/dist/adapters/wasm-sqlite.js +15 -0
- package/dist/adapters/wasm-sqlite.js.map +1 -1
- package/dist/bindings/cjs-module.d.ts +7 -0
- package/dist/bindings/cjs-module.js +96 -0
- package/dist/bindings/cjs-module.js.map +1 -0
- package/dist/bindings/cron.js +9 -2
- package/dist/bindings/cron.js.map +1 -1
- package/dist/bindings/module-registry.d.ts +43 -0
- package/dist/bindings/module-registry.js +192 -0
- package/dist/bindings/module-registry.js.map +1 -0
- package/dist/bindings/worker-loader.d.ts +23 -5
- package/dist/bindings/worker-loader.js +75 -4
- package/dist/bindings/worker-loader.js.map +1 -1
- package/dist/bucket/sqlite-object-store.js +2 -2
- package/dist/bucket/sqlite-object-store.js.map +1 -1
- package/dist/core/alarms.js +12 -2
- package/dist/core/alarms.js.map +1 -1
- package/dist/core/handles.d.ts +21 -1
- package/dist/core/handles.js +49 -3
- package/dist/core/handles.js.map +1 -1
- package/dist/core/namespace.js +4 -1
- package/dist/core/namespace.js.map +1 -1
- package/dist/core/runtime.d.ts +8 -0
- package/dist/core/runtime.js +3 -3
- package/dist/core/runtime.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/isolate/browser.d.ts +1 -1
- package/dist/isolate/browser.js +3 -1
- package/dist/isolate/browser.js.map +1 -1
- package/dist/isolate/function-imports.d.ts +10 -0
- package/dist/isolate/function-imports.js +93 -0
- package/dist/isolate/function-imports.js.map +1 -0
- package/dist/isolate/host.js +20 -2
- package/dist/isolate/host.js.map +1 -1
- package/dist/isolate/isolate-worker.js +18 -2
- package/dist/isolate/isolate-worker.js.map +1 -1
- package/dist/isolate/isolate.js +11 -0
- package/dist/isolate/isolate.js.map +1 -1
- package/dist/isolate/node-entry.js +33 -0
- package/dist/isolate/node-entry.js.map +1 -1
- package/dist/isolate/protocol.d.ts +1 -0
- package/dist/isolate/protocol.js +242 -13
- package/dist/isolate/protocol.js.map +1 -1
- package/dist/isolate/writable-globals.d.ts +9 -0
- package/dist/isolate/writable-globals.js +45 -0
- package/dist/isolate/writable-globals.js.map +1 -0
- package/dist/node-compat/bundle-files.d.ts +26 -0
- package/dist/node-compat/bundle-files.js +210 -0
- package/dist/node-compat/bundle-files.js.map +1 -0
- package/dist/node-compat/fs.d.ts +13 -1
- package/dist/node-compat/fs.js +54 -15
- package/dist/node-compat/fs.js.map +1 -1
- package/dist/project/browser-host.d.ts +2 -0
- package/dist/project/browser-host.js +2 -0
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/browser-load.js +1 -0
- package/dist/project/browser-load.js.map +1 -1
- package/dist/project/browser-modules.d.ts +8 -2
- package/dist/project/browser-modules.js +30 -6
- package/dist/project/browser-modules.js.map +1 -1
- package/dist/project/built-project.d.ts +7 -0
- package/dist/project/built-project.js.map +1 -1
- package/dist/project/cloudflare-workers.d.ts +9 -0
- package/dist/project/cloudflare-workers.js +14 -0
- package/dist/project/cloudflare-workers.js.map +1 -1
- package/dist/project/module-rules.js +31 -10
- package/dist/project/module-rules.js.map +1 -1
- package/dist/project/node-project.d.ts +2 -0
- package/dist/project/node-project.js +157 -25
- package/dist/project/node-project.js.map +1 -1
- package/dist/project/site-loader.js +2 -1
- package/dist/project/site-loader.js.map +1 -1
- package/dist/project/uint8array-base64.d.ts +7 -0
- package/dist/project/uint8array-base64.js +96 -0
- package/dist/project/uint8array-base64.js.map +1 -0
- package/dist/project/workers-globals-module.d.ts +1 -0
- package/dist/project/workers-globals-module.js +3 -0
- package/dist/project/workers-globals-module.js.map +1 -1
- package/dist/project/wrangler.js +8 -9
- package/dist/project/wrangler.js.map +1 -1
- package/dist/ws/upgrade.js +18 -1
- package/dist/ws/upgrade.js.map +1 -1
- package/package.json +10 -10
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
* as base64 (about 1.33 times their size), so a bundle stays one self-contained module (a browser
|
|
6
6
|
* loads it by URL).
|
|
7
7
|
*/
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
8
9
|
import { readFileSync } from "node:fs";
|
|
10
|
+
import { basename } from "node:path";
|
|
9
11
|
/** wrangler's (and workerd's) defaults, applied after a project's own rules. */
|
|
10
12
|
export const DEFAULT_MODULE_RULES = [
|
|
11
13
|
{ type: "Text", globs: ["**/*.txt", "**/*.html", "**/*.sql"] },
|
|
@@ -60,26 +62,45 @@ export function effectiveRules(userRules = []) {
|
|
|
60
62
|
}
|
|
61
63
|
return { rules, ignored };
|
|
62
64
|
}
|
|
63
|
-
// Shared by every inlined file: base64 → bytes (Uint8Array.fromBase64 where the engine has it)
|
|
64
|
-
|
|
65
|
+
// Shared by every inlined file: base64 → bytes (Uint8Array.fromBase64 where the engine has it),
|
|
66
|
+
// and the registration of the file under workerd's `/bundle` (node-compat/bundle-files.ts reads
|
|
67
|
+
// the same registry).
|
|
68
|
+
const DECODE = `export const bundleFile = (name, b) => {
|
|
69
|
+
(globalThis.__cellsBundleFiles ??= new Map()).set(name, b);
|
|
70
|
+
return b;
|
|
71
|
+
};
|
|
72
|
+
export const bytes = (s) => {
|
|
65
73
|
if (typeof Uint8Array.fromBase64 === "function") return Uint8Array.fromBase64(s);
|
|
66
74
|
const t = atob(s);
|
|
67
75
|
const u = new Uint8Array(t.length);
|
|
68
76
|
for (let i = 0; i < t.length; i++) u[i] = t.charCodeAt(i);
|
|
69
77
|
return u;
|
|
70
78
|
};`;
|
|
71
|
-
/**
|
|
72
|
-
|
|
79
|
+
/**
|
|
80
|
+
* The module a matched file becomes. It also registers the file as workerd's `/bundle/<name>`,
|
|
81
|
+
* named as wrangler uploads it: `<sha1 of its bytes>-<file name>`.
|
|
82
|
+
*/
|
|
83
|
+
function ruleModule(type, file, path) {
|
|
84
|
+
const name = JSON.stringify(`${createHash("sha1").update(file).digest("hex")}-${basename(path)}`);
|
|
73
85
|
// A BOM stays part of the text, as wrangler uploads the file's bytes.
|
|
74
86
|
if (type === "Text")
|
|
75
|
-
return
|
|
87
|
+
return [
|
|
88
|
+
'import { bundleFile } from "cellb-rule:decode";',
|
|
89
|
+
`const text = ${JSON.stringify(new TextDecoder("utf-8", { ignoreBOM: true }).decode(file))};`,
|
|
90
|
+
`bundleFile(${name}, () => new TextEncoder().encode(text));`,
|
|
91
|
+
"export default text;",
|
|
92
|
+
].join("\n");
|
|
76
93
|
const b64 = JSON.stringify(file.toString("base64"));
|
|
77
94
|
return [
|
|
78
|
-
'import { bytes } from "cellb-rule:decode";',
|
|
95
|
+
'import { bundleFile, bytes } from "cellb-rule:decode";',
|
|
79
96
|
type === "CompiledWasm"
|
|
80
|
-
? //
|
|
81
|
-
|
|
82
|
-
|
|
97
|
+
? // Synchronous, as workerd imports a wasm module. A top-level await here would make every
|
|
98
|
+
// importer async, and esbuild's async module inits deadlock on circular imports (the
|
|
99
|
+
// bundle never finishes evaluating). Chromium refuses a synchronous compile over 8 MB
|
|
100
|
+
// only on a page's main thread; projects run in Dedicated Workers and on Node.
|
|
101
|
+
`export default new WebAssembly.Module(bundleFile(${name}, bytes(${b64})));`
|
|
102
|
+
: // `/bundle` keeps its own copy: Worker code may change or transfer the exported buffer.
|
|
103
|
+
`const data = bytes(${b64}); bundleFile(${name}, data.slice()); export default data.buffer;`,
|
|
83
104
|
].join("\n");
|
|
84
105
|
}
|
|
85
106
|
/** The esbuild plugin applying `rules` (with the defaults) to a bundle's imports. */
|
|
@@ -122,7 +143,7 @@ export function moduleRulesPlugin(userRules) {
|
|
|
122
143
|
}));
|
|
123
144
|
for (const type of TYPES)
|
|
124
145
|
b.onLoad({ filter: /.*/, namespace: `cellb-rule-${type}` }, (a) => ({
|
|
125
|
-
contents: ruleModule(type, readFileSync(a.path)),
|
|
146
|
+
contents: ruleModule(type, readFileSync(a.path), a.path),
|
|
126
147
|
loader: "js",
|
|
127
148
|
}));
|
|
128
149
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-rules.js","sourceRoot":"","sources":["../../src/project/module-rules.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAWvC,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAiB;IAChD,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE;IAC9D,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,UAAU,CAAC,EAAE;IACrC,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,WAAW,EAAE,kBAAkB,CAAC,EAAE;CACnE,CAAC;AAEF,0FAA0F;AAC1F,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC;YAC9B,EAAE,IAAI,aAAa,CAAC;YACpB,CAAC,IAAI,CAAC,CAAC;QACT,CAAC;aAAM,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,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AQ,EAAE,UAAU,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;oBAChD,MAAM,EAAE,IAAI;iBACb,CAAC,CAAC,CAAC;QACR,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * wrangler's module `rules` for the esbuild bundles of a project's `main` (Node and `cellb build`):\n * `CompiledWasm` (default export a `WebAssembly.Module`), `Data` (an `ArrayBuffer`) and `Text` (a\n * string), matched on the import specifier by `globs`, as wrangler bundles. The bytes are inlined\n * as base64 (about 1.33 times their size), so a bundle stays one self-contained module (a browser\n * loads it by URL).\n */\nimport { readFileSync } from \"node:fs\";\nimport type { Plugin } from \"esbuild\";\n\n/** A wrangler `rules` entry. */\nexport interface ModuleRule {\n type: \"ESModule\" | \"CommonJS\" | \"CompiledWasm\" | \"Data\" | \"Text\" | (string & {});\n globs: string[];\n /** `true`: later rules of the same type (the defaults among them) apply too. */\n fallthrough?: boolean;\n}\n\n/** wrangler's (and workerd's) defaults, applied after a project's own rules. */\nexport const DEFAULT_MODULE_RULES: ModuleRule[] = [\n { type: \"Text\", globs: [\"**/*.txt\", \"**/*.html\", \"**/*.sql\"] },\n { type: \"Data\", globs: [\"**/*.bin\"] },\n { type: \"CompiledWasm\", globs: [\"**/*.wasm\", \"**/*.wasm?module\"] },\n];\n\n/** The rule types the bundles apply; ESModule and CommonJS are esbuild's own business. */\nconst TYPES = new Set([\"CompiledWasm\", \"Data\", \"Text\"]);\n\n/**\n * A glob as an esbuild filter (Go regexp) on the import specifier, as wrangler matches it\n * (glob-to-regexp with globstar): `**` spans any folders, `*` stays within one, the rest is literal.\n */\nexport function globFilter(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (glob.startsWith(\"**/\", i)) {\n re += \"(?:[^/]*/)*\";\n i += 2;\n } else if (glob.startsWith(\"**\", i)) {\n re += \".*\";\n i++;\n } else if (c === \"*\") re += \"[^/]*\";\n else re += c.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * The rules in effect, as wrangler's `parseRules`: the project's, then the defaults. The first rule\n * of a type without `fallthrough: true` closes the type: later rules of it are dropped (`ignored`\n * names the project's own, unless the closing rule says `fallthrough: false`).\n */\nexport function effectiveRules(userRules: ModuleRule[] = []): {\n rules: ModuleRule[];\n ignored: string[];\n} {\n const all = [...userRules, ...DEFAULT_MODULE_RULES];\n const closedAt = new Map<string, number>();\n const rules: ModuleRule[] = [];\n const ignored: string[] = [];\n for (const [i, rule] of all.entries()) {\n const at = closedAt.get(rule.type);\n if (at !== undefined) {\n if (i < userRules.length && all[at].fallthrough !== false)\n ignored.push(\n `rules[${i}] (${rule.type}) is ignored: rules[${at}] has the same type and no \\`fallthrough = true\\``,\n );\n continue;\n }\n if (rule.fallthrough !== true) closedAt.set(rule.type, i);\n rules.push(rule);\n }\n return { rules, ignored };\n}\n\n// Shared by every inlined file: base64 → bytes (Uint8Array.fromBase64 where the engine has it).\nconst DECODE = `export const bytes = (s) => {\n if (typeof Uint8Array.fromBase64 === \"function\") return Uint8Array.fromBase64(s);\n const t = atob(s);\n const u = new Uint8Array(t.length);\n for (let i = 0; i < t.length; i++) u[i] = t.charCodeAt(i);\n return u;\n};`;\n\n/** The module a matched file becomes. */\nfunction ruleModule(type: string, file: Buffer): string {\n // A BOM stays part of the text, as wrangler uploads the file's bytes.\n if (type === \"Text\")\n return `export default ${JSON.stringify(new TextDecoder(\"utf-8\", { ignoreBOM: true }).decode(file))};`;\n const b64 = JSON.stringify(file.toString(\"base64\"));\n return [\n 'import { bytes } from \"cellb-rule:decode\";',\n type === \"CompiledWasm\"\n ? // asynchronous: no engine limit on the size of a synchronous compile (Chromium's main thread)\n `export default await WebAssembly.compile(bytes(${b64}));`\n : `export default bytes(${b64}).buffer;`,\n ].join(\"\\n\");\n}\n\n/** The esbuild plugin applying `rules` (with the defaults) to a bundle's imports. */\nexport function moduleRulesPlugin(userRules?: ModuleRule[]): Plugin {\n return {\n name: \"cellb-module-rules\",\n setup(b) {\n const { rules, ignored } = effectiveRules(userRules);\n for (const message of ignored) console.warn(`[cellb] ${message}`);\n for (const rule of rules) {\n if (!TYPES.has(rule.type)) continue;\n for (const glob of rule.globs)\n b.onResolve({ filter: globFilter(glob) }, async (a) => {\n // files on disk only: in-memory modules (Worker Loader code) bring `{ wasm }` entries\n if (a.namespace !== \"file\" || a.pluginData?.cellbModuleRule) return undefined;\n // esbuild resolves the file (relative, or a package's through `exports`); the rule loads it\n const r = await b.resolve(a.path.replace(/\\?module$/, \"\"), {\n kind: a.kind,\n importer: a.importer,\n resolveDir: a.resolveDir,\n pluginData: { cellbModuleRule: true },\n });\n if (r.errors.length) return { errors: r.errors };\n // The type is part of the module's identity: one file reached by rules of two types\n // is two modules.\n return { path: r.path, namespace: `cellb-rule-${rule.type}` };\n });\n }\n b.onResolve({ filter: /^cellb-rule:decode$/ }, () => ({\n path: \"decode\",\n namespace: \"cellb-rule-decode\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cellb-rule-decode\" }, () => ({\n contents: DECODE,\n loader: \"js\",\n }));\n for (const type of TYPES)\n b.onLoad({ filter: /.*/, namespace: `cellb-rule-${type}` }, (a) => ({\n contents: ruleModule(type, readFileSync(a.path)),\n loader: \"js\",\n }));\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"module-rules.js","sourceRoot":"","sources":["../../src/project/module-rules.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAWrC,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAiB;IAChD,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC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,EAAE,CAAC,CAAC,IAAI,CAAC;oBACxD,MAAM,EAAE,IAAI;iBACb,CAAC,CAAC,CAAC;QACR,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * wrangler's module `rules` for the esbuild bundles of a project's `main` (Node and `cellb build`):\n * `CompiledWasm` (default export a `WebAssembly.Module`), `Data` (an `ArrayBuffer`) and `Text` (a\n * string), matched on the import specifier by `globs`, as wrangler bundles. The bytes are inlined\n * as base64 (about 1.33 times their size), so a bundle stays one self-contained module (a browser\n * loads it by URL).\n */\nimport { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport type { Plugin } from \"esbuild\";\n\n/** A wrangler `rules` entry. */\nexport interface ModuleRule {\n type: \"ESModule\" | \"CommonJS\" | \"CompiledWasm\" | \"Data\" | \"Text\" | (string & {});\n globs: string[];\n /** `true`: later rules of the same type (the defaults among them) apply too. */\n fallthrough?: boolean;\n}\n\n/** wrangler's (and workerd's) defaults, applied after a project's own rules. */\nexport const DEFAULT_MODULE_RULES: ModuleRule[] = [\n { type: \"Text\", globs: [\"**/*.txt\", \"**/*.html\", \"**/*.sql\"] },\n { type: \"Data\", globs: [\"**/*.bin\"] },\n { type: \"CompiledWasm\", globs: [\"**/*.wasm\", \"**/*.wasm?module\"] },\n];\n\n/** The rule types the bundles apply; ESModule and CommonJS are esbuild's own business. */\nconst TYPES = new Set([\"CompiledWasm\", \"Data\", \"Text\"]);\n\n/**\n * A glob as an esbuild filter (Go regexp) on the import specifier, as wrangler matches it\n * (glob-to-regexp with globstar): `**` spans any folders, `*` stays within one, the rest is literal.\n */\nexport function globFilter(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (glob.startsWith(\"**/\", i)) {\n re += \"(?:[^/]*/)*\";\n i += 2;\n } else if (glob.startsWith(\"**\", i)) {\n re += \".*\";\n i++;\n } else if (c === \"*\") re += \"[^/]*\";\n else re += c.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * The rules in effect, as wrangler's `parseRules`: the project's, then the defaults. The first rule\n * of a type without `fallthrough: true` closes the type: later rules of it are dropped (`ignored`\n * names the project's own, unless the closing rule says `fallthrough: false`).\n */\nexport function effectiveRules(userRules: ModuleRule[] = []): {\n rules: ModuleRule[];\n ignored: string[];\n} {\n const all = [...userRules, ...DEFAULT_MODULE_RULES];\n const closedAt = new Map<string, number>();\n const rules: ModuleRule[] = [];\n const ignored: string[] = [];\n for (const [i, rule] of all.entries()) {\n const at = closedAt.get(rule.type);\n if (at !== undefined) {\n if (i < userRules.length && all[at].fallthrough !== false)\n ignored.push(\n `rules[${i}] (${rule.type}) is ignored: rules[${at}] has the same type and no \\`fallthrough = true\\``,\n );\n continue;\n }\n if (rule.fallthrough !== true) closedAt.set(rule.type, i);\n rules.push(rule);\n }\n return { rules, ignored };\n}\n\n// Shared by every inlined file: base64 → bytes (Uint8Array.fromBase64 where the engine has it),\n// and the registration of the file under workerd's `/bundle` (node-compat/bundle-files.ts reads\n// the same registry).\nconst DECODE = `export const bundleFile = (name, b) => {\n (globalThis.__cellsBundleFiles ??= new Map()).set(name, b);\n return b;\n};\nexport const bytes = (s) => {\n if (typeof Uint8Array.fromBase64 === \"function\") return Uint8Array.fromBase64(s);\n const t = atob(s);\n const u = new Uint8Array(t.length);\n for (let i = 0; i < t.length; i++) u[i] = t.charCodeAt(i);\n return u;\n};`;\n\n/**\n * The module a matched file becomes. It also registers the file as workerd's `/bundle/<name>`,\n * named as wrangler uploads it: `<sha1 of its bytes>-<file name>`.\n */\nfunction ruleModule(type: string, file: Buffer, path: string): string {\n const name = JSON.stringify(`${createHash(\"sha1\").update(file).digest(\"hex\")}-${basename(path)}`);\n // A BOM stays part of the text, as wrangler uploads the file's bytes.\n if (type === \"Text\")\n return [\n 'import { bundleFile } from \"cellb-rule:decode\";',\n `const text = ${JSON.stringify(new TextDecoder(\"utf-8\", { ignoreBOM: true }).decode(file))};`,\n `bundleFile(${name}, () => new TextEncoder().encode(text));`,\n \"export default text;\",\n ].join(\"\\n\");\n const b64 = JSON.stringify(file.toString(\"base64\"));\n return [\n 'import { bundleFile, bytes } from \"cellb-rule:decode\";',\n type === \"CompiledWasm\"\n ? // Synchronous, as workerd imports a wasm module. A top-level await here would make every\n // importer async, and esbuild's async module inits deadlock on circular imports (the\n // bundle never finishes evaluating). Chromium refuses a synchronous compile over 8 MB\n // only on a page's main thread; projects run in Dedicated Workers and on Node.\n `export default new WebAssembly.Module(bundleFile(${name}, bytes(${b64})));`\n : // `/bundle` keeps its own copy: Worker code may change or transfer the exported buffer.\n `const data = bytes(${b64}); bundleFile(${name}, data.slice()); export default data.buffer;`,\n ].join(\"\\n\");\n}\n\n/** The esbuild plugin applying `rules` (with the defaults) to a bundle's imports. */\nexport function moduleRulesPlugin(userRules?: ModuleRule[]): Plugin {\n return {\n name: \"cellb-module-rules\",\n setup(b) {\n const { rules, ignored } = effectiveRules(userRules);\n for (const message of ignored) console.warn(`[cellb] ${message}`);\n for (const rule of rules) {\n if (!TYPES.has(rule.type)) continue;\n for (const glob of rule.globs)\n b.onResolve({ filter: globFilter(glob) }, async (a) => {\n // files on disk only: in-memory modules (Worker Loader code) bring `{ wasm }` entries\n if (a.namespace !== \"file\" || a.pluginData?.cellbModuleRule) return undefined;\n // esbuild resolves the file (relative, or a package's through `exports`); the rule loads it\n const r = await b.resolve(a.path.replace(/\\?module$/, \"\"), {\n kind: a.kind,\n importer: a.importer,\n resolveDir: a.resolveDir,\n pluginData: { cellbModuleRule: true },\n });\n if (r.errors.length) return { errors: r.errors };\n // The type is part of the module's identity: one file reached by rules of two types\n // is two modules.\n return { path: r.path, namespace: `cellb-rule-${rule.type}` };\n });\n }\n b.onResolve({ filter: /^cellb-rule:decode$/ }, () => ({\n path: \"decode\",\n namespace: \"cellb-rule-decode\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cellb-rule-decode\" }, () => ({\n contents: DECODE,\n loader: \"js\",\n }));\n for (const type of TYPES)\n b.onLoad({ filter: /.*/, namespace: `cellb-rule-${type}` }, (a) => ({\n contents: ruleModule(type, readFileSync(a.path), a.path),\n loader: \"js\",\n }));\n },\n };\n}\n"]}
|
|
@@ -17,6 +17,8 @@ export declare function bundleWorker(entry: {
|
|
|
17
17
|
} | {
|
|
18
18
|
modules: Record<string, string>;
|
|
19
19
|
main: string;
|
|
20
|
+
/** The `cellb:modules` registry the modules import (loadedModuleTexts). */
|
|
21
|
+
registry?: string;
|
|
20
22
|
}, logs?: LogSink, outbound?: typeof fetch, opts?: {
|
|
21
23
|
nodeCompat?: boolean;
|
|
22
24
|
standardBinaryType?: boolean;
|
|
@@ -5,7 +5,8 @@ import { join, resolve } from "node:path";
|
|
|
5
5
|
import { Worker as NodeWorker } from "node:worker_threads";
|
|
6
6
|
import { build } from "esbuild";
|
|
7
7
|
import { applyD1Migrations } from "../bindings/d1-migrations.js";
|
|
8
|
-
import {
|
|
8
|
+
import { analyzeModule, exportNamesByModule, IMPORT_FROM, prefixModule, RESOLVE_MODULE_NAME_SOURCE, } from "../bindings/module-registry.js";
|
|
9
|
+
import { compileWasmModules, moduleText, outboundFetch, wasmModulesOf, } from "../bindings/worker-loader.js";
|
|
9
10
|
import { ctxExports } from "../core/handles.js";
|
|
10
11
|
import { isolatedModuleLoader } from "../isolate/host.js";
|
|
11
12
|
import * as workersClasses from "./cloudflare-workers.js";
|
|
@@ -28,6 +29,75 @@ const nodeBuiltinName = new RegExp(`^(${builtinModules
|
|
|
28
29
|
.filter((m) => !m.startsWith("_") && !m.includes(":"))
|
|
29
30
|
.map((m) => m.replace(/[/]/g, "\\/"))
|
|
30
31
|
.join("|")})$`);
|
|
32
|
+
/** Worker code's `node:fs` under nodejs_compat on Node: Node's own, with workerd's `/bundle`. */
|
|
33
|
+
const FS_OVERLAY = `import * as real from "node:fs";
|
|
34
|
+
import { bundleFs } from "cellb:bundle-fs";
|
|
35
|
+
export * from "node:fs";
|
|
36
|
+
const o = bundleFs(real);
|
|
37
|
+
export const { existsSync, readFileSync, statSync, lstatSync, readdirSync, accessSync, readFile, stat, lstat, readdir, access, promises } = o;
|
|
38
|
+
export default { ...real, ...o };`;
|
|
39
|
+
/** Worker code's `node:fs/promises`, the same way. */
|
|
40
|
+
const FS_PROMISES_OVERLAY = `import * as real from "node:fs/promises";
|
|
41
|
+
import { bundleFsPromises } from "cellb:bundle-fs";
|
|
42
|
+
export * from "node:fs/promises";
|
|
43
|
+
const o = bundleFsPromises(real);
|
|
44
|
+
export const { readFile, stat, lstat, readdir, access } = o;
|
|
45
|
+
export default o;`;
|
|
46
|
+
/**
|
|
47
|
+
* The modules of loaded code as ES module text, each `import()` the bundler cannot link going to
|
|
48
|
+
* the `cellb:modules` registry instead (module-registry.ts).
|
|
49
|
+
*/
|
|
50
|
+
function loadedModuleTexts(code) {
|
|
51
|
+
const texts = {};
|
|
52
|
+
const names = new Set(Object.keys(code.modules));
|
|
53
|
+
for (const [name, m] of Object.entries(code.modules))
|
|
54
|
+
texts[name] = moduleText(m, name, names);
|
|
55
|
+
const modules = {};
|
|
56
|
+
const exports = new Map();
|
|
57
|
+
for (const [name, text] of Object.entries(texts)) {
|
|
58
|
+
// One parse per module: the import() calls to route, and the exports the registry lists.
|
|
59
|
+
const analysis = analyzeModule(text, name);
|
|
60
|
+
exports.set(name, analysis?.exports ?? { names: [], stars: [] });
|
|
61
|
+
const routed = analysis?.routed;
|
|
62
|
+
let prelude = routed === undefined ? "" : `import { importFrom as ${IMPORT_FROM} } from "cellb:modules"; `;
|
|
63
|
+
// The main module evaluates the registry, so it is there before any code runs.
|
|
64
|
+
if (name === code.mainModule && !prelude)
|
|
65
|
+
prelude = 'import "cellb:modules"; ';
|
|
66
|
+
modules[name] = prelude ? prefixModule(routed ?? text, prelude) : text;
|
|
67
|
+
}
|
|
68
|
+
return { modules, registry: registrySource(Object.keys(texts), exports, code.mainModule) };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* What an import of loaded code that names none of its modules becomes: a module that throws when
|
|
72
|
+
* it is evaluated, so the failure comes where workerd's would (when the importing module runs), not
|
|
73
|
+
* at build time or when an unrelated module loads. CommonJS, so any named import of it builds.
|
|
74
|
+
*/
|
|
75
|
+
function missingModule(spec, importer) {
|
|
76
|
+
const message = `No such module "${spec}" (imported from "${importer}")`;
|
|
77
|
+
return {
|
|
78
|
+
path: `${importer}\u0000${spec}`,
|
|
79
|
+
namespace: "cells-missing",
|
|
80
|
+
pluginData: `throw new Error(${JSON.stringify(message)});\nmodule.exports = {};`,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The `cellb:modules` registry of a bundle of loaded code: each module, imported on demand. It
|
|
85
|
+
* also publishes itself as `globalThis.__cellbLoadedModules`, where an isolate thread's module
|
|
86
|
+
* hooks find it (node-entry.ts: `import()` from code built with `Function`).
|
|
87
|
+
*/
|
|
88
|
+
function registrySource(names, exports, main) {
|
|
89
|
+
const q = JSON.stringify;
|
|
90
|
+
return [
|
|
91
|
+
`const names = new Set(${q(names)});`,
|
|
92
|
+
`const resolve = ${RESOLVE_MODULE_NAME_SOURCE};`,
|
|
93
|
+
`const table = { ${names.map((n) => `${q(n)}: () => import(${q(`memory:${n}`)})`).join(", ")} };`,
|
|
94
|
+
"export const importFrom = (spec, importer) => {",
|
|
95
|
+
" const name = resolve(String(spec), importer, names);",
|
|
96
|
+
" return name === undefined ? import(spec) : table[name]();",
|
|
97
|
+
"};",
|
|
98
|
+
`globalThis.__cellbLoadedModules = { main: ${q(main)}, names, exportNames: ${q(exportNamesByModule(exports))}, load: (name) => table[name]() };`,
|
|
99
|
+
].join("\n");
|
|
100
|
+
}
|
|
31
101
|
/**
|
|
32
102
|
* Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.
|
|
33
103
|
* `cloudflare:workers` resolves to cellb's module so user classes extend the
|
|
@@ -121,8 +191,23 @@ export async function bundleWorker(entry, logs, outbound, opts = {}) {
|
|
|
121
191
|
path: "console",
|
|
122
192
|
namespace: "cells-console",
|
|
123
193
|
}));
|
|
124
|
-
// nodejs_compat on a Node host: `node:*` are the real Node.js modules
|
|
194
|
+
// nodejs_compat on a Node host: `node:*` are the real Node.js modules, except that
|
|
195
|
+
// `node:fs` also reads workerd's `/bundle` (node-compat/bundle-files.ts).
|
|
125
196
|
if (opts.nodeCompat) {
|
|
197
|
+
b.onResolve({ filter: /^(node:)?fs(\/promises)?$/ }, (a) => {
|
|
198
|
+
const name = a.path.replace(/^node:/, "");
|
|
199
|
+
return a.namespace === "cells-fs"
|
|
200
|
+
? { path: `node:${name}`, external: true }
|
|
201
|
+
: { path: name, namespace: "cells-fs" };
|
|
202
|
+
});
|
|
203
|
+
b.onResolve({ filter: /^cellb:bundle-fs$/ }, () => ({
|
|
204
|
+
path: ownModule(join(import.meta.dirname, "../node-compat"), "bundle-files"),
|
|
205
|
+
external: true,
|
|
206
|
+
}));
|
|
207
|
+
b.onLoad({ filter: /.*/, namespace: "cells-fs" }, (a) => ({
|
|
208
|
+
contents: a.path === "fs" ? FS_OVERLAY : FS_PROMISES_OVERLAY,
|
|
209
|
+
loader: "js",
|
|
210
|
+
}));
|
|
126
211
|
b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));
|
|
127
212
|
// workerd's nodejs_compat also takes the bare names ("path", "fs/promises").
|
|
128
213
|
b.onResolve({ filter: nodeBuiltinName }, (a) => ({
|
|
@@ -168,16 +253,41 @@ export async function bundleWorker(entry, logs, outbound, opts = {}) {
|
|
|
168
253
|
path: a.path.slice(7),
|
|
169
254
|
namespace: "memory",
|
|
170
255
|
}));
|
|
171
|
-
b.onResolve({ filter: /^\.{1,2}\// }, (a) =>
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
256
|
+
b.onResolve({ filter: /^\.{1,2}\// }, (a) => {
|
|
257
|
+
if (a.namespace !== "memory")
|
|
258
|
+
return undefined;
|
|
259
|
+
const path = new URL(a.path, `file:///${a.importer}`).pathname.slice(1);
|
|
260
|
+
// Not one of the loaded modules: it fails when it runs, as on workerd (missingModule).
|
|
261
|
+
return path in memory
|
|
262
|
+
? { path, namespace: "memory" }
|
|
263
|
+
: missingModule(a.path, a.importer);
|
|
264
|
+
});
|
|
177
265
|
b.onLoad({ filter: /.*/, namespace: "memory" }, (a) => ({
|
|
178
266
|
contents: memory[a.path],
|
|
179
267
|
loader: "js",
|
|
180
268
|
}));
|
|
269
|
+
b.onResolve({ filter: /^cellb:modules$/ }, () => ({
|
|
270
|
+
path: "modules",
|
|
271
|
+
namespace: "cells-modules",
|
|
272
|
+
}));
|
|
273
|
+
b.onLoad({ filter: /.*/, namespace: "cells-modules" }, () => ({
|
|
274
|
+
contents: entry.registry ??
|
|
275
|
+
"export const importFrom = (s) => import(s);",
|
|
276
|
+
loader: "js",
|
|
277
|
+
}));
|
|
278
|
+
// Anything else loaded code imports: a module's whole name (a URL, say), as workerd names
|
|
279
|
+
// modules, or else a module that throws when it is evaluated (missingModule).
|
|
280
|
+
b.onResolve({ filter: /.*/ }, (a) => {
|
|
281
|
+
if (a.namespace !== "memory")
|
|
282
|
+
return undefined;
|
|
283
|
+
if (a.path in memory)
|
|
284
|
+
return { path: a.path, namespace: "memory" };
|
|
285
|
+
return missingModule(a.path, a.importer);
|
|
286
|
+
});
|
|
287
|
+
b.onLoad({ filter: /.*/, namespace: "cells-missing" }, (a) => ({
|
|
288
|
+
contents: a.pluginData,
|
|
289
|
+
loader: "js",
|
|
290
|
+
}));
|
|
181
291
|
},
|
|
182
292
|
},
|
|
183
293
|
moduleRulesPlugin(opts.rules),
|
|
@@ -186,15 +296,14 @@ export async function bundleWorker(entry, logs, outbound, opts = {}) {
|
|
|
186
296
|
return (await import(/* @vite-ignore */ out));
|
|
187
297
|
}
|
|
188
298
|
/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */
|
|
189
|
-
export const nodeModuleLoader = async (_id,
|
|
299
|
+
export const nodeModuleLoader = async (_id, loaded, logs) => {
|
|
300
|
+
const code = await compileWasmModules(loaded);
|
|
190
301
|
const outbound = outboundFetch(code);
|
|
191
|
-
const modules =
|
|
192
|
-
for (const [name, m] of Object.entries(code.modules))
|
|
193
|
-
modules[name] = moduleText(m);
|
|
302
|
+
const { modules, registry } = loadedModuleTexts(code);
|
|
194
303
|
// `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).
|
|
195
304
|
const env = code.env ?? {};
|
|
196
305
|
const scope = workerScope(env);
|
|
197
|
-
const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {
|
|
306
|
+
const module = (await bundleWorker({ modules, main: code.mainModule, registry }, logs, outbound, {
|
|
198
307
|
scope,
|
|
199
308
|
}));
|
|
200
309
|
scope.bind({ env, exports: ctxExports(module, env) });
|
|
@@ -285,12 +394,10 @@ export function nodeIsolatedLoader(storage) {
|
|
|
285
394
|
port.unref(); // an idle isolate never keeps the process alive
|
|
286
395
|
return { port: port, terminate: () => void port.terminate() };
|
|
287
396
|
},
|
|
288
|
-
prepare: async (_id,
|
|
397
|
+
prepare: async (_id, loaded) => {
|
|
289
398
|
isolateEntry ??= buildIsolateEntry();
|
|
290
|
-
await isolateEntry;
|
|
291
|
-
const modules =
|
|
292
|
-
for (const [name, m] of Object.entries(code.modules))
|
|
293
|
-
modules[name] = moduleText(m);
|
|
399
|
+
const [code] = await Promise.all([compileWasmModules(loaded), isolateEntry]);
|
|
400
|
+
const { modules, registry } = loadedModuleTexts(code);
|
|
294
401
|
const out = await build({
|
|
295
402
|
entryPoints: [`memory:${code.mainModule}`],
|
|
296
403
|
write: false,
|
|
@@ -325,21 +432,46 @@ export function nodeIsolatedLoader(storage) {
|
|
|
325
432
|
path: a.path.slice(7),
|
|
326
433
|
namespace: "memory",
|
|
327
434
|
}));
|
|
328
|
-
b.onResolve({ filter: /^\.{1,2}\// }, (a) =>
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
435
|
+
b.onResolve({ filter: /^\.{1,2}\// }, (a) => {
|
|
436
|
+
if (a.namespace !== "memory")
|
|
437
|
+
return undefined;
|
|
438
|
+
const path = new URL(a.path, `file:///${a.importer}`).pathname.slice(1);
|
|
439
|
+
// Not one of the loaded modules: it fails when it runs, as on workerd (missingModule).
|
|
440
|
+
return path in modules
|
|
441
|
+
? { path, namespace: "memory" }
|
|
442
|
+
: missingModule(a.path, a.importer);
|
|
443
|
+
});
|
|
334
444
|
b.onLoad({ filter: /.*/, namespace: "memory" }, (a) => ({
|
|
335
445
|
contents: modules[a.path],
|
|
336
446
|
loader: "js",
|
|
337
447
|
}));
|
|
448
|
+
b.onResolve({ filter: /^cellb:modules$/ }, () => ({
|
|
449
|
+
path: "modules",
|
|
450
|
+
namespace: "cells-modules",
|
|
451
|
+
}));
|
|
452
|
+
b.onLoad({ filter: /.*/, namespace: "cells-modules" }, () => ({
|
|
453
|
+
contents: registry,
|
|
454
|
+
loader: "js",
|
|
455
|
+
}));
|
|
456
|
+
// Anything else loaded code imports: a module's whole name (a URL, say), as workerd names
|
|
457
|
+
// modules, or else a module that throws when it is evaluated (missingModule).
|
|
458
|
+
b.onResolve({ filter: /.*/ }, (a) => {
|
|
459
|
+
if (a.namespace !== "memory")
|
|
460
|
+
return undefined;
|
|
461
|
+
if (a.path in modules)
|
|
462
|
+
return { path: a.path, namespace: "memory" };
|
|
463
|
+
return missingModule(a.path, a.importer);
|
|
464
|
+
});
|
|
465
|
+
b.onLoad({ filter: /.*/, namespace: "cells-missing" }, (a) => ({
|
|
466
|
+
contents: a.pluginData,
|
|
467
|
+
loader: "js",
|
|
468
|
+
}));
|
|
338
469
|
},
|
|
339
470
|
},
|
|
340
471
|
],
|
|
341
472
|
});
|
|
342
|
-
|
|
473
|
+
// Compiled wasm modules travel beside the source (a worker thread takes them as they are).
|
|
474
|
+
return { source: out.outputFiles[0].text, wasm: wasmModulesOf(code) };
|
|
343
475
|
},
|
|
344
476
|
});
|
|
345
477
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAGL,UAAU,EACV,aAAa,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,KAAK,cAAc,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAmB,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAoB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,WAAW,EAGX,mBAAmB,EACnB,YAAY,EACZ,cAAc,GAEf,MAAM,eAAe,CAAC;AAEvB,oGAAoG;AACpG,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,KAAK,MAAM,IAAI,IAAI,cAAc,EAAE,CAAC;QAClC,M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,iBAAiB;IAC9B,gBAAgB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;IACtF,MAAM,KAAK,CAAC;QACV,WAAW,EAAE,CAAC,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;QACtE,OAAO,EAAE,gBAAgB;QACzB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,QAAQ;QAChB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,wFAAwF;AACxF,SAAS,wBAAwB,CAAC,KAAkB;IAClD,MAAM,CAAC,GAAG,UAAqC,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { type ModuleRule, moduleRulesPlugin } from \"./module-rules.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n hasNodeCompat,\n loadProjectBindings,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n populatesProcessEnv,\n processEnvOf,\n WRANGLER_FILES,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of WRANGLER_FILES) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry: { path: string } | { modules: Record<string, string>; main: string },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: {\n nodeCompat?: boolean;\n standardBinaryType?: boolean;\n scope?: WorkerScope;\n /** wrangler `rules` for non-JS imports (the defaults: `.wasm`, `.bin`, `.txt`…, as wrangler). */\n rules?: ModuleRule[];\n } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n registry[consoleKey] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n // nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires\n // node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's\n // require shim needs a `require` in scope: vitest's module runner provides one, plain Node\n // does not.\n ...(opts.nodeCompat\n ? {\n banner: {\n js: 'import { createRequire as __cellbCreateRequire } from \"node:module\";\\nconst require = __cellbCreateRequire(import.meta.url);',\n },\n }\n : {}),\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules.\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n },\n },\n moduleRulesPlugin(opts.rules),\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, code, logs) => {\n const outbound = outboundFetch(code);\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = hasNodeCompat(config);\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (populatesProcessEnv(config))\n for (const [k, v] of Object.entries(processEnvOf(config))) process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n rules: config.rules,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n bindings: await loadProjectBindings(config),\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, code) => {\n isolateEntry ??= buildIsolateEntry();\n await isolateEntry;\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n // cloudflare-workers.js in the published package (dist/), .ts in the sources.\n `export * from ${JSON.stringify(ownModule(import.meta.dirname, \"cloudflare-workers\"))};`,\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return { source: out.outputFiles[0].text };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|
|
1
|
+
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,WAAW,EAEX,YAAY,EACZ,0BAA0B,GAC3B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kBAAkB,EAGlB,UAAU,EACV,aAAa,EAEb,aAAa,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,KAAK,cAAc,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAA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,gBAAgB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;IACtF,MAAM,KAAK,CAAC;QACV,WAAW,EAAE,CAAC,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;QACtE,OAAO,EAAE,gBAAgB;QACzB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,MAAM;QAChB,MAAM,EAAE,QAAQ;QAChB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,wFAAwF;AACxF,SAAS,wBAAwB,CAAC,KAAkB;IAClD,MAAM,CAAC,GAAG,UAAqC,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n analyzeModule,\n exportNamesByModule,\n IMPORT_FROM,\n type ModuleExports,\n prefixModule,\n RESOLVE_MODULE_NAME_SOURCE,\n} from \"../bindings/module-registry.js\";\nimport {\n compileWasmModules,\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n wasmModulesOf,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { type ModuleRule, moduleRulesPlugin } from \"./module-rules.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n hasNodeCompat,\n loadProjectBindings,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n populatesProcessEnv,\n processEnvOf,\n WRANGLER_FILES,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of WRANGLER_FILES) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/** Worker code's `node:fs` under nodejs_compat on Node: Node's own, with workerd's `/bundle`. */\nconst FS_OVERLAY = `import * as real from \"node:fs\";\nimport { bundleFs } from \"cellb:bundle-fs\";\nexport * from \"node:fs\";\nconst o = bundleFs(real);\nexport const { existsSync, readFileSync, statSync, lstatSync, readdirSync, accessSync, readFile, stat, lstat, readdir, access, promises } = o;\nexport default { ...real, ...o };`;\n/** Worker code's `node:fs/promises`, the same way. */\nconst FS_PROMISES_OVERLAY = `import * as real from \"node:fs/promises\";\nimport { bundleFsPromises } from \"cellb:bundle-fs\";\nexport * from \"node:fs/promises\";\nconst o = bundleFsPromises(real);\nexport const { readFile, stat, lstat, readdir, access } = o;\nexport default o;`;\n\n/**\n * The modules of loaded code as ES module text, each `import()` the bundler cannot link going to\n * the `cellb:modules` registry instead (module-registry.ts).\n */\nfunction loadedModuleTexts(code: WorkerCode): {\n modules: Record<string, string>;\n registry: string;\n} {\n const texts: Record<string, string> = {};\n const names = new Set(Object.keys(code.modules));\n for (const [name, m] of Object.entries(code.modules)) texts[name] = moduleText(m, name, names);\n const modules: Record<string, string> = {};\n const exports = new Map<string, ModuleExports>();\n for (const [name, text] of Object.entries(texts)) {\n // One parse per module: the import() calls to route, and the exports the registry lists.\n const analysis = analyzeModule(text, name);\n exports.set(name, analysis?.exports ?? { names: [], stars: [] });\n const routed = analysis?.routed;\n let prelude =\n routed === undefined ? \"\" : `import { importFrom as ${IMPORT_FROM} } from \"cellb:modules\"; `;\n // The main module evaluates the registry, so it is there before any code runs.\n if (name === code.mainModule && !prelude) prelude = 'import \"cellb:modules\"; ';\n modules[name] = prelude ? prefixModule(routed ?? text, prelude) : text;\n }\n return { modules, registry: registrySource(Object.keys(texts), exports, code.mainModule) };\n}\n\n/**\n * What an import of loaded code that names none of its modules becomes: a module that throws when\n * it is evaluated, so the failure comes where workerd's would (when the importing module runs), not\n * at build time or when an unrelated module loads. CommonJS, so any named import of it builds.\n */\nfunction missingModule(spec: string, importer: string) {\n const message = `No such module \"${spec}\" (imported from \"${importer}\")`;\n return {\n path: `${importer}\\u0000${spec}`,\n namespace: \"cells-missing\",\n pluginData: `throw new Error(${JSON.stringify(message)});\\nmodule.exports = {};`,\n };\n}\n\n/**\n * The `cellb:modules` registry of a bundle of loaded code: each module, imported on demand. It\n * also publishes itself as `globalThis.__cellbLoadedModules`, where an isolate thread's module\n * hooks find it (node-entry.ts: `import()` from code built with `Function`).\n */\nfunction registrySource(\n names: string[],\n exports: Map<string, ModuleExports>,\n main: string,\n): string {\n const q = JSON.stringify;\n return [\n `const names = new Set(${q(names)});`,\n `const resolve = ${RESOLVE_MODULE_NAME_SOURCE};`,\n `const table = { ${names.map((n) => `${q(n)}: () => import(${q(`memory:${n}`)})`).join(\", \")} };`,\n \"export const importFrom = (spec, importer) => {\",\n \" const name = resolve(String(spec), importer, names);\",\n \" return name === undefined ? import(spec) : table[name]();\",\n \"};\",\n `globalThis.__cellbLoadedModules = { main: ${q(main)}, names, exportNames: ${q(exportNamesByModule(exports))}, load: (name) => table[name]() };`,\n ].join(\"\\n\");\n}\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry:\n | { path: string }\n | {\n modules: Record<string, string>;\n main: string;\n /** The `cellb:modules` registry the modules import (loadedModuleTexts). */\n registry?: string;\n },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: {\n nodeCompat?: boolean;\n standardBinaryType?: boolean;\n scope?: WorkerScope;\n /** wrangler `rules` for non-JS imports (the defaults: `.wasm`, `.bin`, `.txt`…, as wrangler). */\n rules?: ModuleRule[];\n } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n registry[consoleKey] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n // nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires\n // node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's\n // require shim needs a `require` in scope: vitest's module runner provides one, plain Node\n // does not.\n ...(opts.nodeCompat\n ? {\n banner: {\n js: 'import { createRequire as __cellbCreateRequire } from \"node:module\";\\nconst require = __cellbCreateRequire(import.meta.url);',\n },\n }\n : {}),\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules, except that\n // `node:fs` also reads workerd's `/bundle` (node-compat/bundle-files.ts).\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^(node:)?fs(\\/promises)?$/ }, (a) => {\n const name = a.path.replace(/^node:/, \"\");\n return a.namespace === \"cells-fs\"\n ? { path: `node:${name}`, external: true }\n : { path: name, namespace: \"cells-fs\" };\n });\n b.onResolve({ filter: /^cellb:bundle-fs$/ }, () => ({\n path: ownModule(join(import.meta.dirname, \"../node-compat\"), \"bundle-files\"),\n external: true,\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fs\" }, (a) => ({\n contents: a.path === \"fs\" ? FS_OVERLAY : FS_PROMISES_OVERLAY,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) => {\n if (a.namespace !== \"memory\") return undefined;\n const path = new URL(a.path, `file:///${a.importer}`).pathname.slice(1);\n // Not one of the loaded modules: it fails when it runs, as on workerd (missingModule).\n return path in memory\n ? { path, namespace: \"memory\" }\n : missingModule(a.path, a.importer);\n });\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:modules$/ }, () => ({\n path: \"modules\",\n namespace: \"cells-modules\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-modules\" }, () => ({\n contents:\n (entry as { registry?: string }).registry ??\n \"export const importFrom = (s) => import(s);\",\n loader: \"js\",\n }));\n // Anything else loaded code imports: a module's whole name (a URL, say), as workerd names\n // modules, or else a module that throws when it is evaluated (missingModule).\n b.onResolve({ filter: /.*/ }, (a) => {\n if (a.namespace !== \"memory\") return undefined;\n if (a.path in memory) return { path: a.path, namespace: \"memory\" };\n return missingModule(a.path, a.importer);\n });\n b.onLoad({ filter: /.*/, namespace: \"cells-missing\" }, (a) => ({\n contents: a.pluginData as string,\n loader: \"js\",\n }));\n },\n },\n moduleRulesPlugin(opts.rules),\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, loaded, logs) => {\n const code = await compileWasmModules(loaded);\n const outbound = outboundFetch(code);\n const { modules, registry } = loadedModuleTexts(code);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule, registry }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = hasNodeCompat(config);\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (populatesProcessEnv(config))\n for (const [k, v] of Object.entries(processEnvOf(config))) process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n rules: config.rules,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n bindings: await loadProjectBindings(config),\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, loaded) => {\n isolateEntry ??= buildIsolateEntry();\n const [code] = await Promise.all([compileWasmModules(loaded), isolateEntry]);\n const { modules, registry } = loadedModuleTexts(code);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n // cloudflare-workers.js in the published package (dist/), .ts in the sources.\n `export * from ${JSON.stringify(ownModule(import.meta.dirname, \"cloudflare-workers\"))};`,\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) => {\n if (a.namespace !== \"memory\") return undefined;\n const path = new URL(a.path, `file:///${a.importer}`).pathname.slice(1);\n // Not one of the loaded modules: it fails when it runs, as on workerd (missingModule).\n return path in modules\n ? { path, namespace: \"memory\" }\n : missingModule(a.path, a.importer);\n });\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:modules$/ }, () => ({\n path: \"modules\",\n namespace: \"cells-modules\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-modules\" }, () => ({\n contents: registry,\n loader: \"js\",\n }));\n // Anything else loaded code imports: a module's whole name (a URL, say), as workerd names\n // modules, or else a module that throws when it is evaluated (missingModule).\n b.onResolve({ filter: /.*/ }, (a) => {\n if (a.namespace !== \"memory\") return undefined;\n if (a.path in modules) return { path: a.path, namespace: \"memory\" };\n return missingModule(a.path, a.importer);\n });\n b.onLoad({ filter: /.*/, namespace: \"cells-missing\" }, (a) => ({\n contents: a.pluginData as string,\n loader: \"js\",\n }));\n },\n },\n ],\n });\n // Compiled wasm modules travel beside the source (a worker thread takes them as they are).\n return { source: out.outputFiles[0].text, wasm: wasmModulesOf(code) };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|
|
@@ -13,6 +13,7 @@ export const WORKERS_MODULE_NAMES = [
|
|
|
13
13
|
"WorkerEntrypoint",
|
|
14
14
|
"WorkflowEntrypoint",
|
|
15
15
|
"RpcTarget",
|
|
16
|
+
"abortIsolate",
|
|
16
17
|
"env",
|
|
17
18
|
"exports",
|
|
18
19
|
"waitUntil",
|
|
@@ -51,7 +52,7 @@ export function putLoadedModule(url, m) {
|
|
|
51
52
|
const wrapped = typeof m === "object" && !("js" in m) && !("esModule" in m);
|
|
52
53
|
return fetch(url, {
|
|
53
54
|
method: "PUT",
|
|
54
|
-
body: moduleText(m),
|
|
55
|
+
body: moduleText(m, url.slice(url.lastIndexOf("/") + 1)),
|
|
55
56
|
headers: wrapped ? { [ESM_HEADER]: "1" } : {},
|
|
56
57
|
});
|
|
57
58
|
}
|