@statewalker/cellb 0.8.7 → 0.8.9
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 +1 -1
- package/dist/adapters/node-sqlite.js +42 -13
- package/dist/adapters/node-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/module-registry.d.ts +33 -0
- package/dist/bindings/module-registry.js +180 -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/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/host.js +20 -2
- package/dist/isolate/host.js.map +1 -1
- package/dist/isolate/isolate-worker.js +13 -1
- 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 +228 -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-modules.d.ts +1 -1
- package/dist/project/browser-modules.js +25 -5
- package/dist/project/browser-modules.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 +154 -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
package/dist/node-compat/fs.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `node:fs` for browsers (nodejs_compat): there is no file system, so every call fails with
|
|
3
3
|
* `ENOENT` (as for a missing file) and `existsSync` is false. Code that probes for optional
|
|
4
|
-
* files, such as an SDK reading `/proc/self/environ` inside a `try`, keeps working.
|
|
4
|
+
* files, such as an SDK reading `/proc/self/environ` inside a `try`, keeps working. The one
|
|
5
|
+
* directory there is is workerd's `/bundle`, read-only: the bundle's own non-JS modules
|
|
6
|
+
* (bundle-files.ts).
|
|
5
7
|
*/
|
|
8
|
+
import { bundleFs } from "./bundle-files.js";
|
|
6
9
|
const missing = (op) => (path) => {
|
|
7
10
|
throw Object.assign(new Error(`ENOENT: no such file or directory, ${op} '${String(path)}'`), {
|
|
8
11
|
code: "ENOENT",
|
|
@@ -11,22 +14,52 @@ const missing = (op) => (path) => {
|
|
|
11
14
|
});
|
|
12
15
|
};
|
|
13
16
|
const missingAsync = (op) => async (path) => missing(op)(path);
|
|
14
|
-
|
|
15
|
-
|
|
17
|
+
const missingCallback = (op) => (path, ...rest) => {
|
|
18
|
+
const cb = rest.pop();
|
|
19
|
+
try {
|
|
20
|
+
missing(op)(path);
|
|
21
|
+
}
|
|
22
|
+
catch (e) {
|
|
23
|
+
queueMicrotask(() => cb(e));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const none = {
|
|
27
|
+
existsSync: (_path) => false,
|
|
28
|
+
readFileSync: missing("open"),
|
|
29
|
+
statSync: missing("stat"),
|
|
30
|
+
lstatSync: missing("lstat"),
|
|
31
|
+
readdirSync: missing("scandir"),
|
|
32
|
+
accessSync: missing("access"),
|
|
33
|
+
readFile: missingCallback("open"),
|
|
34
|
+
stat: missingCallback("stat"),
|
|
35
|
+
lstat: missingCallback("lstat"),
|
|
36
|
+
readdir: missingCallback("scandir"),
|
|
37
|
+
access: missingCallback("access"),
|
|
38
|
+
promises: {
|
|
39
|
+
readFile: missingAsync("open"),
|
|
40
|
+
writeFile: missingAsync("open"),
|
|
41
|
+
stat: missingAsync("stat"),
|
|
42
|
+
lstat: missingAsync("lstat"),
|
|
43
|
+
readdir: missingAsync("scandir"),
|
|
44
|
+
mkdir: missingAsync("mkdir"),
|
|
45
|
+
access: missingAsync("access"),
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
const fs = bundleFs(none);
|
|
49
|
+
export const existsSync = fs.existsSync;
|
|
50
|
+
export const readFileSync = fs.readFileSync;
|
|
16
51
|
export const writeFileSync = missing("open");
|
|
17
|
-
export const statSync =
|
|
18
|
-
export const lstatSync =
|
|
19
|
-
export const readdirSync =
|
|
52
|
+
export const statSync = fs.statSync;
|
|
53
|
+
export const lstatSync = fs.lstatSync;
|
|
54
|
+
export const readdirSync = fs.readdirSync;
|
|
55
|
+
export const accessSync = fs.accessSync;
|
|
20
56
|
export const mkdirSync = missing("mkdir");
|
|
21
|
-
export const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
mkdir: missingAsync("mkdir"),
|
|
28
|
-
access: missingAsync("access"),
|
|
29
|
-
};
|
|
57
|
+
export const readFile = fs.readFile;
|
|
58
|
+
export const stat = fs.stat;
|
|
59
|
+
export const lstat = fs.lstat;
|
|
60
|
+
export const readdir = fs.readdir;
|
|
61
|
+
export const access = fs.access;
|
|
62
|
+
export const promises = fs.promises;
|
|
30
63
|
export default {
|
|
31
64
|
existsSync,
|
|
32
65
|
readFileSync,
|
|
@@ -34,7 +67,13 @@ export default {
|
|
|
34
67
|
statSync,
|
|
35
68
|
lstatSync,
|
|
36
69
|
readdirSync,
|
|
70
|
+
accessSync,
|
|
37
71
|
mkdirSync,
|
|
72
|
+
readFile,
|
|
73
|
+
stat,
|
|
74
|
+
lstat,
|
|
75
|
+
readdir,
|
|
76
|
+
access,
|
|
38
77
|
promises,
|
|
39
78
|
};
|
|
40
79
|
//# sourceMappingURL=fs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/node-compat/fs.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/node-compat/fs.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAE7C,MAAM,OAAO,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,CAAC,IAAc,EAAE,EAAE;IACjD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,sCAAsC,EAAE,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAC3F,IAAI,EAAE,QAAQ;QACd,OA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IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,QAAQ;CACT,CAAC","sourcesContent":["/**\n * `node:fs` for browsers (nodejs_compat): there is no file system, so every call fails with\n * `ENOENT` (as for a missing file) and `existsSync` is false. Code that probes for optional\n * files, such as an SDK reading `/proc/self/environ` inside a `try`, keeps working. The one\n * directory there is is workerd's `/bundle`, read-only: the bundle's own non-JS modules\n * (bundle-files.ts).\n */\nimport { bundleFs } from \"./bundle-files.js\";\n\nconst missing = (op: string) => (path?: unknown) => {\n throw Object.assign(new Error(`ENOENT: no such file or directory, ${op} '${String(path)}'`), {\n code: \"ENOENT\",\n syscall: op,\n path,\n });\n};\nconst missingAsync =\n (op: string) =>\n async (path?: unknown): Promise<never> =>\n missing(op)(path);\nconst missingCallback =\n (op: string) =>\n (path: unknown, ...rest: unknown[]) => {\n const cb = rest.pop() as (e: unknown) => void;\n try {\n missing(op)(path);\n } catch (e) {\n queueMicrotask(() => cb(e));\n }\n };\n\nconst none = {\n existsSync: (_path?: unknown) => false,\n readFileSync: missing(\"open\"),\n statSync: missing(\"stat\"),\n lstatSync: missing(\"lstat\"),\n readdirSync: missing(\"scandir\"),\n accessSync: missing(\"access\"),\n readFile: missingCallback(\"open\"),\n stat: missingCallback(\"stat\"),\n lstat: missingCallback(\"lstat\"),\n readdir: missingCallback(\"scandir\"),\n access: missingCallback(\"access\"),\n promises: {\n readFile: missingAsync(\"open\"),\n writeFile: missingAsync(\"open\"),\n stat: missingAsync(\"stat\"),\n lstat: missingAsync(\"lstat\"),\n readdir: missingAsync(\"scandir\"),\n mkdir: missingAsync(\"mkdir\"),\n access: missingAsync(\"access\"),\n },\n};\nconst fs = bundleFs(none) as typeof none;\n\nexport const existsSync = fs.existsSync;\nexport const readFileSync = fs.readFileSync;\nexport const writeFileSync = missing(\"open\");\nexport const statSync = fs.statSync;\nexport const lstatSync = fs.lstatSync;\nexport const readdirSync = fs.readdirSync;\nexport const accessSync = fs.accessSync;\nexport const mkdirSync = missing(\"mkdir\");\nexport const readFile = fs.readFile;\nexport const stat = fs.stat;\nexport const lstat = fs.lstat;\nexport const readdir = fs.readdir;\nexport const access = fs.access;\nexport const promises = fs.promises;\n\nexport default {\n existsSync,\n readFileSync,\n writeFileSync,\n statSync,\n lstatSync,\n readdirSync,\n accessSync,\n mkdirSync,\n readFile,\n stat,\n lstat,\n readdir,\n access,\n promises,\n};\n"]}
|
|
@@ -6,7 +6,7 @@ import { type ModuleLoader } from "../bindings/worker-loader.js";
|
|
|
6
6
|
* bundled with the Worker, so it declares no names beyond its exports: esbuild would rename the
|
|
7
7
|
* Worker's own variables of the same name, and those names show in error messages.
|
|
8
8
|
*/
|
|
9
|
-
export declare const PROJECT_WORKERS_MODULE_SHIM = "const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget; export default m; export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);";
|
|
9
|
+
export declare const PROJECT_WORKERS_MODULE_SHIM = "const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m; export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);";
|
|
10
10
|
/**
|
|
11
11
|
* Worker Loader in a browser realm: each module of a WorkerCode becomes a Blob-URL ES
|
|
12
12
|
* module. `cloudflare:workers` resolves to a shim reading the runtime's own classes from
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { IMPORT_FROM, prefixModule, resolveModuleName, routeDynamicImports, } from "../bindings/module-registry.js";
|
|
2
|
+
import { compileWasmModules, moduleText, outboundFetch, } from "../bindings/worker-loader.js";
|
|
2
3
|
import { ctxExports } from "../core/handles.js";
|
|
3
4
|
import { rewriteModuleSpecifiers } from "./module-specifiers.js";
|
|
4
5
|
import { workerScope } from "./worker-scope.js";
|
|
5
|
-
const WORKERS_CLASSES = "const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget; export default m;";
|
|
6
|
+
const WORKERS_CLASSES = "const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m;";
|
|
6
7
|
/**
|
|
7
8
|
* `cloudflare:workers` for a project's own bundle: the classes, and the project's `env` and
|
|
8
9
|
* `exports` from `globalThis.__cellsProjectScope` (set by `browserProjectRuntime`, and by
|
|
@@ -21,7 +22,8 @@ export const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env
|
|
|
21
22
|
export function browserModuleLoader(workersModuleShim) {
|
|
22
23
|
const blob = (text) => URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
|
|
23
24
|
const fixedShimUrl = workersModuleShim && blob(workersModuleShim);
|
|
24
|
-
return async (_id,
|
|
25
|
+
return async (_id, loaded, logs) => {
|
|
26
|
+
const code = await compileWasmModules(loaded);
|
|
25
27
|
const env = code.env ?? {};
|
|
26
28
|
const scope = fixedShimUrl ? undefined : workerScope(env);
|
|
27
29
|
let shimUrl = fixedShimUrl;
|
|
@@ -59,6 +61,24 @@ export function browserModuleLoader(workersModuleShim) {
|
|
|
59
61
|
g.__cellsOutbound[key] = outbound;
|
|
60
62
|
consolePrelude += `const fetch = globalThis.__cellsOutbound[${JSON.stringify(key)}];\n`;
|
|
61
63
|
}
|
|
64
|
+
// `import()` the Blob URLs cannot link (a computed specifier, a module's whole name) resolves
|
|
65
|
+
// against this load's modules at run time (module-registry.ts).
|
|
66
|
+
const names = new Set(Object.keys(code.modules));
|
|
67
|
+
const importsKey = `i${Math.random().toString(36).slice(2)}`;
|
|
68
|
+
const g = globalThis;
|
|
69
|
+
g.__cellsImports ??= {};
|
|
70
|
+
const imports = g.__cellsImports;
|
|
71
|
+
imports[importsKey] = (spec, importer) => {
|
|
72
|
+
const name = resolveModuleName(String(spec), importer, names);
|
|
73
|
+
return import(/* @vite-ignore */ name === undefined ? String(spec) : urlOf(name));
|
|
74
|
+
};
|
|
75
|
+
const routed = (name) => {
|
|
76
|
+
const text = source(name);
|
|
77
|
+
const out = routeDynamicImports(text, name);
|
|
78
|
+
return out === undefined
|
|
79
|
+
? text
|
|
80
|
+
: prefixModule(out, `const ${IMPORT_FROM} = globalThis.__cellsImports[${JSON.stringify(importsKey)}]; `);
|
|
81
|
+
};
|
|
62
82
|
const urls = new Map();
|
|
63
83
|
// Modules whose Blob URL is being made: a Blob URL exists only once its text (with its
|
|
64
84
|
// imports' URLs) does, so modules that import each other cannot be loaded this way.
|
|
@@ -67,7 +87,7 @@ export function browserModuleLoader(workersModuleShim) {
|
|
|
67
87
|
const m = code.modules[name];
|
|
68
88
|
if (m === undefined)
|
|
69
89
|
throw new Error(`Worker Loader: module "${name}" not found`);
|
|
70
|
-
return moduleText(m);
|
|
90
|
+
return moduleText(m, name, names);
|
|
71
91
|
};
|
|
72
92
|
const urlOf = (name) => {
|
|
73
93
|
const known = urls.get(name);
|
|
@@ -79,7 +99,7 @@ export function browserModuleLoader(workersModuleShim) {
|
|
|
79
99
|
const base = name.includes("/") ? name.slice(0, name.lastIndexOf("/") + 1) : "";
|
|
80
100
|
// Only the module's own imports: the same words in a string, a template or a comment are
|
|
81
101
|
// not imports (a code generator's template may well contain `from "cloudflare:workers"`).
|
|
82
|
-
const text = rewriteModuleSpecifiers(
|
|
102
|
+
const text = rewriteModuleSpecifiers(routed(name), (spec) => {
|
|
83
103
|
if (spec === "cloudflare:workers")
|
|
84
104
|
return shimUrl;
|
|
85
105
|
if (spec.startsWith("./") || spec.startsWith("../"))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-modules.js","sourceRoot":"","sources":["../../src/project/browser-modules.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,eAAe,GACnB,uNAAuN,CAAC;AAE1N;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,eAAe,0LAA0L,CAAC;AAExP;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,iBAA0B;IAC5D,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC;IAClG,MAAM,YAAY,GAAG,iBAAiB,IAAI,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAClE,OAAO,KAAK,EAAE,GAAW,EAAE,IAAgB,EAAE,IAAc,EAAE,EAAE;QAC7D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,OAAO,GAAG,YAAY,CAAC;QAC3B,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,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CAAC,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport { rewriteModuleSpecifiers } from \"./module-specifiers.js\";\nimport { workerScope } from \"./worker-scope.js\";\n\nconst WORKERS_CLASSES =\n \"const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget; export default m;\";\n\n/**\n * `cloudflare:workers` for a project's own bundle: the classes, and the project's `env` and\n * `exports` from `globalThis.__cellsProjectScope` (set by `browserProjectRuntime`, and by\n * `serveIsolate` for the loaded Worker an isolate runs). The shim is\n * bundled with the Worker, so it declares no names beyond its exports: esbuild would rename the\n * Worker's own variables of the same name, and those names show in error messages.\n */\nexport const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);`;\n\n/**\n * Worker Loader in a browser realm: each module of a WorkerCode becomes a Blob-URL ES\n * module. `cloudflare:workers` resolves to a shim reading the runtime's own classes from\n * `globalThis.__cellsWorkersModule` and the loaded code's own `env` and `exports` (or to\n * `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of\n * sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).\n */\nexport function browserModuleLoader(workersModuleShim?: string): ModuleLoader {\n const blob = (text: string) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\n const fixedShimUrl = workersModuleShim && blob(workersModuleShim);\n return async (_id: string, code: WorkerCode, logs?: LogSink) => {\n const env = code.env ?? {};\n const scope = fixedShimUrl ? undefined : workerScope(env);\n let shimUrl = fixedShimUrl;\n if (scope) {\n const key = `s${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[key] = scope;\n shimUrl = blob(\n `${WORKERS_CLASSES} const s = globalThis.__cellsWorkerScopes[${JSON.stringify(key)}]; export const env = s.env, exports = s.exports, waitUntil = s.waitUntil;`,\n );\n }\n let consolePrelude = \"\";\n if (logs) {\n const key = `c${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\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 (g.__cellsConsoles as Record<string, unknown>)[key] = 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 consolePrelude = `const console = globalThis.__cellsConsoles[${JSON.stringify(key)}];\\n`;\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const key = `o${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[key] = outbound;\n consolePrelude += `const fetch = globalThis.__cellsOutbound[${JSON.stringify(key)}];\\n`;\n }\n const urls = new Map<string, string>();\n // Modules whose Blob URL is being made: a Blob URL exists only once its text (with its\n // imports' URLs) does, so modules that import each other cannot be loaded this way.\n const making: string[] = [];\n const source = (name: string) => {\n const m = code.modules[name];\n if (m === undefined) throw new Error(`Worker Loader: module \"${name}\" not found`);\n return moduleText(m);\n };\n const urlOf = (name: string): string => {\n const known = urls.get(name);\n if (known) return known;\n if (making.includes(name))\n throw new Error(\n `Worker Loader: modules import each other (${[...making.slice(making.indexOf(name)), name].join(\" → \")}); a browser realm loads each module from a Blob URL, which cannot form a cycle`,\n );\n making.push(name);\n const base = name.includes(\"/\") ? name.slice(0, name.lastIndexOf(\"/\") + 1) : \"\";\n // Only the module's own imports: the same words in a string, a template or a comment are\n // not imports (a code generator's template may well contain `from \"cloudflare:workers\"`).\n const text = rewriteModuleSpecifiers(source(name), (spec) => {\n if (spec === \"cloudflare:workers\") return shimUrl;\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\"))\n return urlOf(new URL(spec, `file:///${base}`).pathname.slice(1));\n return undefined;\n });\n const url = URL.createObjectURL(\n new Blob([consolePrelude + text], { type: \"text/javascript\" }),\n );\n urls.set(name, url);\n making.pop();\n return url;\n };\n const module = (await import(/* @vite-ignore */ urlOf(code.mainModule))) as Record<\n string,\n unknown\n >;\n scope?.bind({ env, exports: ctxExports(module, env) });\n return module;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-modules.js","sourceRoot":"","sources":["../../src/project/browser-modules.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kBAAkB,EAGlB,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,eAAe,GACnB,sPAAsP,CAAC;AAEzP;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,eAAe,0LAA0L,CAAC;AAExP;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,iBAA0B;IAC5D,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC,CA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IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAC/D,CAAC;YACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,GAAG,CAAC;QACb,CAAC,CAAC;QACF,MAAM,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAGtE,CAAC;QACF,KAAK,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n IMPORT_FROM,\n prefixModule,\n resolveModuleName,\n routeDynamicImports,\n} from \"../bindings/module-registry.js\";\nimport {\n compileWasmModules,\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport { rewriteModuleSpecifiers } from \"./module-specifiers.js\";\nimport { workerScope } from \"./worker-scope.js\";\n\nconst WORKERS_CLASSES =\n \"const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m;\";\n\n/**\n * `cloudflare:workers` for a project's own bundle: the classes, and the project's `env` and\n * `exports` from `globalThis.__cellsProjectScope` (set by `browserProjectRuntime`, and by\n * `serveIsolate` for the loaded Worker an isolate runs). The shim is\n * bundled with the Worker, so it declares no names beyond its exports: esbuild would rename the\n * Worker's own variables of the same name, and those names show in error messages.\n */\nexport const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);`;\n\n/**\n * Worker Loader in a browser realm: each module of a WorkerCode becomes a Blob-URL ES\n * module. `cloudflare:workers` resolves to a shim reading the runtime's own classes from\n * `globalThis.__cellsWorkersModule` and the loaded code's own `env` and `exports` (or to\n * `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of\n * sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).\n */\nexport function browserModuleLoader(workersModuleShim?: string): ModuleLoader {\n const blob = (text: string) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\n const fixedShimUrl = workersModuleShim && blob(workersModuleShim);\n return async (_id: string, loaded: WorkerCode, logs?: LogSink) => {\n const code = await compileWasmModules(loaded);\n const env = code.env ?? {};\n const scope = fixedShimUrl ? undefined : workerScope(env);\n let shimUrl = fixedShimUrl;\n if (scope) {\n const key = `s${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[key] = scope;\n shimUrl = blob(\n `${WORKERS_CLASSES} const s = globalThis.__cellsWorkerScopes[${JSON.stringify(key)}]; export const env = s.env, exports = s.exports, waitUntil = s.waitUntil;`,\n );\n }\n let consolePrelude = \"\";\n if (logs) {\n const key = `c${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\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 (g.__cellsConsoles as Record<string, unknown>)[key] = 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 consolePrelude = `const console = globalThis.__cellsConsoles[${JSON.stringify(key)}];\\n`;\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const key = `o${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[key] = outbound;\n consolePrelude += `const fetch = globalThis.__cellsOutbound[${JSON.stringify(key)}];\\n`;\n }\n // `import()` the Blob URLs cannot link (a computed specifier, a module's whole name) resolves\n // against this load's modules at run time (module-registry.ts).\n const names = new Set(Object.keys(code.modules));\n const importsKey = `i${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsImports ??= {};\n const imports = g.__cellsImports as Record<string, unknown>;\n imports[importsKey] = (spec: unknown, importer: string) => {\n const name = resolveModuleName(String(spec), importer, names);\n return import(/* @vite-ignore */ name === undefined ? String(spec) : urlOf(name));\n };\n const routed = (name: string) => {\n const text = source(name);\n const out = routeDynamicImports(text, name);\n return out === undefined\n ? text\n : prefixModule(\n out,\n `const ${IMPORT_FROM} = globalThis.__cellsImports[${JSON.stringify(importsKey)}]; `,\n );\n };\n const urls = new Map<string, string>();\n // Modules whose Blob URL is being made: a Blob URL exists only once its text (with its\n // imports' URLs) does, so modules that import each other cannot be loaded this way.\n const making: string[] = [];\n const source = (name: string) => {\n const m = code.modules[name];\n if (m === undefined) throw new Error(`Worker Loader: module \"${name}\" not found`);\n return moduleText(m, name, names);\n };\n const urlOf = (name: string): string => {\n const known = urls.get(name);\n if (known) return known;\n if (making.includes(name))\n throw new Error(\n `Worker Loader: modules import each other (${[...making.slice(making.indexOf(name)), name].join(\" → \")}); a browser realm loads each module from a Blob URL, which cannot form a cycle`,\n );\n making.push(name);\n const base = name.includes(\"/\") ? name.slice(0, name.lastIndexOf(\"/\") + 1) : \"\";\n // Only the module's own imports: the same words in a string, a template or a comment are\n // not imports (a code generator's template may well contain `from \"cloudflare:workers\"`).\n const text = rewriteModuleSpecifiers(routed(name), (spec) => {\n if (spec === \"cloudflare:workers\") return shimUrl;\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\"))\n return urlOf(new URL(spec, `file:///${base}`).pathname.slice(1));\n return undefined;\n });\n const url = URL.createObjectURL(\n new Blob([consolePrelude + text], { type: \"text/javascript\" }),\n );\n urls.set(name, url);\n making.pop();\n return url;\n };\n const module = (await import(/* @vite-ignore */ urlOf(code.mainModule))) as Record<\n string,\n unknown\n >;\n scope?.bind({ env, exports: ctxExports(module, env) });\n return module;\n };\n}\n"]}
|
|
@@ -10,3 +10,12 @@ export declare class WorkflowEntrypoint<Env = unknown> {
|
|
|
10
10
|
constructor(ctx: unknown, env: Env);
|
|
11
11
|
}
|
|
12
12
|
export { RpcTarget } from "../core/durable-object.js";
|
|
13
|
+
/** Where an isolate's runtime installs what `abortIsolate` does there (src/isolate/isolate.ts). */
|
|
14
|
+
export declare const ABORT_ISOLATE: unique symbol;
|
|
15
|
+
/**
|
|
16
|
+
* workerd's `abortIsolate(reason)`: ends the isolate the calling code runs in, and never returns.
|
|
17
|
+
* In a loaded Worker's isolate, the host terminates it: calls in flight reject, and the next
|
|
18
|
+
* `get()` of its id loads the code again. Elsewhere (a project's own realm, a loaded Worker in
|
|
19
|
+
* the project's realm) there is no isolate of its own to end, so the call only throws.
|
|
20
|
+
*/
|
|
21
|
+
export declare function abortIsolate(reason?: unknown): never;
|
|
@@ -13,4 +13,18 @@ export class WorkflowEntrypoint {
|
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
15
|
export { RpcTarget } from "../core/durable-object.js";
|
|
16
|
+
/** Where an isolate's runtime installs what `abortIsolate` does there (src/isolate/isolate.ts). */
|
|
17
|
+
export const ABORT_ISOLATE = Symbol.for("cellb.abort-isolate");
|
|
18
|
+
/**
|
|
19
|
+
* workerd's `abortIsolate(reason)`: ends the isolate the calling code runs in, and never returns.
|
|
20
|
+
* In a loaded Worker's isolate, the host terminates it: calls in flight reject, and the next
|
|
21
|
+
* `get()` of its id loads the code again. Elsewhere (a project's own realm, a loaded Worker in
|
|
22
|
+
* the project's realm) there is no isolate of its own to end, so the call only throws.
|
|
23
|
+
*/
|
|
24
|
+
export function abortIsolate(reason) {
|
|
25
|
+
const abort = globalThis[ABORT_ISOLATE];
|
|
26
|
+
if (abort)
|
|
27
|
+
return abort(reason);
|
|
28
|
+
throw new Error(`abortIsolate(${String(reason ?? "")}): this code runs in no isolate of its own (cellb runs only loaded Workers in isolates)`);
|
|
29
|
+
}
|
|
16
30
|
//# sourceMappingURL=cloudflare-workers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-workers.js","sourceRoot":"","sources":["../../src/project/cloudflare-workers.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE5E,2FAA2F;AAC3F,MAAM,OAAO,kBAAkB;IACnB,GAAG,CAAU;IACb,GAAG,CAAM;IACnB,YAAY,GAAY,EAAE,GAAQ;QAChC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;CACF;AAED,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * The `cloudflare:workers` module for Worker code run by cellb (mapped by the\n * bundler / webrun-modules). Exposes the classes Workers code imports.\n */\nexport { DurableObject, WorkerEntrypoint } from \"../core/durable-object.js\";\n\n/** Base class of Workflows (`class X extends WorkflowEntrypoint { run(event, step) }`). */\nexport class WorkflowEntrypoint<Env = unknown> {\n protected ctx: unknown;\n protected env: Env;\n constructor(ctx: unknown, env: Env) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\nexport { RpcTarget } from \"../core/durable-object.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"cloudflare-workers.js","sourceRoot":"","sources":["../../src/project/cloudflare-workers.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE5E,2FAA2F;AAC3F,MAAM,OAAO,kBAAkB;IACnB,GAAG,CAAU;IACb,GAAG,CAAM;IACnB,YAAY,GAAY,EAAE,GAAQ;QAChC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;CACF;AAED,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAEtD,mGAAmG;AACnG,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAE/D;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,MAAgB;IAC3C,MAAM,KAAK,GAAI,UAAkE,CAAC,aAAa,CAAC,CAAC;IACjG,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC;IAChC,MAAM,IAAI,KAAK,CACb,gBAAgB,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,yFAAyF,CAC9H,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The `cloudflare:workers` module for Worker code run by cellb (mapped by the\n * bundler / webrun-modules). Exposes the classes Workers code imports.\n */\nexport { DurableObject, WorkerEntrypoint } from \"../core/durable-object.js\";\n\n/** Base class of Workflows (`class X extends WorkflowEntrypoint { run(event, step) }`). */\nexport class WorkflowEntrypoint<Env = unknown> {\n protected ctx: unknown;\n protected env: Env;\n constructor(ctx: unknown, env: Env) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\nexport { RpcTarget } from \"../core/durable-object.js\";\n\n/** Where an isolate's runtime installs what `abortIsolate` does there (src/isolate/isolate.ts). */\nexport const ABORT_ISOLATE = Symbol.for(\"cellb.abort-isolate\");\n\n/**\n * workerd's `abortIsolate(reason)`: ends the isolate the calling code runs in, and never returns.\n * In a loaded Worker's isolate, the host terminates it: calls in flight reject, and the next\n * `get()` of its id loads the code again. Elsewhere (a project's own realm, a loaded Worker in\n * the project's realm) there is no isolate of its own to end, so the call only throws.\n */\nexport function abortIsolate(reason?: unknown): never {\n const abort = (globalThis as Record<symbol, ((r: unknown) => never) | undefined>)[ABORT_ISOLATE];\n if (abort) return abort(reason);\n throw new Error(\n `abortIsolate(${String(reason ?? \"\")}): this code runs in no isolate of its own (cellb runs only loaded Workers in isolates)`,\n );\n}\n"]}
|
|
@@ -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,IAA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AAE,CAAC,CAAC;oBAClE,QAAQ,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,EA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AC,CAAC,CAAC,IAAI,CAAC,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;
|