@statewalker/cellb 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -6
- package/dist/adapters/ltx-vfs.js +26 -4
- package/dist/adapters/ltx-vfs.js.map +1 -1
- package/dist/browser.d.ts +4 -0
- package/dist/browser.js +2 -0
- package/dist/browser.js.map +1 -1
- package/dist/bundle.d.ts +2 -0
- package/dist/bundle.js +5 -0
- package/dist/bundle.js.map +1 -0
- package/dist/core/object-host.d.ts +7 -0
- package/dist/core/object-host.js +40 -7
- package/dist/core/object-host.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ltx/files-rpc.d.ts +30 -0
- package/dist/ltx/files-rpc.js +129 -0
- package/dist/ltx/files-rpc.js.map +1 -0
- package/dist/ltx/ltx-host.d.ts +63 -0
- package/dist/ltx/ltx-host.js +46 -0
- package/dist/ltx/ltx-host.js.map +1 -0
- package/dist/ltx/ltx-page-server.d.ts +42 -1
- package/dist/ltx/ltx-page-server.js +101 -21
- package/dist/ltx/ltx-page-server.js.map +1 -1
- package/dist/ltx/ltx-pages.d.ts +5 -0
- package/dist/ltx/ltx-pages.js +32 -3
- package/dist/ltx/ltx-pages.js.map +1 -1
- package/dist/ltx/ltx-store-worker.js +35 -22
- package/dist/ltx/ltx-store-worker.js.map +1 -1
- package/dist/node-compat/browser-registry.d.ts +1 -0
- package/dist/node-compat/browser-registry.js +5 -0
- package/dist/node-compat/browser-registry.js.map +1 -1
- package/dist/node-compat/util-guard.d.ts +2 -0
- package/dist/node-compat/util-guard.js +14 -0
- package/dist/node-compat/util-guard.js.map +1 -0
- package/dist/project/browser-host.d.ts +32 -3
- package/dist/project/browser-host.js +47 -20
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/browser-load.d.ts +16 -4
- package/dist/project/browser-load.js +46 -9
- package/dist/project/browser-load.js.map +1 -1
- package/dist/project/build.js +2 -2
- package/dist/project/build.js.map +1 -1
- package/dist/project/bundle-compiler.d.ts +31 -0
- package/dist/project/bundle-compiler.js +73 -0
- package/dist/project/bundle-compiler.js.map +1 -0
- package/dist/project/node-project.js +3 -3
- package/dist/project/node-project.js.map +1 -1
- package/dist/project/site-compiler.d.ts +67 -0
- package/dist/project/site-compiler.js +134 -0
- package/dist/project/site-compiler.js.map +1 -0
- package/dist/project/source-project.d.ts +46 -0
- package/dist/project/source-project.js +45 -0
- package/dist/project/source-project.js.map +1 -0
- package/dist/project/wrangler.d.ts +4 -0
- package/dist/project/wrangler.js +7 -1
- package/dist/project/wrangler.js.map +1 -1
- package/dist/site.d.ts +2 -0
- package/dist/site.js +4 -3
- package/dist/site.js.map +1 -1
- package/package.json +11 -1
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { HostedSiteBuilder } from "@statewalker/webrun-site-host";
|
|
2
|
+
import { linkOverPort, serveHandlerOverPort } from "../transport/port.js";
|
|
3
|
+
import { createProjectSite } from "./site.js";
|
|
4
|
+
/** The default host: a ServiceWorker registered from this realm. */
|
|
5
|
+
function serviceWorkerHost(serviceWorkerUrl) {
|
|
6
|
+
return async (handler) => {
|
|
7
|
+
if (!globalThis.navigator?.serviceWorker)
|
|
8
|
+
throw new Error("siteCompiler: this realm cannot register a ServiceWorker (a Dedicated Worker cannot): " +
|
|
9
|
+
"pass `host: siteHostOverPort(port)` and call `hostSitesForWorker(port)` in the page");
|
|
10
|
+
const builder = new HostedSiteBuilder().setHandler(handler);
|
|
11
|
+
if (serviceWorkerUrl)
|
|
12
|
+
builder.setServiceWorkerUrl(serviceWorkerUrl);
|
|
13
|
+
const site = await builder.build();
|
|
14
|
+
return { baseUrl: site.baseUrl, stop: () => site.stop() };
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A compiler for `loadProject(files, { compile })` that serves the project's modules from an
|
|
19
|
+
* in-browser HTTP server (`createProjectSite`): `main` and Worker Loader code are imported from
|
|
20
|
+
* it, so a change can rebuild one module. The site stops when the project closes.
|
|
21
|
+
*/
|
|
22
|
+
export function siteCompiler(options = {}) {
|
|
23
|
+
const host = options.host ?? serviceWorkerHost(options.serviceWorkerUrl);
|
|
24
|
+
return {
|
|
25
|
+
kind: "site",
|
|
26
|
+
async compile({ files, nodeCompat }) {
|
|
27
|
+
let nodeModules;
|
|
28
|
+
if (nodeCompat) {
|
|
29
|
+
// The served `node:*` proxies take their export names from the registry entries, which
|
|
30
|
+
// the browser host binds in this realm; the npm `util` polyfill reads `process` when it
|
|
31
|
+
// is imported.
|
|
32
|
+
(await import("../node-compat/install.js")).installNodeGlobals();
|
|
33
|
+
nodeModules = (await import("../node-compat/browser-registry.js")).nodeRegistryEntries;
|
|
34
|
+
}
|
|
35
|
+
const handler = createProjectSite({
|
|
36
|
+
projectFiles: files,
|
|
37
|
+
nodeCompat,
|
|
38
|
+
nodeModules,
|
|
39
|
+
lowerAwait: options.lowerAwait,
|
|
40
|
+
});
|
|
41
|
+
const site = await host(handler);
|
|
42
|
+
const baseUrl = site.baseUrl.endsWith("/") ? site.baseUrl : `${site.baseUrl}/`;
|
|
43
|
+
return { code: { site: baseUrl }, close: () => site.stop() };
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const HOST_SITE = "cellb:host-site";
|
|
48
|
+
const STOP_SITE = "cellb:stop-site";
|
|
49
|
+
/** The next message on `port`, or `{ error }` after `timeoutMs` (a page that never answers). */
|
|
50
|
+
const once = (port, timeoutMs) => new Promise((resolve) => {
|
|
51
|
+
const timer = setTimeout(() => resolve({ error: `no answer in ${timeoutMs} ms (does the page run hostSitesForWorker?)` }), timeoutMs);
|
|
52
|
+
port.onmessage = (e) => {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
resolve(e.data);
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Worker side: hosts each site through the page at the other end of `control`, which runs
|
|
59
|
+
* `hostSitesForWorker`. The handler stays in this worker; the page's ServiceWorker forwards each
|
|
60
|
+
* request to it.
|
|
61
|
+
*/
|
|
62
|
+
export function siteHostOverPort(control,
|
|
63
|
+
/**
|
|
64
|
+
* How long the page may take to host the site (default 30 s; a ServiceWorker's first install
|
|
65
|
+
* can be slow), and to confirm it stopped one (default 2 s; the worker stops serving anyway).
|
|
66
|
+
*/
|
|
67
|
+
{ timeoutMs = 30_000, stopTimeoutMs = 2_000, } = {}) {
|
|
68
|
+
return async (handler) => {
|
|
69
|
+
const link = new MessageChannel();
|
|
70
|
+
const reply = new MessageChannel();
|
|
71
|
+
const stopServing = await serveHandlerOverPort(link.port1, handler);
|
|
72
|
+
const answered = once(reply.port1, timeoutMs);
|
|
73
|
+
const request = { type: HOST_SITE, link: link.port2, reply: reply.port2 };
|
|
74
|
+
control.postMessage(request, [link.port2, reply.port2]);
|
|
75
|
+
const { baseUrl, error } = await answered;
|
|
76
|
+
if (!baseUrl) {
|
|
77
|
+
// A page that hosts the site after all finds this stop waiting for it, and takes the site
|
|
78
|
+
// down (its port stays open for that).
|
|
79
|
+
reply.port1.onmessage = null;
|
|
80
|
+
reply.port1.postMessage({ type: STOP_SITE });
|
|
81
|
+
await stopServing();
|
|
82
|
+
throw new Error(`the page did not host the site: ${error}`);
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
baseUrl,
|
|
86
|
+
stop: async () => {
|
|
87
|
+
// A page that does not answer stops nothing: the worker stops serving all the same.
|
|
88
|
+
const stopped = once(reply.port1, stopTimeoutMs);
|
|
89
|
+
reply.port1.postMessage({ type: STOP_SITE });
|
|
90
|
+
await stopped;
|
|
91
|
+
reply.port1.close();
|
|
92
|
+
await stopServing();
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Page side: hosts in this page's ServiceWorker the sites a worker asks for over `control`
|
|
99
|
+
* (`siteHostOverPort`). Returns a function that stops listening; the sites stop when the worker
|
|
100
|
+
* stops them.
|
|
101
|
+
*/
|
|
102
|
+
export function hostSitesForWorker(control, options = {}) {
|
|
103
|
+
const listener = async (e) => {
|
|
104
|
+
const req = e.data;
|
|
105
|
+
if (req?.type !== HOST_SITE)
|
|
106
|
+
return;
|
|
107
|
+
try {
|
|
108
|
+
// The worker may give up waiting (`timeoutMs`) and ask to stop before the site is up: the
|
|
109
|
+
// stop then waits on `reply` until the handler below reads it.
|
|
110
|
+
const link = await linkOverPort(req.link);
|
|
111
|
+
const builder = new HostedSiteBuilder().setHandler(link.send);
|
|
112
|
+
if (options.serviceWorkerUrl)
|
|
113
|
+
builder.setServiceWorkerUrl(options.serviceWorkerUrl);
|
|
114
|
+
const site = await builder.build();
|
|
115
|
+
req.reply.onmessage = async (m) => {
|
|
116
|
+
if (m.data?.type !== STOP_SITE)
|
|
117
|
+
return;
|
|
118
|
+
await site.stop().catch(() => { });
|
|
119
|
+
await link.close().catch(() => { });
|
|
120
|
+
req.reply.postMessage({ stopped: true });
|
|
121
|
+
req.reply.close();
|
|
122
|
+
};
|
|
123
|
+
req.reply.postMessage({ baseUrl: site.baseUrl });
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
req.reply.postMessage({ error: String(err?.message ?? err) });
|
|
127
|
+
req.reply.close();
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
control.addEventListener("message", listener);
|
|
131
|
+
control.start?.();
|
|
132
|
+
return () => control.removeEventListener("message", listener);
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=site-compiler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"site-compiler.js","sourceRoot":"","sources":["../../src/project/site-compiler.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAA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E,MAAM,CAAE,GAAa,EAAE,OAAO,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;YACzE,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;IACH,CAAC,CAAC;IACF,OAAO,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC7C,OAAkC,CAAC,KAAK,EAAE,EAAE,CAAC;IAC9C,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * `siteCompiler`: a project's sources served by an in-browser HTTP server (`createProjectSite`,\n * hosted in a ServiceWorker by webrun-site-host), for `loadProject(files, { compile })`. Modules\n * are compiled one by one as the browser imports them; nothing is bundled.\n *\n * `loadProject` runs in a Dedicated Worker, which cannot register a ServiceWorker: the site is\n * hosted by a page. `siteHostOverPort` (worker) and `hostSitesForWorker` (page) do that over a\n * MessagePort: the worker serves the site's handler, the page mounts it in its ServiceWorker.\n */\nimport type { SiteHandler } from \"@statewalker/webrun-site-builder\";\nimport { HostedSiteBuilder } from \"@statewalker/webrun-site-host\";\nimport { linkOverPort, serveHandlerOverPort } from \"../transport/port.js\";\nimport { createProjectSite } from \"./site.js\";\nimport type { ProjectCompiler } from \"./source-project.js\";\n\n/** A site, hosted: its base URL (ending in \"/\") and how to take it down. */\nexport interface HostedProjectSite {\n baseUrl: string;\n stop(): Promise<void>;\n}\n\n/** Hosts a site handler where this realm's code can `import()` from it. */\nexport type SiteHost = (handler: SiteHandler) => Promise<HostedProjectSite>;\n\nexport interface SiteCompilerOptions {\n /**\n * Where the site is hosted. Default: a ServiceWorker this realm registers (`HostedSiteBuilder`),\n * which a page can do and a Dedicated Worker cannot; in a worker, pass `siteHostOverPort(port)`\n * and call `hostSitesForWorker(port)` in the page.\n */\n host?: SiteHost;\n /** The ServiceWorker script for the default host (default: `/sw-worker.js`). */\n serviceWorkerUrl?: string;\n /** `createProjectSite`'s `lowerAwait` (default: with nodejs_compat, unless AsyncContext). */\n lowerAwait?: boolean;\n}\n\n/** The default host: a ServiceWorker registered from this realm. */\nfunction serviceWorkerHost(serviceWorkerUrl?: string): SiteHost {\n return async (handler) => {\n if (!(globalThis as { navigator?: { serviceWorker?: unknown } }).navigator?.serviceWorker)\n throw new Error(\n \"siteCompiler: this realm cannot register a ServiceWorker (a Dedicated Worker cannot): \" +\n \"pass `host: siteHostOverPort(port)` and call `hostSitesForWorker(port)` in the page\",\n );\n const builder = new HostedSiteBuilder().setHandler(handler);\n if (serviceWorkerUrl) builder.setServiceWorkerUrl(serviceWorkerUrl);\n const site = await builder.build();\n return { baseUrl: site.baseUrl, stop: () => site.stop() };\n };\n}\n\n/**\n * A compiler for `loadProject(files, { compile })` that serves the project's modules from an\n * in-browser HTTP server (`createProjectSite`): `main` and Worker Loader code are imported from\n * it, so a change can rebuild one module. The site stops when the project closes.\n */\nexport function siteCompiler(options: SiteCompilerOptions = {}): ProjectCompiler {\n const host = options.host ?? serviceWorkerHost(options.serviceWorkerUrl);\n return {\n kind: \"site\",\n async compile({ files, nodeCompat }) {\n let nodeModules: Record<string, unknown> | undefined;\n if (nodeCompat) {\n // The served `node:*` proxies take their export names from the registry entries, which\n // the browser host binds in this realm; the npm `util` polyfill reads `process` when it\n // is imported.\n (await import(\"../node-compat/install.js\")).installNodeGlobals();\n nodeModules = (await import(\"../node-compat/browser-registry.js\")).nodeRegistryEntries;\n }\n const handler = createProjectSite({\n projectFiles: files,\n nodeCompat,\n nodeModules,\n lowerAwait: options.lowerAwait,\n });\n const site = await host(handler);\n const baseUrl = site.baseUrl.endsWith(\"/\") ? site.baseUrl : `${site.baseUrl}/`;\n return { code: { site: baseUrl }, close: () => site.stop() };\n },\n };\n}\n\nconst HOST_SITE = \"cellb:host-site\";\nconst STOP_SITE = \"cellb:stop-site\";\n\n/**\n * Where a worker and its page talk about sites: a MessagePort, the `Worker` (page side) or the\n * worker's own scope (`self`). Other messages on it are left alone.\n */\nexport interface SiteControl {\n postMessage(message: unknown, transfer: Transferable[]): void;\n addEventListener(type: \"message\", listener: (e: MessageEvent) => void): void;\n removeEventListener(type: \"message\", listener: (e: MessageEvent) => void): void;\n}\n\n/** What a worker asks its page for, on the control port. */\ninterface HostSiteRequest {\n type: typeof HOST_SITE;\n /** The worker serves the site's handler on this port's other end. */\n link: MessagePort;\n /** The page answers here, and the worker asks to stop here. */\n reply: MessagePort;\n}\n\n/** The next message on `port`, or `{ error }` after `timeoutMs` (a page that never answers). */\nconst once = (port: MessagePort, timeoutMs: number) =>\n new Promise<{ baseUrl?: string; error?: string }>((resolve) => {\n const timer = setTimeout(\n () =>\n resolve({ error: `no answer in ${timeoutMs} ms (does the page run hostSitesForWorker?)` }),\n timeoutMs,\n );\n port.onmessage = (e) => {\n clearTimeout(timer);\n resolve(e.data);\n };\n });\n\n/**\n * Worker side: hosts each site through the page at the other end of `control`, which runs\n * `hostSitesForWorker`. The handler stays in this worker; the page's ServiceWorker forwards each\n * request to it.\n */\nexport function siteHostOverPort(\n control: SiteControl,\n /**\n * How long the page may take to host the site (default 30 s; a ServiceWorker's first install\n * can be slow), and to confirm it stopped one (default 2 s; the worker stops serving anyway).\n */\n {\n timeoutMs = 30_000,\n stopTimeoutMs = 2_000,\n }: { timeoutMs?: number; stopTimeoutMs?: number } = {},\n): SiteHost {\n return async (handler) => {\n const link = new MessageChannel();\n const reply = new MessageChannel();\n const stopServing = await serveHandlerOverPort(link.port1, handler);\n const answered = once(reply.port1, timeoutMs);\n const request: HostSiteRequest = { type: HOST_SITE, link: link.port2, reply: reply.port2 };\n control.postMessage(request, [link.port2, reply.port2]);\n const { baseUrl, error } = await answered;\n if (!baseUrl) {\n // A page that hosts the site after all finds this stop waiting for it, and takes the site\n // down (its port stays open for that).\n reply.port1.onmessage = null;\n reply.port1.postMessage({ type: STOP_SITE });\n await stopServing();\n throw new Error(`the page did not host the site: ${error}`);\n }\n return {\n baseUrl,\n stop: async () => {\n // A page that does not answer stops nothing: the worker stops serving all the same.\n const stopped = once(reply.port1, stopTimeoutMs);\n reply.port1.postMessage({ type: STOP_SITE });\n await stopped;\n reply.port1.close();\n await stopServing();\n },\n };\n };\n}\n\n/**\n * Page side: hosts in this page's ServiceWorker the sites a worker asks for over `control`\n * (`siteHostOverPort`). Returns a function that stops listening; the sites stop when the worker\n * stops them.\n */\nexport function hostSitesForWorker(\n control: SiteControl,\n options: { serviceWorkerUrl?: string } = {},\n): () => void {\n const listener = async (e: MessageEvent) => {\n const req = e.data as HostSiteRequest | undefined;\n if (req?.type !== HOST_SITE) return;\n try {\n // The worker may give up waiting (`timeoutMs`) and ask to stop before the site is up: the\n // stop then waits on `reply` until the handler below reads it.\n const link = await linkOverPort(req.link);\n const builder = new HostedSiteBuilder().setHandler(link.send);\n if (options.serviceWorkerUrl) builder.setServiceWorkerUrl(options.serviceWorkerUrl);\n const site = await builder.build();\n req.reply.onmessage = async (m) => {\n if ((m.data as { type?: string })?.type !== STOP_SITE) return;\n await site.stop().catch(() => {});\n await link.close().catch(() => {});\n req.reply.postMessage({ stopped: true });\n req.reply.close();\n };\n req.reply.postMessage({ baseUrl: site.baseUrl });\n } catch (err) {\n req.reply.postMessage({ error: String((err as Error)?.message ?? err) });\n req.reply.close();\n }\n };\n control.addEventListener(\"message\", listener);\n (control as { start?: () => void }).start?.();\n return () => control.removeEventListener(\"message\", listener);\n}\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A project's sources (`wrangler.jsonc`, `main`, `package.json`, assets) in a FilesApi, and the
|
|
3
|
+
* compilers that turn them into code `browserProjectRuntime` runs (`loadProject`'s `compile`).
|
|
4
|
+
*
|
|
5
|
+
* Platform-neutral and free of compilers: a compiler is made by the entry point that owns it
|
|
6
|
+
* (`bundleCompiler` in `@statewalker/cellb/bundle`, `siteCompiler` in `@statewalker/cellb/site`),
|
|
7
|
+
* so a plain `loadProject` ships neither esbuild-wasm nor webrun-modules.
|
|
8
|
+
*/
|
|
9
|
+
import type { FilesApi } from "@statewalker/webrun-files";
|
|
10
|
+
import type { AssetFiles } from "../bindings/assets.js";
|
|
11
|
+
import { hasNodeCompat, WRANGLER_FILES, type WranglerConfig } from "./wrangler.js";
|
|
12
|
+
export { hasNodeCompat, WRANGLER_FILES };
|
|
13
|
+
/** A source project read from a FilesApi: what a compiler needs besides the files. */
|
|
14
|
+
export interface SourceProject {
|
|
15
|
+
config: WranglerConfig;
|
|
16
|
+
/** The files of `assets.directory` ("/index.html" → bytes), or undefined without assets. */
|
|
17
|
+
assets?: AssetFiles;
|
|
18
|
+
}
|
|
19
|
+
/** What a compiler gives `browserProjectRuntime`: the project's code, and what to stop after. */
|
|
20
|
+
export interface CompiledProject {
|
|
21
|
+
/** `browserProjectRuntime`'s `code`. */
|
|
22
|
+
code: {
|
|
23
|
+
bundle: string | null;
|
|
24
|
+
} | {
|
|
25
|
+
site: string;
|
|
26
|
+
};
|
|
27
|
+
/** Releases what the compiler holds (a site's ServiceWorker registration); after `close()`. */
|
|
28
|
+
close?(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
/** Turns a source project into code for `browserProjectRuntime` (`loadProject`'s `compile`). */
|
|
31
|
+
export interface ProjectCompiler {
|
|
32
|
+
/** A name for messages ("bundle", "site"). */
|
|
33
|
+
readonly kind: string;
|
|
34
|
+
compile(project: {
|
|
35
|
+
/** The project's files, its configuration at the root. */
|
|
36
|
+
files: FilesApi;
|
|
37
|
+
config: WranglerConfig;
|
|
38
|
+
/** Whether the project has `nodejs_compat` (or a `nodejs_compat_*` flag). */
|
|
39
|
+
nodeCompat: boolean;
|
|
40
|
+
}): Promise<CompiledProject>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Reads a source folder at the root of `files`: its `wrangler.jsonc` (or `wrangler.json`) and the
|
|
44
|
+
* files of its `assets.directory`. Undefined when there is no configuration.
|
|
45
|
+
*/
|
|
46
|
+
export declare function readSourceProject(files: FilesApi): Promise<SourceProject | undefined>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { filesApiReader, readJson } from "./built-project.js";
|
|
2
|
+
import { hasNodeCompat, WRANGLER_FILES } from "./wrangler.js";
|
|
3
|
+
export { hasNodeCompat, WRANGLER_FILES };
|
|
4
|
+
/**
|
|
5
|
+
* Reads a source folder at the root of `files`: its `wrangler.jsonc` (or `wrangler.json`) and the
|
|
6
|
+
* files of its `assets.directory`. Undefined when there is no configuration.
|
|
7
|
+
*/
|
|
8
|
+
export async function readSourceProject(files) {
|
|
9
|
+
const reader = filesApiReader(files);
|
|
10
|
+
let config;
|
|
11
|
+
for (const name of WRANGLER_FILES) {
|
|
12
|
+
config = await readJson(reader, name);
|
|
13
|
+
if (config)
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
if (!config)
|
|
17
|
+
return undefined;
|
|
18
|
+
if (!config.main && !config.assets)
|
|
19
|
+
throw new Error("wrangler config has neither `main` nor `assets`");
|
|
20
|
+
if (!config.assets?.directory)
|
|
21
|
+
return { config };
|
|
22
|
+
const dir = folderPath(config.assets.directory);
|
|
23
|
+
const paths = await reader.list(dir || "/");
|
|
24
|
+
const assets = new Map();
|
|
25
|
+
await Promise.all(paths.map(async (path) => {
|
|
26
|
+
const bytes = await reader.bytes(`${dir}${path}`);
|
|
27
|
+
if (bytes)
|
|
28
|
+
assets.set(path, bytes);
|
|
29
|
+
}));
|
|
30
|
+
return { config, assets };
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A folder of the project as a path from its root, "" for the root itself: "./public/" →
|
|
34
|
+
* "/public", "." → "", "a/../b" → "/b" (as `path.resolve` takes `assets.directory` on Node).
|
|
35
|
+
*/
|
|
36
|
+
function folderPath(dir) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
for (const part of dir.split("/"))
|
|
39
|
+
if (part === "..")
|
|
40
|
+
parts.pop();
|
|
41
|
+
else if (part && part !== ".")
|
|
42
|
+
parts.push(part);
|
|
43
|
+
return parts.map((p) => `/${p}`).join("");
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=source-project.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source-project.js","sourceRoot":"","sources":["../../src/project/source-project.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAuB,MAAM,eAAe,CAAC;AAEnF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,CAAC;AA8BzC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,KAAe;IACrD,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IACrC,IAAI,MAAkC,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,cAAc,EAAE,CAAC;QAClC,MAAM,GAAG,MAAM,QAAQ,CAAiB,MAAM,EAAE,IAAI,CAAC,CAAC;QACtD,IAAI,MAAM;YAAE,MAAM;IACpB,CAAC;IACD,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAC;IAC9B,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM;QAChC,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACjD,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,MAAO,MAAM,CAAC,IAAwC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;IACjF,MAAM,MAAM,GAAe,IAAI,GAAG,EAAE,CAAC;IACrC,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QACvB,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,GAAG,GAAG,GAAG,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,KAAK;YAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC5B,CAAC;AAED;;;GAGG;AACH,SAAS,UAAU,CAAC,GAAW;IAC7B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC;QAC/B,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;aAC1B,IAAI,IAAI,IAAI,IAAI,KAAK,GAAG;YAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClD,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["/**\n * A project's sources (`wrangler.jsonc`, `main`, `package.json`, assets) in a FilesApi, and the\n * compilers that turn them into code `browserProjectRuntime` runs (`loadProject`'s `compile`).\n *\n * Platform-neutral and free of compilers: a compiler is made by the entry point that owns it\n * (`bundleCompiler` in `@statewalker/cellb/bundle`, `siteCompiler` in `@statewalker/cellb/site`),\n * so a plain `loadProject` ships neither esbuild-wasm nor webrun-modules.\n */\nimport type { FilesApi } from \"@statewalker/webrun-files\";\nimport type { AssetFiles } from \"../bindings/assets.js\";\nimport { filesApiReader, readJson } from \"./built-project.js\";\nimport { hasNodeCompat, WRANGLER_FILES, type WranglerConfig } from \"./wrangler.js\";\n\nexport { hasNodeCompat, WRANGLER_FILES };\n\n/** A source project read from a FilesApi: what a compiler needs besides the files. */\nexport interface SourceProject {\n config: WranglerConfig;\n /** The files of `assets.directory` (\"/index.html\" → bytes), or undefined without assets. */\n assets?: AssetFiles;\n}\n\n/** What a compiler gives `browserProjectRuntime`: the project's code, and what to stop after. */\nexport interface CompiledProject {\n /** `browserProjectRuntime`'s `code`. */\n code: { bundle: string | null } | { site: string };\n /** Releases what the compiler holds (a site's ServiceWorker registration); after `close()`. */\n close?(): Promise<void>;\n}\n\n/** Turns a source project into code for `browserProjectRuntime` (`loadProject`'s `compile`). */\nexport interface ProjectCompiler {\n /** A name for messages (\"bundle\", \"site\"). */\n readonly kind: string;\n compile(project: {\n /** The project's files, its configuration at the root. */\n files: FilesApi;\n config: WranglerConfig;\n /** Whether the project has `nodejs_compat` (or a `nodejs_compat_*` flag). */\n nodeCompat: boolean;\n }): Promise<CompiledProject>;\n}\n\n/**\n * Reads a source folder at the root of `files`: its `wrangler.jsonc` (or `wrangler.json`) and the\n * files of its `assets.directory`. Undefined when there is no configuration.\n */\nexport async function readSourceProject(files: FilesApi): Promise<SourceProject | undefined> {\n const reader = filesApiReader(files);\n let config: WranglerConfig | undefined;\n for (const name of WRANGLER_FILES) {\n config = await readJson<WranglerConfig>(reader, name);\n if (config) break;\n }\n if (!config) return undefined;\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n if (!config.assets?.directory) return { config };\n const dir = folderPath(config.assets.directory);\n const paths = await (reader.list as NonNullable<typeof reader.list>)(dir || \"/\");\n const assets: AssetFiles = new Map();\n await Promise.all(\n paths.map(async (path) => {\n const bytes = await reader.bytes(`${dir}${path}`);\n if (bytes) assets.set(path, bytes);\n }),\n );\n return { config, assets };\n}\n\n/**\n * A folder of the project as a path from its root, \"\" for the root itself: \"./public/\" →\n * \"/public\", \".\" → \"\", \"a/../b\" → \"/b\" (as `path.resolve` takes `assets.directory` on Node).\n */\nfunction folderPath(dir: string): string {\n const parts: string[] = [];\n for (const part of dir.split(\"/\"))\n if (part === \"..\") parts.pop();\n else if (part && part !== \".\") parts.push(part);\n return parts.map((p) => `/${p}`).join(\"\");\n}\n"]}
|
|
@@ -120,6 +120,10 @@ export declare function withResourceIds(config: WranglerConfig): WranglerConfig;
|
|
|
120
120
|
* `nodejs_compat_do_not_populate_process_env` is set. Frameworks read their settings there
|
|
121
121
|
* (EmDash's `EMDASH_SITE_URL`, for one).
|
|
122
122
|
*/
|
|
123
|
+
/** Whether `config` asks for nodejs_compat (the flag, or a `nodejs_compat_*` one). */
|
|
124
|
+
export declare function hasNodeCompat(config: WranglerConfig): boolean;
|
|
125
|
+
/** The configuration files of a project folder, in the order celld reads them. */
|
|
126
|
+
export declare const WRANGLER_FILES: string[];
|
|
123
127
|
export declare function populatesProcessEnv(config: WranglerConfig): boolean;
|
|
124
128
|
/** The text `vars` of a project, as `process.env` holds them. */
|
|
125
129
|
export declare function processEnvOf(config: WranglerConfig): Record<string, string>;
|
package/dist/project/wrangler.js
CHANGED
|
@@ -355,9 +355,15 @@ export function withResourceIds(config) {
|
|
|
355
355
|
* `nodejs_compat_do_not_populate_process_env` is set. Frameworks read their settings there
|
|
356
356
|
* (EmDash's `EMDASH_SITE_URL`, for one).
|
|
357
357
|
*/
|
|
358
|
+
/** Whether `config` asks for nodejs_compat (the flag, or a `nodejs_compat_*` one). */
|
|
359
|
+
export function hasNodeCompat(config) {
|
|
360
|
+
return (config.compatibility_flags ?? []).some((f) => f.startsWith("nodejs_compat"));
|
|
361
|
+
}
|
|
362
|
+
/** The configuration files of a project folder, in the order celld reads them. */
|
|
363
|
+
export const WRANGLER_FILES = ["wrangler.jsonc", "wrangler.json"];
|
|
358
364
|
export function populatesProcessEnv(config) {
|
|
359
365
|
const flags = config.compatibility_flags ?? [];
|
|
360
|
-
if (!
|
|
366
|
+
if (!hasNodeCompat(config))
|
|
361
367
|
return false;
|
|
362
368
|
if (flags.includes("nodejs_compat_do_not_populate_process_env"))
|
|
363
369
|
return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wrangler.js","sourceRoot":"","sources":["../../src/project/wrangler.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,YA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C,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QAAE,IAAI,OAAO,CAAC,KAAK,QAAQ;YAAE,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAC9F,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import type { FilesApi } from \"@statewalker/webrun-files\";\nimport { type AssetFiles, type AssetsConfig, createAssets } from \"../bindings/assets.js\";\nimport { celldKv } from \"../bindings/celld-kv.js\";\nimport { celldQueues, type QueueConsumerConfig } from \"../bindings/celld-queues.js\";\nimport { celldWorkflows } from \"../bindings/celld-workflows.js\";\nimport { startCronTriggers } from \"../bindings/cron.js\";\nimport { r2Bucket, r2BucketOn } from \"../bindings/r2.js\";\nimport { celldR2Backend } from \"../bindings/r2-celld.js\";\nimport { type ModuleLoader, workerLoader } from \"../bindings/worker-loader.js\";\nimport { type WorkersAiOptions, workersAi } from \"../bindings/workers-ai.js\";\nimport { entrypointStub } from \"../core/handles.js\";\nimport type { DurableObjectNamespace } from \"../core/namespace.js\";\nimport {\n type CellRuntime,\n type CellRuntimeOptions,\n createCellRuntime,\n type WorkerModule,\n} from \"../core/runtime.js\";\nimport { splitSqlStatements } from \"../core/sql-split.js\";\nimport { filesApiBlobService } from \"../miniflare-compat/blob-service.js\";\nimport { simulatorFetcher } from \"../miniflare-compat/simulator-fetcher.js\";\nimport { D1DatabaseObject, makeD1Binding } from \"../miniflare-compat/vendored.js\";\nimport { systemClock } from \"../ports.js\";\n\n/** The subset of wrangler.json(c) that celld deploys (and cellb reads). */\nexport interface WranglerConfig {\n name?: string;\n main?: string;\n compatibility_date?: string;\n compatibility_flags?: string[];\n vars?: Record<string, unknown>;\n durable_objects?: { bindings?: { name: string; class_name: string; script_name?: string }[] };\n migrations?: {\n tag: string;\n new_sqlite_classes?: string[];\n new_classes?: string[];\n renamed_classes?: { from: string; to: string }[];\n deleted_classes?: string[];\n }[];\n kv_namespaces?: { binding: string; id?: string }[];\n d1_databases?: { binding: string; database_name?: string; database_id?: string }[];\n r2_buckets?: { binding: string; bucket_name: string }[];\n queues?: {\n producers?: { binding: string; queue: string; delivery_delay?: number }[];\n consumers?: QueueConsumerConfig[];\n };\n workflows?: WorkflowConfig[];\n triggers?: { crons?: string[] };\n assets?: AssetsConfig;\n services?: { binding: string; service: string; entrypoint?: string; props?: unknown }[];\n worker_loaders?: { binding: string }[];\n /** Workers AI: served by the host's OpenAI-compatible endpoint (`ProjectHost.ai`), if any. */\n ai?: { binding: string };\n /** Containers (celld runs them with Docker or Podman): not supported, reported. */\n containers?: { class_name: string; image?: string }[];\n}\n\n/** wrangler `workflows` entries. */\nexport interface WorkflowConfig {\n binding: string;\n name: string;\n class_name: string;\n}\n\n/** Runs the Worker's `queue(batch, env, ctx)` handler for a batch celld's queue cell leased. */\ninterface QueueDispatcher {\n deliver(batch: unknown): Promise<void>;\n}\n\nexport interface ProjectHost\n extends Pick<CellRuntimeOptions, \"openSql\" | \"storage\" | \"clock\" | \"peers\" | \"route\"> {\n /** Files of `assets.directory` (path \"/a/b.html\" → bytes), loaded by the host. */\n assetFiles?: AssetFiles;\n /** Runs each loaded Worker in its own realm (celld isolates); classes still use `loadModules`. */\n isolatedModules?: ModuleLoader;\n /** Compiles code given to a Worker Loader binding (esbuild on Node, webrun-modules in browsers). */\n loadModules?: ModuleLoader;\n /** Blob store of the KV simulator (large values): OPFS in a browser, a directory or S3 on a server. */\n files: FilesApi;\n /** The OpenAI-compatible endpoint behind the `ai` binding; without it the binding is unsupported. */\n ai?: WorkersAiOptions;\n}\n\nexport interface ProjectRuntime {\n runtime: CellRuntime;\n /** Configuration entries cellb does not support yet (reported, not silently ignored). */\n unsupported: string[];\n}\n\n/**\n * What `env` of `cloudflare:workers` holds while the Worker's module is evaluated, before the\n * runtime exists: the vars, and the bindings that need no runtime (`ai`; Flue's entry reads\n * `env.AI` at load).\n */\nexport function loadTimeEnv(\n config: WranglerConfig,\n ai?: WorkersAiOptions,\n): Record<string, unknown> {\n const env: Record<string, unknown> = { ...config.vars };\n if (config.ai && ai) env[config.ai.binding] = workersAi(ai);\n return env;\n}\n\n// Internal bindings carrying the runtime-supplied objects behind KV and D1.\nconst KV_OBJECTS = \"__CELLS_KV_OBJECTS\";\nconst D1_OBJECTS = \"__CELLS_D1_OBJECTS\";\nconst QUEUE_OBJECTS = \"__CELLS_QUEUE_OBJECTS\";\nconst WORKFLOW_OBJECTS = \"__CELLS_WORKFLOW_OBJECTS\";\n\n/**\n * Builds a runtime from a wrangler config and the Worker's module namespace — the same\n * inputs celld deploys. Hosts differ only in `host` (storage) and in how they load `main`.\n */\nexport function createProjectRuntime(\n config: WranglerConfig,\n module: WorkerModule,\n host: ProjectHost,\n): ProjectRuntime {\n config = withResourceIds(config);\n const unsupported: string[] = [];\n const durableObjects: NonNullable<CellRuntimeOptions[\"durableObjects\"]> = {};\n const sqliteClasses = new Set<string>();\n for (const m of config.migrations ?? []) {\n for (const c of m.new_sqlite_classes ?? []) sqliteClasses.add(c);\n for (const c of m.new_classes ?? []) sqliteClasses.add(c); // KV-backed on Cloudflare; SQLite here (superset)\n for (const r of m.renamed_classes ?? [])\n unsupported.push(`migrations.renamed_classes (${r.from} → ${r.to})`);\n }\n for (const c of config.containers ?? [])\n unsupported.push(`containers[${c.class_name}] (cellb runs no containers)`);\n for (const b of config.durable_objects?.bindings ?? []) {\n if (b.script_name) unsupported.push(`durable_objects.bindings[${b.name}].script_name`);\n durableObjects[b.name] = { className: b.class_name };\n }\n const worker: WorkerModule = { ...module };\n let kv: ReturnType<typeof celldKv> | undefined;\n if (config.kv_namespaces?.length) {\n kv = celldKv(host.files);\n worker.__KvNamespace = kv.KvNamespaceCell as never;\n durableObjects[KV_OBJECTS] = { className: \"__KvNamespace\" };\n }\n if (config.d1_databases?.length) {\n worker.__D1Database = D1DatabaseObject;\n durableObjects[D1_OBJECTS] = { className: \"__D1Database\" };\n }\n // Queues: every queue is a cell of a runtime-supplied class (as on celld).\n const consumers = new Map((config.queues?.consumers ?? []).map((c) => [c.queue, c]));\n // celld's own queue code (vendor/celld/queues.js): its queue cell, producer and consumer\n // batch, so a queue's cell (and pending messages) is celld's format.\n let queueDispatcher: QueueDispatcher | undefined;\n let queues: ReturnType<typeof celldQueues> | undefined;\n if (config.queues?.producers?.length || consumers.size) {\n queues = celldQueues({\n namespace: () => runtime.env[QUEUE_OBJECTS] as never,\n consumers: [...consumers.values()],\n compatibilityDate: config.compatibility_date,\n runConsumer: (batch) => queueDispatcher!.deliver(batch as never),\n });\n worker.__Queue = queues.QueueCell as never;\n durableObjects[QUEUE_OBJECTS] = { className: \"__Queue\" };\n }\n // Workflows: every instance is a cell of a runtime-supplied class (as on celld).\n // celld's own workflow code (vendor/celld/workflows.js): its instance cell and binding.\n let workflows: ReturnType<typeof celldWorkflows> | undefined;\n if (config.workflows?.length) {\n workflows = celldWorkflows({\n script: config.name ?? \"worker\",\n workflows: Object.fromEntries(config.workflows.map((w) => [w.name, w.class_name])),\n exports: () => module as Record<string, unknown>,\n env: () => runtime.env,\n namespace: () => runtime.env[WORKFLOW_OBJECTS],\n });\n worker[workflows.className] = workflows.WorkflowCell as never;\n durableObjects[WORKFLOW_OBJECTS] = { className: workflows.className };\n }\n if (config.ai && !host.ai)\n unsupported.push(\n `ai[${config.ai.binding}] (Workers AI: give the host an OpenAI-compatible \\`ai\\`)`,\n );\n for (const s of config.services ?? [])\n if (s.service !== config.name)\n unsupported.push(\n `services[${s.binding}] → \"${s.service}\" (only this script's own entrypoints)`,\n );\n const sqlExtensions: string[] = [];\n let deleteAllPreservesAlarm = false;\n for (const f of config.compatibility_flags ?? []) {\n if (f === \"delete_all_preserves_alarm\") deleteAllPreservesAlarm = true;\n else if (f === \"delete_all_deletes_alarm\")\n continue; // the default\n else if (f === \"sqlite_vec\")\n sqlExtensions.push(\"sqlite_vec\"); // vec0 virtual tables, as on celld\n else if (f === \"nodejs_compat\" || f === \"nodejs_compat_v2\")\n continue; // the host's bundler maps node:*\n else if (f === \"websocket_standard_binary_type\")\n continue; // the host picks the project's WebSocketPair\n else unsupported.push(`compatibility_flags: ${f}`);\n }\n\n const runtime = createCellRuntime({\n worker,\n durableObjects,\n vars: { ...config.vars, MINIFLARE_BLOBS: filesApiBlobService(host.files) },\n openSql: host.openSql,\n sqlExtensions,\n deleteAllPreservesAlarm,\n scriptName: config.name ?? \"worker\",\n // celld's fleet-wide namespaces for the resources several scripts can share.\n namespaceKeys: {\n __KvNamespace: \"cells:v1:kv:__KvNamespace\",\n __D1Database: \"cells:v1:d1:__D1Database\",\n __Queue: \"cells:v1:queue:__Queue\",\n },\n storage: host.storage,\n clock: host.clock,\n peers: host.peers,\n route: host.route,\n });\n const env = runtime.env as Record<string, unknown>;\n if (config.ai && host.ai) env[config.ai.binding] = workersAi(host.ai);\n // KV: celld's own client against celld's own namespace cell (cell name \"<id>/<shard>\").\n for (const ns of config.kv_namespaces ?? [])\n env[ns.binding] = new kv!.KvNamespace(() => env[KV_OBJECTS], `${ns.id}/0`);\n for (const p of config.queues?.producers ?? [])\n env[p.binding] = queues!.producer(p.queue, p.delivery_delay ?? 0);\n if (consumers.size) {\n const handler = (module.default as { queue?: (b: unknown, e: unknown, c: unknown) => unknown })\n .queue;\n if (typeof handler !== \"function\")\n unsupported.push(\"queues.consumers without a queue() handler\");\n queueDispatcher = {\n deliver: async (batch) => {\n const pending: Promise<unknown>[] = [];\n await handler?.call(module.default, batch, env, {\n waitUntil: (p: Promise<unknown>) => pending.push(p),\n passThroughOnException() {},\n });\n await Promise.allSettled(pending);\n },\n };\n }\n // The isolates of loaded Workers end with the runtime (on Node, a worker thread's port would\n // keep the process alive; in a browser, a Dedicated Worker would outlive the runtime).\n const isolated = host.isolatedModules as\n | (ModuleLoader & { close?(): void | Promise<void> })\n | undefined;\n if (config.worker_loaders?.length && isolated?.close) {\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n await close();\n await isolated.close?.();\n };\n }\n for (const l of config.worker_loaders ?? []) {\n if (!host.loadModules)\n unsupported.push(`worker_loaders[${l.binding}] (the host provides no module loader)`);\n else\n env[l.binding] = host.isolatedModules\n ? workerLoader(host.isolatedModules) // facets of loaded code run in the isolate as well\n : workerLoader(host.loadModules);\n }\n // Cron Triggers (validated at load time like `celld deploy` does).\n const crons = config.triggers?.crons ?? [];\n if (crons.length) {\n const scheduled = (\n module.default as { scheduled?: (c: unknown, e: unknown, x: unknown) => unknown }\n ).scheduled;\n if (typeof scheduled !== \"function\")\n unsupported.push(\"triggers.crons without a scheduled() handler\");\n else {\n const db = host.openSql(\"__cellb/cron\");\n const stop = startCronTriggers(\n crons,\n (c, x) => runtime.runEvent(() => scheduled.call(module.default, c, env, x)),\n host.clock ?? systemClock,\n cronState(db),\n );\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n stop();\n db.close();\n await close();\n };\n }\n }\n // Static assets: routed before the Worker; `assets.binding` exposes env.ASSETS.\n if (config.assets) {\n const hasWorker = typeof (module.default as { fetch?: unknown })?.fetch === \"function\";\n if (host.assetFiles?.has(\"/.assetsignore\"))\n throw new Error(\n `${config.assets.directory ?? \"assets\"}/.assetsignore is not supported by celld; remove it`,\n );\n const assets = createAssets(host.assetFiles ?? new Map(), config.assets, hasWorker);\n if (config.assets.binding) env[config.assets.binding] = assets.binding;\n const workerFetch = runtime.fetch.bind(runtime);\n runtime.fetch = async (req) =>\n assets.route(req) ??\n (hasWorker ? workerFetch(req) : new Response(\"Not found\", { status: 404 }));\n }\n for (const w of config.workflows ?? []) env[w.binding] = workflows!.binding(w.name);\n // Service bindings to this script's own entrypoints (a celld fleet runs one application):\n // default export or a named WorkerEntrypoint, with fetch() and JS RPC.\n for (const s of config.services ?? []) {\n if (s.service !== config.name) continue;\n const target = s.entrypoint ? module[s.entrypoint] : module.default;\n if (!target)\n unsupported.push(`services[${s.binding}].entrypoint \"${s.entrypoint}\" is not exported`);\n else env[s.binding] = entrypointStub(target, env, s.props);\n }\n // R2 objects live directly in the host's store, as celld keeps them in the fleet bucket.\n // With a celld fleet bucket, R2 objects live in it as celld keeps them; else in the FilesApi.\n for (const r2 of config.r2_buckets ?? [])\n env[r2.binding] = host.storage?.objects\n ? r2BucketOn(celldR2Backend(host.storage.objects, r2.bucket_name), r2.binding)\n : r2Bucket(host.files, `/r2/${r2.bucket_name}`, r2.binding);\n for (const d1 of config.d1_databases ?? [])\n env[d1.binding] = celldExec(\n makeD1Binding({\n fetcher: simulatorFetcher(\n env[D1_OBJECTS] as DurableObjectNamespace,\n d1.database_id as string, // set by withResourceIds\n ) as never,\n }) as D1Like,\n );\n for (const name of [...sqliteClasses])\n if (!Object.values(durableObjects).some((d) => d.className === name)) {\n // A migrated class without a binding is fine (reachable through other code paths only).\n }\n return { runtime, unsupported };\n}\n\ninterface D1Like {\n exec(sql: string): Promise<{ count: number; duration: number }>;\n prepare(sql: string): { run(): Promise<unknown> };\n}\n\n/**\n * `D1Database#exec` as celld implements it: statements are split by SQL syntax.\n * workerd's d1-api.ts splits on NEWLINES (Cloudflare's documented behaviour), so a\n * multi-line `CREATE TABLE` fails there but works on celld — and celld is the\n * reference here (verified on celld 0.6.2 by the d1 example in conformance/).\n */\nfunction celldExec<T extends D1Like>(db: T): T {\n const exec = async (sql: string) => {\n const t0 = Date.now();\n const statements = splitSqlStatements(sql).filter((s) => s.trim());\n for (const statement of statements) {\n if (/^\\s*BEGIN\\b/i.test(statement))\n throw new Error(\n \"D1_EXEC_ERROR: the SQL ends in an incomplete statement, which did not run: terminate the last statement with a semicolon\",\n );\n guard(statement);\n await db.prepare(statement).run();\n }\n return { count: statements.length, duration: Date.now() - t0 };\n };\n return celldD1(db, exec) as T;\n}\n\n/**\n * celld's D1 rules on top of workerd's client (celld docs/services/d1.md, checked by the\n * d1-details project): ATTACH/DETACH and TEMP objects are \"not authorized\", VACUUM is\n * \"authorization denied\"; there is one primary and no replica, so sessions return the\n * bookmark \"celld:primary\" and every result reports served_by_primary/served_by_region\n * \"local\"; a read-only statement reports last_row_id and changes as 0.\n */\nfunction guard(sql: string): void {\n if (/^\\s*(ATTACH|DETACH)\\b/i.test(sql) || /^\\s*CREATE\\s+(TEMP|TEMPORARY)\\b/i.test(sql))\n throw new Error(\"D1_ERROR: not authorized\");\n if (/^\\s*VACUUM\\b/i.test(sql)) throw new Error(\"D1_ERROR: authorization denied\");\n}\n\nfunction celldMeta(r: any): any {\n if (!r?.meta) return r;\n r.meta.served_by_primary = true;\n r.meta.served_by_region = \"local\";\n if (r.meta.changed_db === false) {\n r.meta.last_row_id = 0;\n r.meta.changes = 0;\n }\n return r;\n}\n\nfunction celldStatement(stmt: any): any {\n return new Proxy(stmt, {\n get(t, p, r) {\n const v = Reflect.get(t, p, r);\n if (p === \"bind\") return (...a: unknown[]) => celldStatement(v.apply(t, a));\n if (p === \"run\" || p === \"all\")\n return async (...a: unknown[]) => celldMeta(await v.apply(t, a));\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\nfunction celldD1(db: any, exec?: (sql: string) => Promise<unknown>): any {\n return new Proxy(db, {\n get(t, p, r) {\n if (p === \"exec\" && exec) return exec;\n const v = Reflect.get(t, p, r);\n if (p === \"prepare\")\n return (sql: string) => {\n guard(sql);\n return celldStatement(v.call(t, sql));\n };\n if (p === \"batch\")\n return async (stmts: unknown[], ...a: unknown[]) =>\n ((await v.call(t, stmts, ...a)) as unknown[]).map(celldMeta);\n if (p === \"withSession\")\n return () => {\n const session = celldD1(t);\n return new Proxy(session, {\n get: (s, q, rr) =>\n q === \"getBookmark\" ? () => \"celld:primary\" : Reflect.get(s, q, rr),\n });\n };\n if (p === \"getBookmark\") return () => \"celld:primary\";\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\n/** Last fired occurrence per cron expression, in a small SQLite database of the host. */\nfunction cronState(db: ReturnType<ProjectHost[\"openSql\"]>) {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS cron_state (expression TEXT PRIMARY KEY, scheduled_time INTEGER)\",\n [],\n );\n return {\n get: (e: string) => {\n const row = db.exec(\"SELECT scheduled_time FROM cron_state WHERE expression = ?\", [e])\n .rows[0];\n return row ? Number(row[0]) : undefined;\n },\n set: (e: string, t: number) =>\n void db.exec(\"INSERT OR REPLACE INTO cron_state (expression, scheduled_time) VALUES (?, ?)\", [\n e,\n t,\n ]),\n };\n}\n\n/**\n * KV namespaces and D1 databases may omit their ids: wrangler provisions them on deploy, and\n * framework builds (Astro's Cloudflare adapter, for one) emit such entries. A KV namespace\n * then takes its binding name as id; a D1 database its `database_name`, else its binding name.\n * Entries with ids are kept as they are, so storage shared with celld keeps its names.\n */\nexport function withResourceIds(config: WranglerConfig): WranglerConfig {\n const kv = config.kv_namespaces;\n const d1 = config.d1_databases;\n if (!kv?.some((n) => !n.id) && !d1?.some((d) => !d.database_id)) return config;\n return {\n ...config,\n kv_namespaces: kv?.map((n) => (n.id ? n : { ...n, id: n.binding })),\n d1_databases: d1?.map((d) =>\n d.database_id ? d : { ...d, database_id: d.database_name ?? d.binding },\n ),\n };\n}\n\n/**\n * workerd fills `process.env` with the project's text `vars` under nodejs_compat from\n * compatibility date 2025-04-01 (`nodejs_compat_populate_process_env`), unless\n * `nodejs_compat_do_not_populate_process_env` is set. Frameworks read their settings there\n * (EmDash's `EMDASH_SITE_URL`, for one).\n */\nexport function populatesProcessEnv(config: WranglerConfig): boolean {\n const flags = config.compatibility_flags ?? [];\n if (!flags.some((f) => f.startsWith(\"nodejs_compat\"))) return false;\n if (flags.includes(\"nodejs_compat_do_not_populate_process_env\")) return false;\n if (flags.includes(\"nodejs_compat_populate_process_env\")) return true;\n return (config.compatibility_date ?? \"\") >= \"2025-04-01\";\n}\n\n/** The text `vars` of a project, as `process.env` holds them. */\nexport function processEnvOf(config: WranglerConfig): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [k, v] of Object.entries(config.vars ?? {})) if (typeof v === \"string\") env[k] = v;\n return env;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"wrangler.js","sourceRoot":"","sources":["../../src/project/wrangler.ts"],"names":[],"mappings":"AACA,OAAO,EAAsC,YAAY,EAAE,MA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BAAkB,IAAI,EAAE,CAAC,IAAI,YAAY,CAAC;AAC3D,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,YAAY,CAAC,MAAsB;IACjD,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QAAE,IAAI,OAAO,CAAC,KAAK,QAAQ;YAAE,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAC9F,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import type { FilesApi } from \"@statewalker/webrun-files\";\nimport { type AssetFiles, type AssetsConfig, createAssets } from \"../bindings/assets.js\";\nimport { celldKv } from \"../bindings/celld-kv.js\";\nimport { celldQueues, type QueueConsumerConfig } from \"../bindings/celld-queues.js\";\nimport { celldWorkflows } from \"../bindings/celld-workflows.js\";\nimport { startCronTriggers } from \"../bindings/cron.js\";\nimport { r2Bucket, r2BucketOn } from \"../bindings/r2.js\";\nimport { celldR2Backend } from \"../bindings/r2-celld.js\";\nimport { type ModuleLoader, workerLoader } from \"../bindings/worker-loader.js\";\nimport { type WorkersAiOptions, workersAi } from \"../bindings/workers-ai.js\";\nimport { entrypointStub } from \"../core/handles.js\";\nimport type { DurableObjectNamespace } from \"../core/namespace.js\";\nimport {\n type CellRuntime,\n type CellRuntimeOptions,\n createCellRuntime,\n type WorkerModule,\n} from \"../core/runtime.js\";\nimport { splitSqlStatements } from \"../core/sql-split.js\";\nimport { filesApiBlobService } from \"../miniflare-compat/blob-service.js\";\nimport { simulatorFetcher } from \"../miniflare-compat/simulator-fetcher.js\";\nimport { D1DatabaseObject, makeD1Binding } from \"../miniflare-compat/vendored.js\";\nimport { systemClock } from \"../ports.js\";\n\n/** The subset of wrangler.json(c) that celld deploys (and cellb reads). */\nexport interface WranglerConfig {\n name?: string;\n main?: string;\n compatibility_date?: string;\n compatibility_flags?: string[];\n vars?: Record<string, unknown>;\n durable_objects?: { bindings?: { name: string; class_name: string; script_name?: string }[] };\n migrations?: {\n tag: string;\n new_sqlite_classes?: string[];\n new_classes?: string[];\n renamed_classes?: { from: string; to: string }[];\n deleted_classes?: string[];\n }[];\n kv_namespaces?: { binding: string; id?: string }[];\n d1_databases?: { binding: string; database_name?: string; database_id?: string }[];\n r2_buckets?: { binding: string; bucket_name: string }[];\n queues?: {\n producers?: { binding: string; queue: string; delivery_delay?: number }[];\n consumers?: QueueConsumerConfig[];\n };\n workflows?: WorkflowConfig[];\n triggers?: { crons?: string[] };\n assets?: AssetsConfig;\n services?: { binding: string; service: string; entrypoint?: string; props?: unknown }[];\n worker_loaders?: { binding: string }[];\n /** Workers AI: served by the host's OpenAI-compatible endpoint (`ProjectHost.ai`), if any. */\n ai?: { binding: string };\n /** Containers (celld runs them with Docker or Podman): not supported, reported. */\n containers?: { class_name: string; image?: string }[];\n}\n\n/** wrangler `workflows` entries. */\nexport interface WorkflowConfig {\n binding: string;\n name: string;\n class_name: string;\n}\n\n/** Runs the Worker's `queue(batch, env, ctx)` handler for a batch celld's queue cell leased. */\ninterface QueueDispatcher {\n deliver(batch: unknown): Promise<void>;\n}\n\nexport interface ProjectHost\n extends Pick<CellRuntimeOptions, \"openSql\" | \"storage\" | \"clock\" | \"peers\" | \"route\"> {\n /** Files of `assets.directory` (path \"/a/b.html\" → bytes), loaded by the host. */\n assetFiles?: AssetFiles;\n /** Runs each loaded Worker in its own realm (celld isolates); classes still use `loadModules`. */\n isolatedModules?: ModuleLoader;\n /** Compiles code given to a Worker Loader binding (esbuild on Node, webrun-modules in browsers). */\n loadModules?: ModuleLoader;\n /** Blob store of the KV simulator (large values): OPFS in a browser, a directory or S3 on a server. */\n files: FilesApi;\n /** The OpenAI-compatible endpoint behind the `ai` binding; without it the binding is unsupported. */\n ai?: WorkersAiOptions;\n}\n\nexport interface ProjectRuntime {\n runtime: CellRuntime;\n /** Configuration entries cellb does not support yet (reported, not silently ignored). */\n unsupported: string[];\n}\n\n/**\n * What `env` of `cloudflare:workers` holds while the Worker's module is evaluated, before the\n * runtime exists: the vars, and the bindings that need no runtime (`ai`; Flue's entry reads\n * `env.AI` at load).\n */\nexport function loadTimeEnv(\n config: WranglerConfig,\n ai?: WorkersAiOptions,\n): Record<string, unknown> {\n const env: Record<string, unknown> = { ...config.vars };\n if (config.ai && ai) env[config.ai.binding] = workersAi(ai);\n return env;\n}\n\n// Internal bindings carrying the runtime-supplied objects behind KV and D1.\nconst KV_OBJECTS = \"__CELLS_KV_OBJECTS\";\nconst D1_OBJECTS = \"__CELLS_D1_OBJECTS\";\nconst QUEUE_OBJECTS = \"__CELLS_QUEUE_OBJECTS\";\nconst WORKFLOW_OBJECTS = \"__CELLS_WORKFLOW_OBJECTS\";\n\n/**\n * Builds a runtime from a wrangler config and the Worker's module namespace — the same\n * inputs celld deploys. Hosts differ only in `host` (storage) and in how they load `main`.\n */\nexport function createProjectRuntime(\n config: WranglerConfig,\n module: WorkerModule,\n host: ProjectHost,\n): ProjectRuntime {\n config = withResourceIds(config);\n const unsupported: string[] = [];\n const durableObjects: NonNullable<CellRuntimeOptions[\"durableObjects\"]> = {};\n const sqliteClasses = new Set<string>();\n for (const m of config.migrations ?? []) {\n for (const c of m.new_sqlite_classes ?? []) sqliteClasses.add(c);\n for (const c of m.new_classes ?? []) sqliteClasses.add(c); // KV-backed on Cloudflare; SQLite here (superset)\n for (const r of m.renamed_classes ?? [])\n unsupported.push(`migrations.renamed_classes (${r.from} → ${r.to})`);\n }\n for (const c of config.containers ?? [])\n unsupported.push(`containers[${c.class_name}] (cellb runs no containers)`);\n for (const b of config.durable_objects?.bindings ?? []) {\n if (b.script_name) unsupported.push(`durable_objects.bindings[${b.name}].script_name`);\n durableObjects[b.name] = { className: b.class_name };\n }\n const worker: WorkerModule = { ...module };\n let kv: ReturnType<typeof celldKv> | undefined;\n if (config.kv_namespaces?.length) {\n kv = celldKv(host.files);\n worker.__KvNamespace = kv.KvNamespaceCell as never;\n durableObjects[KV_OBJECTS] = { className: \"__KvNamespace\" };\n }\n if (config.d1_databases?.length) {\n worker.__D1Database = D1DatabaseObject;\n durableObjects[D1_OBJECTS] = { className: \"__D1Database\" };\n }\n // Queues: every queue is a cell of a runtime-supplied class (as on celld).\n const consumers = new Map((config.queues?.consumers ?? []).map((c) => [c.queue, c]));\n // celld's own queue code (vendor/celld/queues.js): its queue cell, producer and consumer\n // batch, so a queue's cell (and pending messages) is celld's format.\n let queueDispatcher: QueueDispatcher | undefined;\n let queues: ReturnType<typeof celldQueues> | undefined;\n if (config.queues?.producers?.length || consumers.size) {\n queues = celldQueues({\n namespace: () => runtime.env[QUEUE_OBJECTS] as never,\n consumers: [...consumers.values()],\n compatibilityDate: config.compatibility_date,\n runConsumer: (batch) => queueDispatcher!.deliver(batch as never),\n });\n worker.__Queue = queues.QueueCell as never;\n durableObjects[QUEUE_OBJECTS] = { className: \"__Queue\" };\n }\n // Workflows: every instance is a cell of a runtime-supplied class (as on celld).\n // celld's own workflow code (vendor/celld/workflows.js): its instance cell and binding.\n let workflows: ReturnType<typeof celldWorkflows> | undefined;\n if (config.workflows?.length) {\n workflows = celldWorkflows({\n script: config.name ?? \"worker\",\n workflows: Object.fromEntries(config.workflows.map((w) => [w.name, w.class_name])),\n exports: () => module as Record<string, unknown>,\n env: () => runtime.env,\n namespace: () => runtime.env[WORKFLOW_OBJECTS],\n });\n worker[workflows.className] = workflows.WorkflowCell as never;\n durableObjects[WORKFLOW_OBJECTS] = { className: workflows.className };\n }\n if (config.ai && !host.ai)\n unsupported.push(\n `ai[${config.ai.binding}] (Workers AI: give the host an OpenAI-compatible \\`ai\\`)`,\n );\n for (const s of config.services ?? [])\n if (s.service !== config.name)\n unsupported.push(\n `services[${s.binding}] → \"${s.service}\" (only this script's own entrypoints)`,\n );\n const sqlExtensions: string[] = [];\n let deleteAllPreservesAlarm = false;\n for (const f of config.compatibility_flags ?? []) {\n if (f === \"delete_all_preserves_alarm\") deleteAllPreservesAlarm = true;\n else if (f === \"delete_all_deletes_alarm\")\n continue; // the default\n else if (f === \"sqlite_vec\")\n sqlExtensions.push(\"sqlite_vec\"); // vec0 virtual tables, as on celld\n else if (f === \"nodejs_compat\" || f === \"nodejs_compat_v2\")\n continue; // the host's bundler maps node:*\n else if (f === \"websocket_standard_binary_type\")\n continue; // the host picks the project's WebSocketPair\n else unsupported.push(`compatibility_flags: ${f}`);\n }\n\n const runtime = createCellRuntime({\n worker,\n durableObjects,\n vars: { ...config.vars, MINIFLARE_BLOBS: filesApiBlobService(host.files) },\n openSql: host.openSql,\n sqlExtensions,\n deleteAllPreservesAlarm,\n scriptName: config.name ?? \"worker\",\n // celld's fleet-wide namespaces for the resources several scripts can share.\n namespaceKeys: {\n __KvNamespace: \"cells:v1:kv:__KvNamespace\",\n __D1Database: \"cells:v1:d1:__D1Database\",\n __Queue: \"cells:v1:queue:__Queue\",\n },\n storage: host.storage,\n clock: host.clock,\n peers: host.peers,\n route: host.route,\n });\n const env = runtime.env as Record<string, unknown>;\n if (config.ai && host.ai) env[config.ai.binding] = workersAi(host.ai);\n // KV: celld's own client against celld's own namespace cell (cell name \"<id>/<shard>\").\n for (const ns of config.kv_namespaces ?? [])\n env[ns.binding] = new kv!.KvNamespace(() => env[KV_OBJECTS], `${ns.id}/0`);\n for (const p of config.queues?.producers ?? [])\n env[p.binding] = queues!.producer(p.queue, p.delivery_delay ?? 0);\n if (consumers.size) {\n const handler = (module.default as { queue?: (b: unknown, e: unknown, c: unknown) => unknown })\n .queue;\n if (typeof handler !== \"function\")\n unsupported.push(\"queues.consumers without a queue() handler\");\n queueDispatcher = {\n deliver: async (batch) => {\n const pending: Promise<unknown>[] = [];\n await handler?.call(module.default, batch, env, {\n waitUntil: (p: Promise<unknown>) => pending.push(p),\n passThroughOnException() {},\n });\n await Promise.allSettled(pending);\n },\n };\n }\n // The isolates of loaded Workers end with the runtime (on Node, a worker thread's port would\n // keep the process alive; in a browser, a Dedicated Worker would outlive the runtime).\n const isolated = host.isolatedModules as\n | (ModuleLoader & { close?(): void | Promise<void> })\n | undefined;\n if (config.worker_loaders?.length && isolated?.close) {\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n await close();\n await isolated.close?.();\n };\n }\n for (const l of config.worker_loaders ?? []) {\n if (!host.loadModules)\n unsupported.push(`worker_loaders[${l.binding}] (the host provides no module loader)`);\n else\n env[l.binding] = host.isolatedModules\n ? workerLoader(host.isolatedModules) // facets of loaded code run in the isolate as well\n : workerLoader(host.loadModules);\n }\n // Cron Triggers (validated at load time like `celld deploy` does).\n const crons = config.triggers?.crons ?? [];\n if (crons.length) {\n const scheduled = (\n module.default as { scheduled?: (c: unknown, e: unknown, x: unknown) => unknown }\n ).scheduled;\n if (typeof scheduled !== \"function\")\n unsupported.push(\"triggers.crons without a scheduled() handler\");\n else {\n const db = host.openSql(\"__cellb/cron\");\n const stop = startCronTriggers(\n crons,\n (c, x) => runtime.runEvent(() => scheduled.call(module.default, c, env, x)),\n host.clock ?? systemClock,\n cronState(db),\n );\n const close = runtime.close.bind(runtime);\n runtime.close = async () => {\n stop();\n db.close();\n await close();\n };\n }\n }\n // Static assets: routed before the Worker; `assets.binding` exposes env.ASSETS.\n if (config.assets) {\n const hasWorker = typeof (module.default as { fetch?: unknown })?.fetch === \"function\";\n if (host.assetFiles?.has(\"/.assetsignore\"))\n throw new Error(\n `${config.assets.directory ?? \"assets\"}/.assetsignore is not supported by celld; remove it`,\n );\n const assets = createAssets(host.assetFiles ?? new Map(), config.assets, hasWorker);\n if (config.assets.binding) env[config.assets.binding] = assets.binding;\n const workerFetch = runtime.fetch.bind(runtime);\n runtime.fetch = async (req) =>\n assets.route(req) ??\n (hasWorker ? workerFetch(req) : new Response(\"Not found\", { status: 404 }));\n }\n for (const w of config.workflows ?? []) env[w.binding] = workflows!.binding(w.name);\n // Service bindings to this script's own entrypoints (a celld fleet runs one application):\n // default export or a named WorkerEntrypoint, with fetch() and JS RPC.\n for (const s of config.services ?? []) {\n if (s.service !== config.name) continue;\n const target = s.entrypoint ? module[s.entrypoint] : module.default;\n if (!target)\n unsupported.push(`services[${s.binding}].entrypoint \"${s.entrypoint}\" is not exported`);\n else env[s.binding] = entrypointStub(target, env, s.props);\n }\n // R2 objects live directly in the host's store, as celld keeps them in the fleet bucket.\n // With a celld fleet bucket, R2 objects live in it as celld keeps them; else in the FilesApi.\n for (const r2 of config.r2_buckets ?? [])\n env[r2.binding] = host.storage?.objects\n ? r2BucketOn(celldR2Backend(host.storage.objects, r2.bucket_name), r2.binding)\n : r2Bucket(host.files, `/r2/${r2.bucket_name}`, r2.binding);\n for (const d1 of config.d1_databases ?? [])\n env[d1.binding] = celldExec(\n makeD1Binding({\n fetcher: simulatorFetcher(\n env[D1_OBJECTS] as DurableObjectNamespace,\n d1.database_id as string, // set by withResourceIds\n ) as never,\n }) as D1Like,\n );\n for (const name of [...sqliteClasses])\n if (!Object.values(durableObjects).some((d) => d.className === name)) {\n // A migrated class without a binding is fine (reachable through other code paths only).\n }\n return { runtime, unsupported };\n}\n\ninterface D1Like {\n exec(sql: string): Promise<{ count: number; duration: number }>;\n prepare(sql: string): { run(): Promise<unknown> };\n}\n\n/**\n * `D1Database#exec` as celld implements it: statements are split by SQL syntax.\n * workerd's d1-api.ts splits on NEWLINES (Cloudflare's documented behaviour), so a\n * multi-line `CREATE TABLE` fails there but works on celld — and celld is the\n * reference here (verified on celld 0.6.2 by the d1 example in conformance/).\n */\nfunction celldExec<T extends D1Like>(db: T): T {\n const exec = async (sql: string) => {\n const t0 = Date.now();\n const statements = splitSqlStatements(sql).filter((s) => s.trim());\n for (const statement of statements) {\n if (/^\\s*BEGIN\\b/i.test(statement))\n throw new Error(\n \"D1_EXEC_ERROR: the SQL ends in an incomplete statement, which did not run: terminate the last statement with a semicolon\",\n );\n guard(statement);\n await db.prepare(statement).run();\n }\n return { count: statements.length, duration: Date.now() - t0 };\n };\n return celldD1(db, exec) as T;\n}\n\n/**\n * celld's D1 rules on top of workerd's client (celld docs/services/d1.md, checked by the\n * d1-details project): ATTACH/DETACH and TEMP objects are \"not authorized\", VACUUM is\n * \"authorization denied\"; there is one primary and no replica, so sessions return the\n * bookmark \"celld:primary\" and every result reports served_by_primary/served_by_region\n * \"local\"; a read-only statement reports last_row_id and changes as 0.\n */\nfunction guard(sql: string): void {\n if (/^\\s*(ATTACH|DETACH)\\b/i.test(sql) || /^\\s*CREATE\\s+(TEMP|TEMPORARY)\\b/i.test(sql))\n throw new Error(\"D1_ERROR: not authorized\");\n if (/^\\s*VACUUM\\b/i.test(sql)) throw new Error(\"D1_ERROR: authorization denied\");\n}\n\nfunction celldMeta(r: any): any {\n if (!r?.meta) return r;\n r.meta.served_by_primary = true;\n r.meta.served_by_region = \"local\";\n if (r.meta.changed_db === false) {\n r.meta.last_row_id = 0;\n r.meta.changes = 0;\n }\n return r;\n}\n\nfunction celldStatement(stmt: any): any {\n return new Proxy(stmt, {\n get(t, p, r) {\n const v = Reflect.get(t, p, r);\n if (p === \"bind\") return (...a: unknown[]) => celldStatement(v.apply(t, a));\n if (p === \"run\" || p === \"all\")\n return async (...a: unknown[]) => celldMeta(await v.apply(t, a));\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\nfunction celldD1(db: any, exec?: (sql: string) => Promise<unknown>): any {\n return new Proxy(db, {\n get(t, p, r) {\n if (p === \"exec\" && exec) return exec;\n const v = Reflect.get(t, p, r);\n if (p === \"prepare\")\n return (sql: string) => {\n guard(sql);\n return celldStatement(v.call(t, sql));\n };\n if (p === \"batch\")\n return async (stmts: unknown[], ...a: unknown[]) =>\n ((await v.call(t, stmts, ...a)) as unknown[]).map(celldMeta);\n if (p === \"withSession\")\n return () => {\n const session = celldD1(t);\n return new Proxy(session, {\n get: (s, q, rr) =>\n q === \"getBookmark\" ? () => \"celld:primary\" : Reflect.get(s, q, rr),\n });\n };\n if (p === \"getBookmark\") return () => \"celld:primary\";\n return typeof v === \"function\" ? v.bind(t) : v;\n },\n });\n}\n\n/** Last fired occurrence per cron expression, in a small SQLite database of the host. */\nfunction cronState(db: ReturnType<ProjectHost[\"openSql\"]>) {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS cron_state (expression TEXT PRIMARY KEY, scheduled_time INTEGER)\",\n [],\n );\n return {\n get: (e: string) => {\n const row = db.exec(\"SELECT scheduled_time FROM cron_state WHERE expression = ?\", [e])\n .rows[0];\n return row ? Number(row[0]) : undefined;\n },\n set: (e: string, t: number) =>\n void db.exec(\"INSERT OR REPLACE INTO cron_state (expression, scheduled_time) VALUES (?, ?)\", [\n e,\n t,\n ]),\n };\n}\n\n/**\n * KV namespaces and D1 databases may omit their ids: wrangler provisions them on deploy, and\n * framework builds (Astro's Cloudflare adapter, for one) emit such entries. A KV namespace\n * then takes its binding name as id; a D1 database its `database_name`, else its binding name.\n * Entries with ids are kept as they are, so storage shared with celld keeps its names.\n */\nexport function withResourceIds(config: WranglerConfig): WranglerConfig {\n const kv = config.kv_namespaces;\n const d1 = config.d1_databases;\n if (!kv?.some((n) => !n.id) && !d1?.some((d) => !d.database_id)) return config;\n return {\n ...config,\n kv_namespaces: kv?.map((n) => (n.id ? n : { ...n, id: n.binding })),\n d1_databases: d1?.map((d) =>\n d.database_id ? d : { ...d, database_id: d.database_name ?? d.binding },\n ),\n };\n}\n\n/**\n * workerd fills `process.env` with the project's text `vars` under nodejs_compat from\n * compatibility date 2025-04-01 (`nodejs_compat_populate_process_env`), unless\n * `nodejs_compat_do_not_populate_process_env` is set. Frameworks read their settings there\n * (EmDash's `EMDASH_SITE_URL`, for one).\n */\n/** Whether `config` asks for nodejs_compat (the flag, or a `nodejs_compat_*` one). */\nexport function hasNodeCompat(config: WranglerConfig): boolean {\n return (config.compatibility_flags ?? []).some((f) => f.startsWith(\"nodejs_compat\"));\n}\n\n/** The configuration files of a project folder, in the order celld reads them. */\nexport const WRANGLER_FILES = [\"wrangler.jsonc\", \"wrangler.json\"];\n\nexport function populatesProcessEnv(config: WranglerConfig): boolean {\n const flags = config.compatibility_flags ?? [];\n if (!hasNodeCompat(config)) return false;\n if (flags.includes(\"nodejs_compat_do_not_populate_process_env\")) return false;\n if (flags.includes(\"nodejs_compat_populate_process_env\")) return true;\n return (config.compatibility_date ?? \"\") >= \"2025-04-01\";\n}\n\n/** The text `vars` of a project, as `process.env` holds them. */\nexport function processEnvOf(config: WranglerConfig): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [k, v] of Object.entries(config.vars ?? {})) if (typeof v === \"string\") env[k] = v;\n return env;\n}\n"]}
|
package/dist/site.d.ts
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
1
|
export { createProjectSite } from "./project/site.js";
|
|
2
|
+
export { type HostedProjectSite, hostSitesForWorker, type SiteCompilerOptions, type SiteControl, type SiteHost, siteCompiler, siteHostOverPort, } from "./project/site-compiler.js";
|
|
3
|
+
export type { CompiledProject, ProjectCompiler } from "./project/source-project.js";
|
package/dist/site.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @statewalker/cellb/site: a project's sources compiled and served in the browser (an in-browser
|
|
2
|
-
// HTTP server for `browserProjectRuntime({ site })
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// HTTP server for `browserProjectRuntime({ site })`, or `loadProject`'s `compile: siteCompiler()`).
|
|
3
|
+
// It needs the optional peer dependencies @statewalker/webrun-modules,
|
|
4
|
+
// @statewalker/webrun-site-builder and @statewalker/webrun-site-host (the ServiceWorker host).
|
|
5
5
|
export { createProjectSite } from "./project/site.js";
|
|
6
|
+
export { hostSitesForWorker, siteCompiler, siteHostOverPort, } from "./project/site-compiler.js";
|
|
6
7
|
//# sourceMappingURL=site.js.map
|
package/dist/site.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site.js","sourceRoot":"","sources":["../src/site.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,
|
|
1
|
+
{"version":3,"file":"site.js","sourceRoot":"","sources":["../src/site.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,oGAAoG;AACpG,uEAAuE;AACvE,+FAA+F;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAEL,kBAAkB,EAIlB,YAAY,EACZ,gBAAgB,GACjB,MAAM,4BAA4B,CAAC","sourcesContent":["// @statewalker/cellb/site: a project's sources compiled and served in the browser (an in-browser\n// HTTP server for `browserProjectRuntime({ site })`, or `loadProject`'s `compile: siteCompiler()`).\n// It needs the optional peer dependencies @statewalker/webrun-modules,\n// @statewalker/webrun-site-builder and @statewalker/webrun-site-host (the ServiceWorker host).\nexport { createProjectSite } from \"./project/site.js\";\nexport {\n type HostedProjectSite,\n hostSitesForWorker,\n type SiteCompilerOptions,\n type SiteControl,\n type SiteHost,\n siteCompiler,\n siteHostOverPort,\n} from \"./project/site-compiler.js\";\nexport type { CompiledProject, ProjectCompiler } from \"./project/source-project.js\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/cellb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "cellb: isomorphic Durable Objects runtime (celld/Cloudflare-compatible surface) for browsers and servers",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -33,6 +33,10 @@
|
|
|
33
33
|
"types": "./dist/site.d.ts",
|
|
34
34
|
"default": "./dist/site.js"
|
|
35
35
|
},
|
|
36
|
+
"./bundle": {
|
|
37
|
+
"types": "./dist/bundle.d.ts",
|
|
38
|
+
"default": "./dist/bundle.js"
|
|
39
|
+
},
|
|
36
40
|
"./host-modules": {
|
|
37
41
|
"types": "./dist/project/host-modules.d.ts",
|
|
38
42
|
"default": "./dist/project/host-modules.js"
|
|
@@ -74,12 +78,16 @@
|
|
|
74
78
|
"ws": "^8.22.0"
|
|
75
79
|
},
|
|
76
80
|
"peerDependencies": {
|
|
81
|
+
"@statewalker/webrun-bundler": "^0.1.1",
|
|
77
82
|
"@statewalker/webrun-modules": "^0.3.5",
|
|
78
83
|
"@statewalker/webrun-site-builder": "^0.2.0",
|
|
79
84
|
"@statewalker/webrun-site-host": "^0.3.0",
|
|
80
85
|
"esbuild": ">=0.25"
|
|
81
86
|
},
|
|
82
87
|
"peerDependenciesMeta": {
|
|
88
|
+
"@statewalker/webrun-bundler": {
|
|
89
|
+
"optional": true
|
|
90
|
+
},
|
|
83
91
|
"@statewalker/webrun-modules": {
|
|
84
92
|
"optional": true
|
|
85
93
|
},
|
|
@@ -96,12 +104,14 @@
|
|
|
96
104
|
"devDependencies": {
|
|
97
105
|
"@playwright/test": "^1.63.0",
|
|
98
106
|
"@sparticuz/chromium": "^153.0.0",
|
|
107
|
+
"@statewalker/webrun-bundler": "^0.1.1",
|
|
99
108
|
"@statewalker/webrun-modules": "^0.3.5",
|
|
100
109
|
"@statewalker/webrun-site-builder": "^0.2.0",
|
|
101
110
|
"@statewalker/webrun-site-host": "^0.3.0",
|
|
102
111
|
"@types/node": "^26.6.4",
|
|
103
112
|
"@types/ws": "^8.18.2",
|
|
104
113
|
"esbuild": "^0.28.0",
|
|
114
|
+
"esbuild-wasm": "0.28.2",
|
|
105
115
|
"html-rewriter-wasm": "^0.4.1",
|
|
106
116
|
"miniflare": "4.20260730.0",
|
|
107
117
|
"partyserver": "0.5.10",
|