@statewalker/cellb 0.1.1 → 0.3.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 +51 -25
- package/dist/adapters/wasm-sqlite.d.ts +11 -0
- package/dist/adapters/wasm-sqlite.js +26 -3
- package/dist/adapters/wasm-sqlite.js.map +1 -1
- package/dist/bindings/assets.js +2 -2
- package/dist/bindings/assets.js.map +1 -1
- package/dist/bindings/r2.js +2 -2
- package/dist/bindings/r2.js.map +1 -1
- package/dist/browser.d.ts +0 -1
- package/dist/browser.js +0 -1
- package/dist/browser.js.map +1 -1
- package/dist/bucket/celld-cells.js +1 -1
- package/dist/bucket/celld-cells.js.map +1 -1
- package/dist/bucket/s3-object-store.js +1 -1
- package/dist/bucket/s3-object-store.js.map +1 -1
- package/dist/core/handles.d.ts +5 -2
- package/dist/core/handles.js +12 -1
- package/dist/core/handles.js.map +1 -1
- package/dist/core/id.js +3 -3
- package/dist/core/id.js.map +1 -1
- package/dist/core/namespace.d.ts +1 -1
- package/dist/core/namespace.js +2 -1
- package/dist/core/namespace.js.map +1 -1
- package/dist/core/object-host.d.ts +23 -0
- package/dist/core/object-host.js +87 -6
- package/dist/core/object-host.js.map +1 -1
- package/dist/core/runtime.d.ts +10 -0
- package/dist/core/runtime.js +43 -2
- package/dist/core/runtime.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/isolate/browser.js +1 -1
- package/dist/isolate/browser.js.map +1 -1
- package/dist/isolate/host.d.ts +5 -1
- package/dist/isolate/host.js +29 -2
- package/dist/isolate/host.js.map +1 -1
- package/dist/isolate/isolate-worker.js +11 -1
- package/dist/isolate/isolate-worker.js.map +1 -1
- package/dist/isolate/isolate.js +20 -0
- package/dist/isolate/isolate.js.map +1 -1
- package/dist/isolate/node-entry.js +11 -0
- package/dist/isolate/node-entry.js.map +1 -1
- package/dist/isolate/protocol.d.ts +5 -0
- package/dist/isolate/protocol.js +114 -2
- package/dist/isolate/protocol.js.map +1 -1
- package/dist/node-compat/crypto.js +3 -3
- package/dist/node-compat/crypto.js.map +1 -1
- package/dist/peer/celld-peer.d.ts +17 -0
- package/dist/peer/celld-peer.js +49 -7
- package/dist/peer/celld-peer.js.map +1 -1
- package/dist/project/browser-host.js +3 -2
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/node-project.js +2 -1
- package/dist/project/node-project.js.map +1 -1
- package/dist/project/site-loader.d.ts +45 -0
- package/dist/project/site-loader.js +97 -0
- package/dist/project/site-loader.js.map +1 -0
- package/dist/project/site.d.ts +0 -36
- package/dist/project/site.js +11 -99
- package/dist/project/site.js.map +1 -1
- package/dist/project/wrangler.js +10 -0
- package/dist/project/wrangler.js.map +1 -1
- package/dist/router/cell-router.js +1 -1
- package/dist/router/cell-router.js.map +1 -1
- package/dist/site.d.ts +1 -0
- package/dist/site.js +6 -0
- package/dist/site.js.map +1 -0
- package/dist/transport/port.d.ts +3 -4
- package/dist/transport/port.js +21 -79
- package/dist/transport/port.js.map +1 -1
- package/dist/ws/client.d.ts +23 -8
- package/dist/ws/client.js +50 -189
- package/dist/ws/client.js.map +1 -1
- package/dist/ws/frames.d.ts +31 -8
- package/dist/ws/frames.js +54 -7
- package/dist/ws/frames.js.map +1 -1
- package/dist/ws/server.d.ts +4 -0
- package/dist/ws/server.js +29 -5
- package/dist/ws/server.js.map +1 -1
- package/package.json +29 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"celld-peer.js","sourceRoot":"","sources":["../../src/peer/celld-peer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EAAE,YAAY,EAA0D,MAAM,WAAW,CAAC;AAGjG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MA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AAC,qBAAqB,CAAC,KAAK,aAAa;wBACxE,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC;oBAC5B,IAAI,CAAC,CAAC,MAAM,KAAK,GAAG;wBAClB,MAAM,IAAI,KAAK,CACb,0BAA0B,CAAC,CAAC,MAAM,KAAK,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAC1E,CAAC;oBACJ,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI;wBAAE,OAAO,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;oBACnD,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;wBACpB,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAGpD,CAAC;wBACF,IAAI,KAAK,YAAY,KAAK;4BAAE,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;wBAC1E,MAAM,KAAK,CAAC;oBACd,CAAC;oBACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;gBAChE,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\nimport type { ObjectStore } from \"../bucket/object-store.js\";\nimport { toAnotherNode } from \"../core/handles.js\";\nimport type { CellRuntime } from \"../core/runtime.js\";\nimport { deserialize, serialize } from \"../v8/serialize.js\";\nimport { createWebSocketClass } from \"../ws/client.js\";\nimport { CellsResponse, type CfWebSocket, takeClientPort, WebSocketPair } from \"../ws/server.js\";\nimport { withUpgrade } from \"../ws/upgrade.js\";\n\n/**\n * celld's peer protocol (peer_auth.rs, main/peer_tunnel.rs, protocol 5) for a cellb node\n * hosted in Node, so celld nodes can route a cell's requests to it when it owns the cell.\n *\n * Authentication: every peer request carries an HMAC-SHA-256 over\n * \"cells-peer-request-v1\\n5\\n<method>\\n<path?query>\\n<sha256(body)>\\n<source>\\n<target>\\n<ts>\\n<nonce>\"\n * keyed by the fleet secret in `fleet/peer-auth.json`, with headers x-cells-peer-{version,\n * source,target,timestamp,nonce,body-sha256,signature}; ±30 s clock window, nonce replay cache,\n * and the target must be this node.\n *\n * Tunnel: `GET /peer/tunnel` with `Upgrade: celld-tunnel` (kind `do` or `rpc`) is answered with\n * 101; then the connection carries plain HTTP/1.1 requests, one call each, with control headers\n * x-cells-scope (the cell, \"<Class>:<idhex>\"), x-cells-do-name, x-cells-request-id:\n * do — the application request as is; the reply streams back.\n * rpc — POST, method in x-cells-rpc-method, arguments V8-serialized (an array) or JSON; the\n * reply is the V8-serialized result, or a tagged error (0, then [error, props]).\n * A cell this node does not own answers 409 with `x-cells-route-error: stale-owner`, so celld\n * re-resolves the owner.\n */\nconst PROTOCOL = \"5\";\nconst DOMAIN = \"cells-peer-request-v1\";\nconst CLOCK_WINDOW_MS = 30_000;\nconst PEER_HEADERS = {\n version: \"x-cells-peer-version\",\n source: \"x-cells-peer-source\",\n target: \"x-cells-peer-target\",\n timestamp: \"x-cells-peer-timestamp\",\n nonce: \"x-cells-peer-nonce\",\n bodySha: \"x-cells-peer-body-sha256\",\n signature: \"x-cells-peer-signature\",\n} as const;\nconst CONTROL = [\n \"x-cells-scope\",\n \"x-cells-do-name\",\n \"x-cells-request-id\",\n \"x-cells-capacity-handoff\",\n];\n\n/** The fleet's peer secret (celld creates it in the bucket). */\nexport async function loadPeerKey(store: ObjectStore): Promise<Uint8Array> {\n const o = await store.get(\"fleet/peer-auth.json\");\n if (!o) throw new Error(\"the fleet has no peer authentication secret; start a celld node first\");\n const { version, key } = JSON.parse(new TextDecoder().decode(o.body)) as {\n version: number;\n key: string;\n };\n if (version !== 1 || !/^[0-9a-f]{64}$/.test(key))\n throw new Error(\"unexpected fleet/peer-auth.json\");\n return Uint8Array.from(Buffer.from(key, \"hex\"));\n}\n\nconst sha256hex = (b: Uint8Array) => createHash(\"sha256\").update(b).digest(\"hex\");\nconst mac = (\n key: Uint8Array,\n c: {\n method: string;\n path: string;\n bodySha: string;\n source: string;\n target: string;\n ts: string;\n nonce: string;\n },\n) =>\n createHmac(\"sha256\", key)\n .update(\n `${DOMAIN}\\n${PROTOCOL}\\n${c.method}\\n${c.path}\\n${c.bodySha}\\n${c.source}\\n${c.target}\\n${c.ts}\\n${c.nonce}`,\n )\n .digest();\n\n/** Headers that sign one peer request from `source` to `target`. */\nexport function signPeerRequest(\n key: Uint8Array,\n source: string,\n target: string,\n method: string,\n pathAndQuery: string,\n body: Uint8Array = new Uint8Array(),\n) {\n const ts = String(Date.now());\n const nonce = randomBytes(16).toString(\"hex\");\n const bodySha = sha256hex(body);\n const signature = mac(key, {\n method,\n path: pathAndQuery,\n bodySha,\n source,\n target,\n ts,\n nonce,\n }).toString(\"hex\");\n return {\n [PEER_HEADERS.version]: PROTOCOL,\n [PEER_HEADERS.source]: source,\n [PEER_HEADERS.target]: target,\n [PEER_HEADERS.timestamp]: ts,\n [PEER_HEADERS.nonce]: nonce,\n [PEER_HEADERS.bodySha]: bodySha,\n [PEER_HEADERS.signature]: signature,\n };\n}\n\n/** celld's verification; returns a status and message on failure. */\nexport function verifyPeerRequest(\n key: Uint8Array,\n self: string,\n method: string,\n pathAndQuery: string,\n headers: Record<string, string | string[] | undefined>,\n body: Uint8Array,\n seen: Map<string, number>,\n): { status: number; message: string; stale?: boolean } | undefined {\n const h = (n: string) => (typeof headers[n] === \"string\" ? (headers[n] as string) : undefined);\n const version = h(PEER_HEADERS.version);\n if (version === undefined) return { status: 401, message: \"peer authentication failed\" };\n if (version !== PROTOCOL)\n return { status: 426, message: \"peer protocol version is incompatible\" };\n const [source, target, ts, nonce, bodySha, signature] = [\n PEER_HEADERS.source,\n PEER_HEADERS.target,\n PEER_HEADERS.timestamp,\n PEER_HEADERS.nonce,\n PEER_HEADERS.bodySha,\n PEER_HEADERS.signature,\n ].map(h);\n if (!source || !target || !ts || !nonce || !bodySha || !signature)\n return { status: 401, message: \"peer authentication failed\" };\n const now = Date.now();\n if (!/^\\d+$/.test(ts) || Math.abs(now - Number(ts)) > CLOCK_WINDOW_MS)\n return { status: 401, message: \"peer authentication failed\" };\n if (\n sha256hex(body) !== bodySha ||\n !/^[0-9a-f]{32}$/.test(nonce) ||\n !/^[0-9a-f]{64}$/.test(signature)\n )\n return { status: 401, message: \"peer authentication failed\" };\n const expected = mac(key, { method, path: pathAndQuery, bodySha, source, target, ts, nonce });\n if (!timingSafeEqual(expected, Buffer.from(signature, \"hex\")))\n return { status: 401, message: \"peer authentication failed\" };\n if (target !== self)\n return { status: 409, message: \"peer request targets a different node session\", stale: true };\n for (const [n, t] of seen) if (now - t > 2 * CLOCK_WINDOW_MS) seen.delete(n);\n if (seen.has(nonce)) return { status: 409, message: \"peer request replay rejected\" };\n seen.set(nonce, now);\n return undefined;\n}\n\nconst readBody = async (req: IncomingMessage) => {\n const chunks: Buffer[] = [];\n for await (const c of req) chunks.push(c as Buffer);\n return new Uint8Array(Buffer.concat(chunks));\n};\n\n/** The cell a scope names, as a stub of this runtime (undefined: not a class we host). */\nfunction stubFor(runtime: CellRuntime, scope: string, name: string | undefined): any {\n const m = /^([^:]+):([0-9a-f]{64})$/.exec(scope);\n if (!m) return undefined;\n const binding = Object.entries(runtime.durableObjectBindings).find(\n ([, cls]) => cls === m[1],\n )?.[0];\n if (!binding) return undefined;\n const ns = runtime.env[binding] as any;\n return name !== undefined ? ns.getByName(name) : ns.get(ns.idFromString(m[2]));\n}\n\nconst notOwner = (e: unknown) =>\n /owned by another|OwnedElsewhere|lease/i.test(String((e as Error)?.message ?? e)) ||\n (e as Error)?.name === \"CellOwnedElsewhereError\";\n\nfunction reply(\n res: ServerResponse,\n status: number,\n headers: Record<string, string>,\n body?: Uint8Array | string,\n) {\n res.writeHead(status, { [PEER_HEADERS.version]: PROTOCOL, ...headers });\n res.end(body);\n}\nconst stale = (res: ServerResponse) =>\n reply(\n res,\n 409,\n { \"x-cells-route-error\": \"stale-owner\", \"content-type\": \"text/plain\" },\n \"stale route\",\n );\n\nexport interface CelldPeerServer {\n /** host:port celld dials (put it in the node record: celldBucket({ addr })). */\n addr: string;\n close(): Promise<void>;\n}\n\n/**\n * Serves celld's peer tunnel for `runtime` on `host:port` (0: any free port). `node` is this\n * node's name in the fleet (the same as celldBucket's `node`).\n */\nexport async function startCelldPeerServer(opts: {\n runtime: CellRuntime;\n store: ObjectStore;\n node: string;\n host?: string;\n port?: number;\n /** Answers celld's signed probe (celldBucket(...).probe): `celld diagnose --peer` reaches us. */\n probe?: (challenge: string) => Promise<unknown>;\n}): Promise<CelldPeerServer> {\n const key = await loadPeerKey(opts.store);\n const seen = new Map<string, number>();\n const host = opts.host ?? \"127.0.0.1\";\n\n const serveDo = async (req: IncomingMessage, res: ServerResponse) => {\n const scope = String(req.headers[\"x-cells-scope\"] ?? \"\");\n const name = req.headers[\"x-cells-do-name\"] as string | undefined;\n const stub = stubFor(opts.runtime, scope, name);\n if (!stub) return reply(res, 400, {}, \"malformed cell scope\");\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers))\n if (typeof v === \"string\" && !CONTROL.includes(k)) headers.set(k, v);\n const method = req.method ?? \"GET\";\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : await readBody(req);\n const url = /^https?:\\/\\//.test(req.url ?? \"\")\n ? (req.url as string)\n : `http://${req.headers.host ?? \"cell\"}${req.url ?? \"/\"}`;\n try {\n const r: Response = await stub.fetch(new Request(url, { method, headers, body }));\n const out: Record<string, string> = {};\n r.headers.forEach((v, k) => {\n if (k !== \"content-length\" && k !== \"transfer-encoding\" && k !== \"connection\") out[k] = v;\n });\n reply(res, r.status, out, new Uint8Array(await r.arrayBuffer()));\n } catch (e) {\n if (notOwner(e)) return stale(res);\n reply(res, 500, { \"content-type\": \"text/plain\" }, String((e as Error)?.message ?? e));\n }\n };\n\n const serveRpc = async (req: IncomingMessage, res: ServerResponse) => {\n const scope = String(req.headers[\"x-cells-scope\"] ?? \"\");\n const stub = stubFor(opts.runtime, scope, req.headers[\"x-cells-do-name\"] as string | undefined);\n const method = req.headers[\"x-cells-rpc-method\"] as string | undefined;\n if (!stub) return reply(res, 400, {}, \"malformed cell scope\");\n if (!method) return reply(res, 400, {}, \"RPC method header is missing\");\n const raw = await readBody(req);\n const structured = req.headers[\"content-type\"] === \"application/octet-stream\";\n let args: unknown[];\n if (structured) {\n if (raw[0] !== 0xff) return reply(res, 501, {}, \"RPC stubs cannot cross to cellb\");\n args = deserialize(raw) as unknown[];\n } else args = JSON.parse(new TextDecoder().decode(raw)) as unknown[];\n try {\n const result = await stub[method](...(Array.isArray(args) ? args : [args]));\n if (structured)\n reply(\n res,\n 200,\n { \"content-type\": \"application/octet-stream\" },\n serialize(toAnotherNode(result)),\n );\n else reply(res, 200, { \"content-type\": \"application/json\" }, JSON.stringify(result ?? null));\n } catch (e) {\n if (notOwner(e)) return stale(res);\n if (!structured)\n return reply(\n res,\n 500,\n { \"content-type\": \"text/plain\" },\n `RPC failed: ${String((e as Error)?.message ?? e)}`,\n );\n // celld's callee exception: tag 0, then [error, own properties incl. name]\n const err = e instanceof Error ? e : new Error(String(e));\n const props = e instanceof Error ? { ...e, name: e.name } : { name: \"Error\" };\n const sc = serialize([err, props]);\n const tagged = new Uint8Array(sc.length + 1);\n tagged.set(sc, 1);\n reply(res, 200, { \"content-type\": \"application/octet-stream\" }, tagged);\n }\n };\n\n // One inner HTTP/1.1 server per tunnel kind: an upgraded socket becomes its connection.\n // celld's inner RPC requests carry no Host header: Node would answer 400 by default.\n const inner = {\n do: createServer({ requireHostHeader: false }, (q, s) => void serveDo(q, s)),\n rpc: createServer({ requireHostHeader: false }, (q, s) => void serveRpc(q, s)),\n };\n for (const s of Object.values(inner)) s.keepAliveTimeout = 0;\n // A tunneled WebSocket (celld: the client's own handshake crosses the tunnel and the owner\n // answers it): the cell's 101 + webSocket is bridged to the raw connection, framed by `ws`.\n const { WebSocketServer } = await import(\"ws\");\n const wss = new WebSocketServer({ noServer: true });\n inner.do.on(\"upgrade\", async (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n const fail = (status: number, body: string, extra: Record<string, string> = {}) => {\n const lines = [\n `HTTP/1.1 ${status} ${status === 409 ? \"Conflict\" : \"Error\"}`,\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n `content-length: ${Buffer.byteLength(body)}`,\n \"connection: close\",\n ];\n for (const [k, v] of Object.entries(extra)) lines.push(`${k}: ${v}`);\n socket.end(`${lines.join(\"\\r\\n\")}\\r\\n\\r\\n${body}`);\n };\n const stub = stubFor(\n opts.runtime,\n String(req.headers[\"x-cells-scope\"] ?? \"\"),\n req.headers[\"x-cells-do-name\"] as string | undefined,\n );\n if (!stub) return fail(400, \"malformed cell scope\");\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers))\n if (typeof v === \"string\" && !CONTROL.includes(k)) headers.set(k, v);\n const url = /^https?:\\/\\//.test(req.url ?? \"\")\n ? (req.url as string)\n : `http://${req.headers.host ?? \"cell\"}${req.url ?? \"/\"}`;\n const protocols = req.headers[\"sec-websocket-protocol\"] as string | undefined;\n let res: Response & { webSocket?: CfWebSocket | null };\n try {\n res = await stub.fetch(\n withUpgrade(\n new Request(url, { headers }),\n \"websocket\",\n protocols ? { \"Sec-WebSocket-Protocol\": protocols } : undefined,\n ),\n );\n } catch (e) {\n return notOwner(e)\n ? fail(409, \"stale route\", { \"x-cells-route-error\": \"stale-owner\" })\n : fail(500, String((e as Error)?.message ?? e));\n }\n if (res.status !== 101 || !res.webSocket) return fail(res.status, await res.text());\n const port = takeClientPort(res.webSocket);\n const WS = createWebSocketClass(async () => ({\n port,\n protocol: res.headers.get(\"Sec-WebSocket-Protocol\") ?? undefined,\n }));\n const cell = new WS(\"ws://cell/\") as WebSocket;\n cell.binaryType = \"arraybuffer\";\n const pending: (string | ArrayBuffer)[] = [];\n let open = false;\n wss.handleUpgrade(req, socket, head, (client) => {\n cell.onopen = () => {\n open = true;\n for (const m of pending.splice(0)) cell.send(m);\n };\n client.on(\"message\", (data: Buffer, isBinary: boolean) => {\n const m = isBinary ? (new Uint8Array(data).buffer as ArrayBuffer) : data.toString();\n if (open) cell.send(m);\n else pending.push(m);\n });\n cell.onmessage = (ev: MessageEvent) =>\n client.send(ev.data instanceof ArrayBuffer ? Buffer.from(ev.data) : ev.data);\n client.on(\"close\", (code: number, reason: Buffer) =>\n cell.close(\n code >= 1000 && code < 5000 && code !== 1005 && code !== 1006 ? code : 1000,\n reason.toString(),\n ),\n );\n cell.onclose = (ev: CloseEvent) =>\n client.close(\n ev.code >= 1000 && ev.code !== 1005 && ev.code !== 1006 ? ev.code : 1000,\n ev.reason,\n );\n });\n });\n\n const server: Server = createServer(async (req, res) => {\n if (req.url === \"/peer/probe\" && req.method === \"GET\" && opts.probe) {\n const denied = verifyPeerRequest(\n key,\n opts.node,\n \"GET\",\n \"/peer/probe\",\n req.headers,\n new Uint8Array(),\n seen,\n );\n if (denied)\n return reply(res, denied.status, { \"content-type\": \"text/plain\" }, denied.message);\n try {\n const answer = await opts.probe(String(req.headers[\"x-cells-probe-challenge\"] ?? \"\"));\n return reply(res, 200, { \"content-type\": \"application/json\" }, JSON.stringify(answer));\n } catch (e) {\n return reply(\n res,\n 400,\n { \"content-type\": \"text/plain\" },\n String((e as Error)?.message ?? e),\n );\n }\n }\n reply(res, 404, {}, \"not found\");\n });\n server.on(\"upgrade\", (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n const path = req.url ?? \"/\";\n const refuse = (status: number, message: string, extra: Record<string, string> = {}) => {\n const lines = [\n `HTTP/1.1 ${status} ${message}`,\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n \"connection: close\",\n \"content-length: 0\",\n ];\n for (const [k, v] of Object.entries(extra)) lines.push(`${k}: ${v}`);\n socket.end(`${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`);\n };\n if (path !== \"/peer/tunnel\" || req.headers.upgrade !== \"celld-tunnel\")\n return refuse(404, \"Not Found\");\n const denied = verifyPeerRequest(\n key,\n opts.node,\n req.method ?? \"GET\",\n path,\n req.headers,\n new Uint8Array(),\n seen,\n );\n if (denied)\n return refuse(\n denied.status,\n denied.message,\n denied.stale ? { \"x-cells-route-error\": \"stale-owner\" } : {},\n );\n if (req.headers[\"x-cells-tunnel-version\"] !== \"5\") return refuse(426, \"Upgrade Required\");\n const kind = req.headers[\"x-cells-tunnel-kind\"];\n if (kind !== \"do\" && kind !== \"rpc\") return refuse(400, \"Bad Request\");\n socket.write(\n [\n \"HTTP/1.1 101 Switching Protocols\",\n \"upgrade: celld-tunnel\",\n \"connection: upgrade\",\n \"x-cells-tunnel-version: 5\",\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n ].join(\"\\r\\n\") + \"\\r\\n\\r\\n\",\n );\n if (head?.length) socket.unshift(head);\n inner[kind].emit(\"connection\", socket);\n });\n await new Promise<void>((r) => server.listen(opts.port ?? 0, host, () => r()));\n const port = (server.address() as { port: number }).port;\n return {\n addr: `${host}:${port}`,\n close: () =>\n new Promise<void>((r) => {\n server.closeAllConnections?.();\n for (const s of Object.values(inner)) s.closeAllConnections?.();\n server.close(() => r());\n }),\n };\n}\n\n/**\n * The calling half (celld's node A): open a signed tunnel to the owner node and send one call\n * through it — `fetch` on a `do` tunnel, JS RPC on an `rpc` tunnel (V8-serialized arguments;\n * the reply decoded as celld encodes it, a callee exception rethrown with its properties).\n */\n/** A signed `celld-tunnel` upgrade to the owner node: the raw connection after its 101. */\nasync function openTunnel(\n key: Uint8Array,\n source: string,\n owner: { node: string; addr: string },\n kind: \"do\" | \"rpc\",\n): Promise<import(\"node:net\").Socket> {\n const { request } = await import(\"node:http\");\n const [host, port] = [\n owner.addr.slice(0, owner.addr.lastIndexOf(\":\")),\n Number(owner.addr.slice(owner.addr.lastIndexOf(\":\") + 1)),\n ];\n const socket = await new Promise<import(\"node:net\").Socket>((resolve, reject) => {\n const req = request({\n host,\n port,\n path: \"/peer/tunnel\",\n method: \"GET\",\n headers: {\n upgrade: \"celld-tunnel\",\n connection: \"upgrade\",\n \"x-cells-tunnel-version\": \"5\",\n \"x-cells-tunnel-kind\": kind,\n ...signPeerRequest(key, source, owner.node, \"GET\", \"/peer/tunnel\"),\n },\n });\n req.on(\"upgrade\", (_res, sock) => resolve(sock as import(\"node:net\").Socket));\n req.on(\"response\", (res) =>\n reject(\n Object.assign(new Error(`peer tunnel refused: ${res.statusCode}`), {\n stale: res.headers[\"x-cells-route-error\"] === \"stale-owner\",\n }),\n ),\n );\n req.on(\"error\", reject);\n req.end();\n });\n return socket;\n}\n\nasync function tunnelCall(\n key: Uint8Array,\n source: string,\n owner: { node: string; addr: string },\n kind: \"do\" | \"rpc\",\n inner: { method: string; path: string; headers: Record<string, string>; body?: Uint8Array },\n): Promise<{ status: number; headers: Record<string, string>; body: Uint8Array }> {\n const { request } = await import(\"node:http\");\n const socket = await openTunnel(key, source, owner, kind);\n try {\n return await new Promise((resolve, reject) => {\n const req = request(\n // no agent: the request runs on the upgraded socket itself\n {\n createConnection: () => socket,\n method: inner.method,\n path: inner.path,\n headers: inner.headers,\n },\n async (res) => {\n const chunks: Buffer[] = [];\n for await (const c of res) chunks.push(c as Buffer);\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(res.headers))\n if (typeof v === \"string\") headers[k] = v;\n resolve({\n status: res.statusCode ?? 500,\n headers,\n body: new Uint8Array(Buffer.concat(chunks)),\n });\n },\n );\n req.on(\"error\", reject);\n req.end(inner.body);\n });\n } finally {\n socket.destroy();\n }\n}\n\n/**\n * Routing to cells celld nodes own, for CellRuntimeOptions.peers: `ownerOf` reads the cell's\n * own.json, `endpoint` reaches the owner's address from its node record through the tunnel.\n */\nexport function celldPeers(opts: { store: ObjectStore; node: string }) {\n let key: Promise<Uint8Array> | undefined;\n const json = async <T>(k: string) => {\n const o = await opts.store.get(k);\n return o ? (JSON.parse(new TextDecoder().decode(o.body)) as T) : undefined;\n };\n const staleError = (cellKey: string) =>\n Object.assign(new Error(`${cellKey} is owned by another node`), {\n name: \"CellOwnedElsewhereError\",\n });\n return {\n async ownerOf(cellKey: string) {\n const own = await json<{ node: string }>(`cells/${cellKey.replace(\"/\", \":\")}/own.json`);\n return own?.node && own.node !== opts.node ? own.node : undefined;\n },\n link(): never {\n throw new Error(\"celld owners are reached through endpoint()\");\n },\n async endpoint(owner: string, cellKey: string, name: string | undefined) {\n const lease = await json<{ addr: string; expires_ms: number }>(`nodes/${owner}.json`);\n if (!lease?.addr || lease.expires_ms <= Date.now()) return undefined;\n key ??= loadPeerKey(opts.store);\n const k = await key;\n const target = { node: owner, addr: lease.addr };\n const scope = cellKey.replace(\"/\", \":\");\n const control = (h: Record<string, string>) => ({\n ...h,\n \"x-cells-scope\": scope,\n ...(name !== undefined ? { \"x-cells-do-name\": name } : {}),\n });\n // A WebSocket to a cell celld owns: the client handshake crosses a `do` tunnel and `ws`\n // speaks the frames on it; the caller gets a 101 with a WebSocketPair end bridged to it.\n const tunnelWebSocket = async (req: Request, url: URL) => {\n const socket = await openTunnel(k, opts.node, target, \"do\");\n const { WebSocket: WsClient } = await import(\"ws\");\n const protocols = req.headers\n .get(\"sec-websocket-protocol\")\n ?.split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n const remote = new WsClient(`ws://${url.host}${url.pathname}${url.search}`, protocols, {\n createConnection: () => socket,\n headers: control({}),\n });\n await new Promise<void>((resolve, reject) => {\n remote.once(\"open\", () => resolve());\n remote.once(\n \"unexpected-response\",\n (_q: unknown, res: { statusCode?: number; headers: Record<string, unknown> }) =>\n reject(\n res.headers[\"x-cells-route-error\"] === \"stale-owner\"\n ? staleError(cellKey)\n : new Error(`WebSocket through the tunnel refused: ${res.statusCode}`),\n ),\n );\n remote.once(\"error\", reject);\n });\n const pair = new WebSocketPair();\n const [client, server] = [pair[0], pair[1]];\n server.accept();\n server.addEventListener(\"message\", (e) => remote.send((e as MessageEvent).data));\n remote.on(\"message\", (d: Buffer, isBinary: boolean) =>\n server.send(isBinary ? new Uint8Array(d) : d.toString()),\n );\n const code = (c: number) => (c >= 1000 && c !== 1005 && c !== 1006 ? c : 1000);\n server.addEventListener(\"close\", (e) =>\n remote.close(code((e as CloseEvent).code), (e as CloseEvent).reason),\n );\n remote.on(\"close\", (c: number, reason: Buffer) => server.close(code(c), reason.toString()));\n return new CellsResponse(null, {\n status: 101,\n webSocket: client,\n headers: remote.protocol ? { \"Sec-WebSocket-Protocol\": remote.protocol } : {},\n }) as Response;\n };\n return {\n async fetch(req: Request) {\n const url = new URL(req.url);\n if (req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\")\n return tunnelWebSocket(req, url);\n const headers: Record<string, string> = {};\n req.headers.forEach((v, h) => {\n if (!h.startsWith(\"x-cells-\")) headers[h] = v;\n });\n headers.host ??= url.host;\n const body =\n req.method === \"GET\" || req.method === \"HEAD\"\n ? undefined\n : new Uint8Array(await req.arrayBuffer());\n const r = await tunnelCall(k, opts.node, target, \"do\", {\n method: req.method,\n path: url.pathname + url.search,\n headers: control(headers),\n body,\n });\n if (r.status === 409 && r.headers[\"x-cells-route-error\"] === \"stale-owner\")\n throw staleError(cellKey);\n const out = new Headers();\n for (const [h, v] of Object.entries(r.headers))\n if (!h.startsWith(\"x-cells-\")) out.set(h, v);\n return new Response(r.status === 204 || r.status === 304 ? null : (r.body as BodyInit), {\n status: r.status,\n headers: out,\n });\n },\n async call(method: string, args: unknown[]) {\n const body = serialize(toAnotherNode(args));\n const r = await tunnelCall(k, opts.node, target, \"rpc\", {\n method: \"POST\",\n path: \"/\",\n headers: control({\n \"x-cells-rpc-method\": method,\n \"content-type\": \"application/octet-stream\",\n \"content-length\": String(body.length),\n }),\n body,\n });\n if (r.status === 409 && r.headers[\"x-cells-route-error\"] === \"stale-owner\")\n throw staleError(cellKey);\n if (r.status !== 200)\n throw new Error(\n `remote RPC failed with ${r.status}: ${new TextDecoder().decode(r.body)}`,\n );\n if (r.body[0] === 0xff) return deserialize(r.body);\n if (r.body[0] === 0) {\n const [error, props] = deserialize(r.body.subarray(1)) as [\n unknown,\n Record<string, unknown>,\n ];\n if (error instanceof Error) Object.assign(error, props, { remote: true });\n throw error;\n }\n throw new Error(\"RPC stubs cannot cross from celld to cellb\");\n },\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"celld-peer.js","sourceRoot":"","sources":["../../src/peer/celld-peer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EAAE,YAAY,EAA0D,MAAM,WAAW,CAAC;AAGjG,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAoB,cAAc,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACjG,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,MAAM,GAAG,uBAAuB,CAAC;AACvC,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,MAAM,YAAY,GAAG;IACnB,OAAO,EAAE,sBAAsB;IAC/B,MAAM,EAAE,qBAAqB;IAC7B,MAAM,EAAE,qBAAqB;IAC7B,SAAS,EAAE,wBAAwB;IACnC,KAAK,EAAE,oBAAoB;IAC3B,OAAO,EAAE,0BAA0B;IACnC,SAAS,EAAE,wBAAwB;CAC3B,CAAC;AACX,MAAM,OAAO,GAAG;IACd,eAAe;IACf,iBAAiB;IACj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BAC1E,MAAM,KAAK,CAAC;oBACd,CAAC;oBACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;gBAChE,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\nimport type { ObjectStore } from \"../bucket/object-store.js\";\nimport { toAnotherNode } from \"../core/handles.js\";\nimport type { CellRuntime } from \"../core/runtime.js\";\nimport { deserialize, serialize } from \"../v8/serialize.js\";\nimport { createWebSocketClass } from \"../ws/client.js\";\nimport { CellsResponse, type CfWebSocket, takeClientPort, WebSocketPair } from \"../ws/server.js\";\nimport { withUpgrade } from \"../ws/upgrade.js\";\n\n/**\n * celld's peer protocol (peer_auth.rs, main/peer_tunnel.rs, protocol 5) for a cellb node\n * hosted in Node, so celld nodes can route a cell's requests to it when it owns the cell.\n *\n * Authentication: every peer request carries an HMAC-SHA-256 over\n * \"cells-peer-request-v1\\n5\\n<method>\\n<path?query>\\n<sha256(body)>\\n<source>\\n<target>\\n<ts>\\n<nonce>\"\n * keyed by the fleet secret in `fleet/peer-auth.json`, with headers x-cells-peer-{version,\n * source,target,timestamp,nonce,body-sha256,signature}; ±30 s clock window, nonce replay cache,\n * and the target must be this node.\n *\n * Tunnel: `GET /peer/tunnel` with `Upgrade: celld-tunnel` (kind `do` or `rpc`) is answered with\n * 101; then the connection carries plain HTTP/1.1 requests, one call each, with control headers\n * x-cells-scope (the cell, \"<Class>:<idhex>\"), x-cells-do-name, x-cells-request-id:\n * do — the application request as is; the reply streams back.\n * rpc — POST, method in x-cells-rpc-method, arguments V8-serialized (an array) or JSON; the\n * reply is the V8-serialized result, or a tagged error (0, then [error, props]).\n * A cell this node does not own answers 409 with `x-cells-route-error: stale-owner`, so celld\n * re-resolves the owner.\n */\nconst PROTOCOL = \"5\";\nconst DOMAIN = \"cells-peer-request-v1\";\nconst CLOCK_WINDOW_MS = 30_000;\nconst PEER_HEADERS = {\n version: \"x-cells-peer-version\",\n source: \"x-cells-peer-source\",\n target: \"x-cells-peer-target\",\n timestamp: \"x-cells-peer-timestamp\",\n nonce: \"x-cells-peer-nonce\",\n bodySha: \"x-cells-peer-body-sha256\",\n signature: \"x-cells-peer-signature\",\n} as const;\nconst CONTROL = [\n \"x-cells-scope\",\n \"x-cells-do-name\",\n \"x-cells-request-id\",\n \"x-cells-capacity-handoff\",\n];\n\n/** The fleet's peer secret (celld creates it in the bucket). */\nexport async function loadPeerKey(store: ObjectStore): Promise<Uint8Array> {\n const o = await store.get(\"fleet/peer-auth.json\");\n if (!o) throw new Error(\"the fleet has no peer authentication secret; start a celld node first\");\n const { version, key } = JSON.parse(new TextDecoder().decode(o.body)) as {\n version: number;\n key: string;\n };\n if (version !== 1 || !/^[0-9a-f]{64}$/.test(key))\n throw new Error(\"unexpected fleet/peer-auth.json\");\n return Uint8Array.from(Buffer.from(key, \"hex\"));\n}\n\nconst sha256hex = (b: Uint8Array) => createHash(\"sha256\").update(b).digest(\"hex\");\nconst mac = (\n key: Uint8Array,\n c: {\n method: string;\n path: string;\n bodySha: string;\n source: string;\n target: string;\n ts: string;\n nonce: string;\n },\n) =>\n createHmac(\"sha256\", key)\n .update(\n `${DOMAIN}\\n${PROTOCOL}\\n${c.method}\\n${c.path}\\n${c.bodySha}\\n${c.source}\\n${c.target}\\n${c.ts}\\n${c.nonce}`,\n )\n .digest();\n\n/** Headers that sign one peer request from `source` to `target`. */\nexport function signPeerRequest(\n key: Uint8Array,\n source: string,\n target: string,\n method: string,\n pathAndQuery: string,\n body: Uint8Array = new Uint8Array(),\n) {\n const ts = String(Date.now());\n const nonce = randomBytes(16).toString(\"hex\");\n const bodySha = sha256hex(body);\n const signature = mac(key, {\n method,\n path: pathAndQuery,\n bodySha,\n source,\n target,\n ts,\n nonce,\n }).toString(\"hex\");\n return {\n [PEER_HEADERS.version]: PROTOCOL,\n [PEER_HEADERS.source]: source,\n [PEER_HEADERS.target]: target,\n [PEER_HEADERS.timestamp]: ts,\n [PEER_HEADERS.nonce]: nonce,\n [PEER_HEADERS.bodySha]: bodySha,\n [PEER_HEADERS.signature]: signature,\n };\n}\n\n/** celld's verification; returns a status and message on failure. */\nexport function verifyPeerRequest(\n key: Uint8Array,\n self: string,\n method: string,\n pathAndQuery: string,\n headers: Record<string, string | string[] | undefined>,\n body: Uint8Array,\n seen: Map<string, number>,\n): { status: number; message: string; stale?: boolean } | undefined {\n const h = (n: string) => (typeof headers[n] === \"string\" ? (headers[n] as string) : undefined);\n const version = h(PEER_HEADERS.version);\n if (version === undefined) return { status: 401, message: \"peer authentication failed\" };\n if (version !== PROTOCOL)\n return { status: 426, message: \"peer protocol version is incompatible\" };\n const [source, target, ts, nonce, bodySha, signature] = [\n PEER_HEADERS.source,\n PEER_HEADERS.target,\n PEER_HEADERS.timestamp,\n PEER_HEADERS.nonce,\n PEER_HEADERS.bodySha,\n PEER_HEADERS.signature,\n ].map(h);\n if (!source || !target || !ts || !nonce || !bodySha || !signature)\n return { status: 401, message: \"peer authentication failed\" };\n const now = Date.now();\n if (!/^\\d+$/.test(ts) || Math.abs(now - Number(ts)) > CLOCK_WINDOW_MS)\n return { status: 401, message: \"peer authentication failed\" };\n if (\n sha256hex(body) !== bodySha ||\n !/^[0-9a-f]{32}$/.test(nonce) ||\n !/^[0-9a-f]{64}$/.test(signature)\n )\n return { status: 401, message: \"peer authentication failed\" };\n const expected = mac(key, { method, path: pathAndQuery, bodySha, source, target, ts, nonce });\n if (!timingSafeEqual(expected, Buffer.from(signature, \"hex\")))\n return { status: 401, message: \"peer authentication failed\" };\n if (target !== self)\n return { status: 409, message: \"peer request targets a different node session\", stale: true };\n for (const [n, t] of seen) if (now - t > 2 * CLOCK_WINDOW_MS) seen.delete(n);\n if (seen.has(nonce)) return { status: 409, message: \"peer request replay rejected\" };\n seen.set(nonce, now);\n return undefined;\n}\n\nconst readBody = async (req: IncomingMessage) => {\n const chunks: Buffer[] = [];\n for await (const c of req) chunks.push(c as Buffer);\n return new Uint8Array(Buffer.concat(chunks));\n};\n\n/** The cell a scope names, as a stub of this runtime (undefined: not a class we host). */\nfunction stubFor(runtime: CellRuntime, scope: string, name: string | undefined): any {\n const m = /^([^:]+):([0-9a-f]{64})$/.exec(scope);\n if (!m) return undefined;\n const binding = Object.entries(runtime.durableObjectBindings).find(\n ([, cls]) => cls === m[1],\n )?.[0];\n if (!binding) return undefined;\n const ns = runtime.env[binding] as any;\n return name !== undefined ? ns.getByName(name) : ns.get(ns.idFromString(m[2]));\n}\n\nconst notOwner = (e: unknown) =>\n /owned by another|OwnedElsewhere|lease/i.test(String((e as Error)?.message ?? e)) ||\n (e as Error)?.name === \"CellOwnedElsewhereError\";\n\nfunction reply(\n res: ServerResponse,\n status: number,\n headers: Record<string, string>,\n body?: Uint8Array | string,\n) {\n res.writeHead(status, { [PEER_HEADERS.version]: PROTOCOL, ...headers });\n res.end(body);\n}\nconst stale = (res: ServerResponse) =>\n reply(\n res,\n 409,\n { \"x-cells-route-error\": \"stale-owner\", \"content-type\": \"text/plain\" },\n \"stale route\",\n );\n\nexport interface CelldPeerServer {\n /** host:port celld dials (put it in the node record: celldBucket({ addr })). */\n addr: string;\n close(): Promise<void>;\n}\n\n/** RFC 7230 `token`: what a subprotocol name may be. */\nconst TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/**\n * The subprotocols a `Sec-WebSocket-Protocol` header offers, as a client may ask for them: the\n * valid tokens, each once (case-insensitively), in the offered order. A header a client sent\n * through celld is not trusted to be well formed, and the client class refuses a malformed list.\n */\nexport function offeredProtocols(header: string | undefined): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const raw of (header ?? \"\").split(\",\")) {\n const p = raw.trim();\n if (!TOKEN.test(p) || seen.has(p.toLowerCase())) continue;\n seen.add(p.toLowerCase());\n out.push(p);\n }\n return out;\n}\n\n/**\n * The cell's side of a tunneled WebSocket: a client socket on the port of the 101's\n * WebSocketPair end. It asks for the subprotocols the far client offered (`offered`, the\n * `Sec-WebSocket-Protocol` header): a client refuses a subprotocol it did not ask for, and the\n * cell picks one of those. Should the socket not be made, the port is closed, and the cell's\n * end with it.\n */\nexport function cellSocket(\n res: Response & { webSocket: CfWebSocket },\n offered: string | undefined,\n): WebSocket {\n const port = takeClientPort(res.webSocket);\n try {\n const WS = createWebSocketClass(async () => ({\n port,\n protocol: res.headers.get(\"Sec-WebSocket-Protocol\") ?? undefined,\n }));\n const cell = new WS(\"ws://cell/\", offeredProtocols(offered)) as WebSocket;\n cell.binaryType = \"arraybuffer\";\n return cell;\n } catch (error) {\n port.close();\n throw error;\n }\n}\n\n/**\n * Serves celld's peer tunnel for `runtime` on `host:port` (0: any free port). `node` is this\n * node's name in the fleet (the same as celldBucket's `node`).\n */\nexport async function startCelldPeerServer(opts: {\n runtime: CellRuntime;\n store: ObjectStore;\n node: string;\n host?: string;\n port?: number;\n /** Answers celld's signed probe (celldBucket(...).probe): `celld diagnose --peer` reaches us. */\n probe?: (challenge: string) => Promise<unknown>;\n}): Promise<CelldPeerServer> {\n const key = await loadPeerKey(opts.store);\n const seen = new Map<string, number>();\n const host = opts.host ?? \"127.0.0.1\";\n\n const serveDo = async (req: IncomingMessage, res: ServerResponse) => {\n const scope = String(req.headers[\"x-cells-scope\"] ?? \"\");\n const name = req.headers[\"x-cells-do-name\"] as string | undefined;\n const stub = stubFor(opts.runtime, scope, name);\n if (!stub) return reply(res, 400, {}, \"malformed cell scope\");\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers))\n if (typeof v === \"string\" && !CONTROL.includes(k)) headers.set(k, v);\n const method = req.method ?? \"GET\";\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : await readBody(req);\n const url = /^https?:\\/\\//.test(req.url ?? \"\")\n ? (req.url as string)\n : `http://${req.headers.host ?? \"cell\"}${req.url ?? \"/\"}`;\n try {\n const r: Response = await stub.fetch(new Request(url, { method, headers, body }));\n const out: Record<string, string> = {};\n r.headers.forEach((v, k) => {\n if (k !== \"content-length\" && k !== \"transfer-encoding\" && k !== \"connection\") out[k] = v;\n });\n reply(res, r.status, out, new Uint8Array(await r.arrayBuffer()));\n } catch (e) {\n if (notOwner(e)) return stale(res);\n reply(res, 500, { \"content-type\": \"text/plain\" }, String((e as Error)?.message ?? e));\n }\n };\n\n const serveRpc = async (req: IncomingMessage, res: ServerResponse) => {\n const scope = String(req.headers[\"x-cells-scope\"] ?? \"\");\n const stub = stubFor(opts.runtime, scope, req.headers[\"x-cells-do-name\"] as string | undefined);\n const method = req.headers[\"x-cells-rpc-method\"] as string | undefined;\n if (!stub) return reply(res, 400, {}, \"malformed cell scope\");\n if (!method) return reply(res, 400, {}, \"RPC method header is missing\");\n const raw = await readBody(req);\n const structured = req.headers[\"content-type\"] === \"application/octet-stream\";\n let args: unknown[];\n if (structured) {\n if (raw[0] !== 0xff) return reply(res, 501, {}, \"RPC stubs cannot cross to cellb\");\n args = deserialize(raw) as unknown[];\n } else args = JSON.parse(new TextDecoder().decode(raw)) as unknown[];\n try {\n const result = await stub[method](...(Array.isArray(args) ? args : [args]));\n if (structured)\n reply(\n res,\n 200,\n { \"content-type\": \"application/octet-stream\" },\n serialize(toAnotherNode(result)),\n );\n else reply(res, 200, { \"content-type\": \"application/json\" }, JSON.stringify(result ?? null));\n } catch (e) {\n if (notOwner(e)) return stale(res);\n if (!structured)\n return reply(\n res,\n 500,\n { \"content-type\": \"text/plain\" },\n `RPC failed: ${String((e as Error)?.message ?? e)}`,\n );\n // celld's callee exception: tag 0, then [error, own properties incl. name]\n const err = e instanceof Error ? e : new Error(String(e));\n const props = e instanceof Error ? { ...e, name: e.name } : { name: \"Error\" };\n const sc = serialize([err, props]);\n const tagged = new Uint8Array(sc.length + 1);\n tagged.set(sc, 1);\n reply(res, 200, { \"content-type\": \"application/octet-stream\" }, tagged);\n }\n };\n\n // One inner HTTP/1.1 server per tunnel kind: an upgraded socket becomes its connection.\n // celld's inner RPC requests carry no Host header: Node would answer 400 by default.\n const inner = {\n do: createServer({ requireHostHeader: false }, (q, s) => void serveDo(q, s)),\n rpc: createServer({ requireHostHeader: false }, (q, s) => void serveRpc(q, s)),\n };\n for (const s of Object.values(inner)) s.keepAliveTimeout = 0;\n // A tunneled WebSocket (celld: the client's own handshake crosses the tunnel and the owner\n // answers it): the cell's 101 + webSocket is bridged to the raw connection, framed by `ws`.\n const { WebSocketServer } = await import(\"ws\");\n const wss = new WebSocketServer({ noServer: true });\n inner.do.on(\"upgrade\", async (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n const fail = (status: number, body: string, extra: Record<string, string> = {}) => {\n const lines = [\n `HTTP/1.1 ${status} ${status === 409 ? \"Conflict\" : \"Error\"}`,\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n `content-length: ${Buffer.byteLength(body)}`,\n \"connection: close\",\n ];\n for (const [k, v] of Object.entries(extra)) lines.push(`${k}: ${v}`);\n socket.end(`${lines.join(\"\\r\\n\")}\\r\\n\\r\\n${body}`);\n };\n const stub = stubFor(\n opts.runtime,\n String(req.headers[\"x-cells-scope\"] ?? \"\"),\n req.headers[\"x-cells-do-name\"] as string | undefined,\n );\n if (!stub) return fail(400, \"malformed cell scope\");\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers))\n if (typeof v === \"string\" && !CONTROL.includes(k)) headers.set(k, v);\n const url = /^https?:\\/\\//.test(req.url ?? \"\")\n ? (req.url as string)\n : `http://${req.headers.host ?? \"cell\"}${req.url ?? \"/\"}`;\n const protocols = req.headers[\"sec-websocket-protocol\"] as string | undefined;\n let res: Response & { webSocket?: CfWebSocket | null };\n try {\n res = await stub.fetch(\n withUpgrade(\n new Request(url, { headers }),\n \"websocket\",\n protocols ? { \"Sec-WebSocket-Protocol\": protocols } : undefined,\n ),\n );\n } catch (e) {\n return notOwner(e)\n ? fail(409, \"stale route\", { \"x-cells-route-error\": \"stale-owner\" })\n : fail(500, String((e as Error)?.message ?? e));\n }\n if (res.status !== 101 || !res.webSocket) return fail(res.status, await res.text());\n let cell: WebSocket;\n try {\n cell = cellSocket(res as Response & { webSocket: CfWebSocket }, protocols);\n } catch (e) {\n return fail(400, String((e as Error)?.message ?? e));\n }\n const pending: (string | ArrayBuffer)[] = [];\n let open = false;\n wss.handleUpgrade(req, socket, head, (client) => {\n cell.onopen = () => {\n open = true;\n for (const m of pending.splice(0)) cell.send(m);\n };\n client.on(\"message\", (data: Buffer, isBinary: boolean) => {\n const m = isBinary ? (new Uint8Array(data).buffer as ArrayBuffer) : data.toString();\n if (open) cell.send(m);\n else pending.push(m);\n });\n cell.onmessage = (ev: MessageEvent) =>\n client.send(ev.data instanceof ArrayBuffer ? Buffer.from(ev.data) : ev.data);\n client.on(\"close\", (code: number, reason: Buffer) =>\n cell.close(\n code >= 1000 && code < 5000 && code !== 1005 && code !== 1006 ? code : 1000,\n reason.toString(),\n ),\n );\n cell.onclose = (ev: CloseEvent) =>\n client.close(\n ev.code >= 1000 && ev.code !== 1005 && ev.code !== 1006 ? ev.code : 1000,\n ev.reason,\n );\n });\n });\n\n const server: Server = createServer(async (req, res) => {\n if (req.url === \"/peer/probe\" && req.method === \"GET\" && opts.probe) {\n const denied = verifyPeerRequest(\n key,\n opts.node,\n \"GET\",\n \"/peer/probe\",\n req.headers,\n new Uint8Array(),\n seen,\n );\n if (denied)\n return reply(res, denied.status, { \"content-type\": \"text/plain\" }, denied.message);\n try {\n const answer = await opts.probe(String(req.headers[\"x-cells-probe-challenge\"] ?? \"\"));\n return reply(res, 200, { \"content-type\": \"application/json\" }, JSON.stringify(answer));\n } catch (e) {\n return reply(\n res,\n 400,\n { \"content-type\": \"text/plain\" },\n String((e as Error)?.message ?? e),\n );\n }\n }\n reply(res, 404, {}, \"not found\");\n });\n server.on(\"upgrade\", (req: IncomingMessage, socket: Duplex, head: Buffer) => {\n const path = req.url ?? \"/\";\n const refuse = (status: number, message: string, extra: Record<string, string> = {}) => {\n const lines = [\n `HTTP/1.1 ${status} ${message}`,\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n \"connection: close\",\n \"content-length: 0\",\n ];\n for (const [k, v] of Object.entries(extra)) lines.push(`${k}: ${v}`);\n socket.end(`${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`);\n };\n if (path !== \"/peer/tunnel\" || req.headers.upgrade !== \"celld-tunnel\")\n return refuse(404, \"Not Found\");\n const denied = verifyPeerRequest(\n key,\n opts.node,\n req.method ?? \"GET\",\n path,\n req.headers,\n new Uint8Array(),\n seen,\n );\n if (denied)\n return refuse(\n denied.status,\n denied.message,\n denied.stale ? { \"x-cells-route-error\": \"stale-owner\" } : {},\n );\n if (req.headers[\"x-cells-tunnel-version\"] !== \"5\") return refuse(426, \"Upgrade Required\");\n const kind = req.headers[\"x-cells-tunnel-kind\"];\n if (kind !== \"do\" && kind !== \"rpc\") return refuse(400, \"Bad Request\");\n socket.write(\n [\n \"HTTP/1.1 101 Switching Protocols\",\n \"upgrade: celld-tunnel\",\n \"connection: upgrade\",\n \"x-cells-tunnel-version: 5\",\n `${PEER_HEADERS.version}: ${PROTOCOL}`,\n ].join(\"\\r\\n\") + \"\\r\\n\\r\\n\",\n );\n if (head?.length) socket.unshift(head);\n inner[kind].emit(\"connection\", socket);\n });\n await new Promise<void>((r) => server.listen(opts.port ?? 0, host, () => r()));\n const port = (server.address() as { port: number }).port;\n return {\n addr: `${host}:${port}`,\n close: () =>\n new Promise<void>((r) => {\n server.closeAllConnections?.();\n for (const s of Object.values(inner)) s.closeAllConnections?.();\n server.close(() => r());\n }),\n };\n}\n\n/**\n * The calling half (celld's node A): open a signed tunnel to the owner node and send one call\n * through it — `fetch` on a `do` tunnel, JS RPC on an `rpc` tunnel (V8-serialized arguments;\n * the reply decoded as celld encodes it, a callee exception rethrown with its properties).\n */\n/** A signed `celld-tunnel` upgrade to the owner node: the raw connection after its 101. */\nasync function openTunnel(\n key: Uint8Array,\n source: string,\n owner: { node: string; addr: string },\n kind: \"do\" | \"rpc\",\n): Promise<import(\"node:net\").Socket> {\n const { request } = await import(\"node:http\");\n const [host, port] = [\n owner.addr.slice(0, owner.addr.lastIndexOf(\":\")),\n Number(owner.addr.slice(owner.addr.lastIndexOf(\":\") + 1)),\n ];\n const socket = await new Promise<import(\"node:net\").Socket>((resolve, reject) => {\n const req = request({\n host,\n port,\n path: \"/peer/tunnel\",\n method: \"GET\",\n headers: {\n upgrade: \"celld-tunnel\",\n connection: \"upgrade\",\n \"x-cells-tunnel-version\": \"5\",\n \"x-cells-tunnel-kind\": kind,\n ...signPeerRequest(key, source, owner.node, \"GET\", \"/peer/tunnel\"),\n },\n });\n req.on(\"upgrade\", (_res, sock) => resolve(sock as import(\"node:net\").Socket));\n req.on(\"response\", (res) =>\n reject(\n Object.assign(new Error(`peer tunnel refused: ${res.statusCode}`), {\n stale: res.headers[\"x-cells-route-error\"] === \"stale-owner\",\n }),\n ),\n );\n req.on(\"error\", reject);\n req.end();\n });\n return socket;\n}\n\nasync function tunnelCall(\n key: Uint8Array,\n source: string,\n owner: { node: string; addr: string },\n kind: \"do\" | \"rpc\",\n inner: { method: string; path: string; headers: Record<string, string>; body?: Uint8Array },\n): Promise<{ status: number; headers: Record<string, string>; body: Uint8Array }> {\n const { request } = await import(\"node:http\");\n const socket = await openTunnel(key, source, owner, kind);\n try {\n return await new Promise((resolve, reject) => {\n const req = request(\n // no agent: the request runs on the upgraded socket itself\n {\n createConnection: () => socket,\n method: inner.method,\n path: inner.path,\n headers: inner.headers,\n },\n async (res) => {\n const chunks: Buffer[] = [];\n for await (const c of res) chunks.push(c as Buffer);\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(res.headers))\n if (typeof v === \"string\") headers[k] = v;\n resolve({\n status: res.statusCode ?? 500,\n headers,\n body: new Uint8Array(Buffer.concat(chunks)),\n });\n },\n );\n req.on(\"error\", reject);\n req.end(inner.body);\n });\n } finally {\n socket.destroy();\n }\n}\n\n/**\n * Routing to cells celld nodes own, for CellRuntimeOptions.peers: `ownerOf` reads the cell's\n * own.json, `endpoint` reaches the owner's address from its node record through the tunnel.\n */\nexport function celldPeers(opts: { store: ObjectStore; node: string }) {\n let key: Promise<Uint8Array> | undefined;\n const json = async <T>(k: string) => {\n const o = await opts.store.get(k);\n return o ? (JSON.parse(new TextDecoder().decode(o.body)) as T) : undefined;\n };\n const staleError = (cellKey: string) =>\n Object.assign(new Error(`${cellKey} is owned by another node`), {\n name: \"CellOwnedElsewhereError\",\n });\n return {\n async ownerOf(cellKey: string) {\n const own = await json<{ node: string }>(`cells/${cellKey.replace(\"/\", \":\")}/own.json`);\n return own?.node && own.node !== opts.node ? own.node : undefined;\n },\n link(): never {\n throw new Error(\"celld owners are reached through endpoint()\");\n },\n async endpoint(owner: string, cellKey: string, name: string | undefined) {\n const lease = await json<{ addr: string; expires_ms: number }>(`nodes/${owner}.json`);\n if (!lease?.addr || lease.expires_ms <= Date.now()) return undefined;\n key ??= loadPeerKey(opts.store);\n const k = await key;\n const target = { node: owner, addr: lease.addr };\n const scope = cellKey.replace(\"/\", \":\");\n const control = (h: Record<string, string>) => ({\n ...h,\n \"x-cells-scope\": scope,\n ...(name !== undefined ? { \"x-cells-do-name\": name } : {}),\n });\n // A WebSocket to a cell celld owns: the client handshake crosses a `do` tunnel and `ws`\n // speaks the frames on it; the caller gets a 101 with a WebSocketPair end bridged to it.\n const tunnelWebSocket = async (req: Request, url: URL) => {\n const socket = await openTunnel(k, opts.node, target, \"do\");\n const { WebSocket: WsClient } = await import(\"ws\");\n const protocols = req.headers\n .get(\"sec-websocket-protocol\")\n ?.split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n const remote = new WsClient(`ws://${url.host}${url.pathname}${url.search}`, protocols, {\n createConnection: () => socket,\n headers: control({}),\n });\n await new Promise<void>((resolve, reject) => {\n remote.once(\"open\", () => resolve());\n remote.once(\n \"unexpected-response\",\n (_q: unknown, res: { statusCode?: number; headers: Record<string, unknown> }) =>\n reject(\n res.headers[\"x-cells-route-error\"] === \"stale-owner\"\n ? staleError(cellKey)\n : new Error(`WebSocket through the tunnel refused: ${res.statusCode}`),\n ),\n );\n remote.once(\"error\", reject);\n });\n const pair = new WebSocketPair();\n const [client, server] = [pair[0], pair[1]];\n server.accept();\n server.addEventListener(\"message\", (e) => remote.send((e as MessageEvent).data));\n remote.on(\"message\", (d: Buffer, isBinary: boolean) =>\n server.send(isBinary ? new Uint8Array(d) : d.toString()),\n );\n const code = (c: number) => (c >= 1000 && c !== 1005 && c !== 1006 ? c : 1000);\n server.addEventListener(\"close\", (e) =>\n remote.close(code((e as CloseEvent).code), (e as CloseEvent).reason),\n );\n remote.on(\"close\", (c: number, reason: Buffer) => server.close(code(c), reason.toString()));\n return new CellsResponse(null, {\n status: 101,\n webSocket: client,\n headers: remote.protocol ? { \"Sec-WebSocket-Protocol\": remote.protocol } : {},\n }) as Response;\n };\n return {\n async fetch(req: Request) {\n const url = new URL(req.url);\n if (req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\")\n return tunnelWebSocket(req, url);\n const headers: Record<string, string> = {};\n req.headers.forEach((v, h) => {\n if (!h.startsWith(\"x-cells-\")) headers[h] = v;\n });\n headers.host ??= url.host;\n const body =\n req.method === \"GET\" || req.method === \"HEAD\"\n ? undefined\n : new Uint8Array(await req.arrayBuffer());\n const r = await tunnelCall(k, opts.node, target, \"do\", {\n method: req.method,\n path: url.pathname + url.search,\n headers: control(headers),\n body,\n });\n if (r.status === 409 && r.headers[\"x-cells-route-error\"] === \"stale-owner\")\n throw staleError(cellKey);\n const out = new Headers();\n for (const [h, v] of Object.entries(r.headers))\n if (!h.startsWith(\"x-cells-\")) out.set(h, v);\n return new Response(r.status === 204 || r.status === 304 ? null : (r.body as BodyInit), {\n status: r.status,\n headers: out,\n });\n },\n async call(method: string, args: unknown[]) {\n const body = serialize(toAnotherNode(args));\n const r = await tunnelCall(k, opts.node, target, \"rpc\", {\n method: \"POST\",\n path: \"/\",\n headers: control({\n \"x-cells-rpc-method\": method,\n \"content-type\": \"application/octet-stream\",\n \"content-length\": String(body.length),\n }),\n body,\n });\n if (r.status === 409 && r.headers[\"x-cells-route-error\"] === \"stale-owner\")\n throw staleError(cellKey);\n if (r.status !== 200)\n throw new Error(\n `remote RPC failed with ${r.status}: ${new TextDecoder().decode(r.body)}`,\n );\n if (r.body[0] === 0xff) return deserialize(r.body);\n if (r.body[0] === 0) {\n const [error, props] = deserialize(r.body.subarray(1)) as [\n unknown,\n Record<string, unknown>,\n ];\n if (error instanceof Error) Object.assign(error, props, { remote: true });\n throw error;\n }\n throw new Error(\"RPC stubs cannot cross from celld to cellb\");\n },\n };\n },\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BrowserFilesApi } from "@statewalker/webrun-files-browser";
|
|
2
2
|
import { installLtxVfs } from "../adapters/ltx-vfs.js";
|
|
3
|
-
import { sahpoolOpener, WasmSqliteDriver, wasmMemoryOpener } from "../adapters/wasm-sqlite.js";
|
|
3
|
+
import { sahpoolOpener, tuneCellConnection, WasmSqliteDriver, wasmMemoryOpener, } from "../adapters/wasm-sqlite.js";
|
|
4
4
|
import { celldBucket } from "../bucket/celld-cells.js";
|
|
5
5
|
import { idbObjectStore } from "../bucket/idb-object-store.js";
|
|
6
6
|
import { filesApiObjectStore } from "../bucket/object-store.js";
|
|
@@ -10,7 +10,7 @@ import { installAsyncContext } from "../node-compat/async_hooks.js";
|
|
|
10
10
|
import { installNodeGlobals } from "../node-compat/install.js";
|
|
11
11
|
import { browserModuleLoader } from "./browser-modules.js";
|
|
12
12
|
import * as workersModule from "./cloudflare-workers.js";
|
|
13
|
-
import { siteModuleLoader, workersHostRegistry } from "./site.js";
|
|
13
|
+
import { siteModuleLoader, workersHostRegistry } from "./site-loader.js";
|
|
14
14
|
import { workerScope } from "./worker-scope.js";
|
|
15
15
|
import * as workersGlobals from "./workers-globals-module.js";
|
|
16
16
|
import { createProjectRuntime, loadTimeEnv } from "./wrangler.js";
|
|
@@ -45,6 +45,7 @@ async function ltxOpener(sqlite3, dir, compactAfter, files) {
|
|
|
45
45
|
const s3 = sqlite3;
|
|
46
46
|
const open = (cellKey) => {
|
|
47
47
|
const db = new s3.oo1.DB({ filename: cellKey, vfs: name, flags: "c" });
|
|
48
|
+
tuneCellConnection(sqlite3, db);
|
|
48
49
|
db.exec("PRAGMA journal_mode=MEMORY; PRAGMA synchronous=FULL;");
|
|
49
50
|
// SQLite's C API for inTransaction() only (no page hook or session capture on this VFS).
|
|
50
51
|
return new WasmSqliteDriver(db, undefined, undefined, sqlite3.capi);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-host.js","sourceRoot":"","sources":["../../src/project/browser-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAG/F,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAoB,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,aAAa,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EAAoB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,KAAK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O,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,sDAAsD;QAC3E,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAsB;IACxD,MAAM,KAAK,GAAG,MAAM,CAAC,mBAAmB,IAAI,EAAE,CAAC;IAC/C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACpE,IAAI,KAAK,CAAC,QAAQ,CAAC,2CAA2C,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,IAAI,KAAK,CAAC,QAAQ,CAAC,oCAAoC,CAAC;QAAE,OAAO,IAAI,CAAC;IACtE,OAAO,CAAC,MAAM,CAAC,kBAAkB,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 { BrowserFilesApi } from \"@statewalker/webrun-files-browser\";\nimport { installLtxVfs } from \"../adapters/ltx-vfs.js\";\nimport { sahpoolOpener, WasmSqliteDriver, wasmMemoryOpener } from \"../adapters/wasm-sqlite.js\";\nimport type { AssetFiles } from \"../bindings/assets.js\";\nimport type { WorkersAiOptions } from \"../bindings/workers-ai.js\";\nimport { celldBucket } from \"../bucket/celld-cells.js\";\nimport { idbObjectStore } from \"../bucket/idb-object-store.js\";\nimport { filesApiObjectStore, type ObjectStore } from \"../bucket/object-store.js\";\nimport { s3ObjectStore } from \"../bucket/s3-object-store.js\";\nimport type { CellRuntimeOptions, WorkerModule } from \"../core/runtime.js\";\nimport { browserIsolatedLoader } from \"../isolate/browser.js\";\nimport { installAsyncContext } from \"../node-compat/async_hooks.js\";\nimport { installNodeGlobals } from \"../node-compat/install.js\";\nimport { browserModuleLoader } from \"./browser-modules.js\";\nimport * as workersModule from \"./cloudflare-workers.js\";\nimport { siteModuleLoader, workersHostRegistry } from \"./site.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport * as workersGlobals from \"./workers-globals-module.js\";\nimport { createProjectRuntime, loadTimeEnv, type WranglerConfig } from \"./wrangler.js\";\n\n/**\n * Where a browser-hosted project keeps its cells when they must outlive the page or move to\n * other nodes: a celld fleet bucket. Cells, facets and alarms are then exactly celld's\n * (ownership in `own.json`, LTX logs, wake index) and R2 objects live in it too, so the same\n * cells can be served by this browser, by other browsers and by celld nodes, in turn.\n *\n * - `s3`: an S3-compatible bucket, reached directly (the bucket must allow CORS for the page's\n * origin: methods GET/PUT/DELETE/HEAD, request headers `authorization`, `content-type`,\n * `x-amz-*`, `if-match`, `if-none-match`; exposed headers `etag`, `last-modified`,\n * `x-amz-meta-celld-r2`) or through a same-origin proxy (`endpoint` = the proxy,\n * `signAs` = the real endpoint: SigV4 signs the real host and path).\n * - `opfs`: a bucket in this origin's OPFS — persistence without a server. Conditional writes\n * are atomic only within one writer, so one tab or worker at a time should own its cells.\n * - `store`: any ObjectStore.\n */\nexport type BrowserBucket =\n | {\n s3: {\n endpoint: string;\n signAs?: string;\n bucket: string;\n prefix?: string;\n region?: string;\n accessKeyId: string;\n secretAccessKey: string;\n };\n node: string;\n leaseTtlMs?: number;\n }\n | { opfs: string; node: string; leaseTtlMs?: number }\n /**\n * `idb`: a bucket in this origin's IndexedDB (atomic conditional writes across tabs and\n * workers). Cells then run SQLite in memory and persist through the bucket's page-level logs:\n * no OPFS pool, so any number of workers can serve cells at once.\n */\n | { idb: string; node: string; leaseTtlMs?: number }\n /**\n * `ltx`: cells as celld keeps them, LTX files (a snapshot and one file per commit) in an OPFS\n * directory, read page by page (a SQLite VFS over a store worker): no OPFS pool, and a\n * cell's memory is its page cache, not its database. A cell is folded into one snapshot\n * (streamed) past `compactAfter` files (default 64), or once the files after its snapshot hold\n * more than half of it. See docs/browser-host.md.\n */\n | {\n ltx: string;\n node: string;\n leaseTtlMs?: number;\n compactAfter?: number;\n /**\n * The cells' FilesApi in the store worker: OPFS through synchronous handles (default,\n * `opfs-sync`), OPFS through its asynchronous API (`opfs`), or memory (nothing kept).\n */\n files?: \"opfs\" | \"opfs-sync\" | \"memory\";\n }\n | { store: ObjectStore; node: string; leaseTtlMs?: number };\n\nexport interface BrowserProjectOptions {\n config: WranglerConfig;\n /**\n * The project's Worker code, imported in this realm once its Workers globals (and with\n * nodejs_compat `Buffer` and `process`) are installed:\n * - `bundle`: one ES module built for browsers (`bundleWorkerForBrowser`), whose\n * `cloudflare:workers` is `PROJECT_WORKERS_MODULE_SHIM` and whose Workers globals read\n * `globalThis.__cellsGlobals`\n * (`null`: the project has no `main`). Worker Loader code becomes Blob-URL modules.\n * - `site`: the base URL of the project's site (`createProjectSite`, hosted by\n * webrun-site-host). `main` and Worker Loader code are imported from it.\n */\n code: { bundle: string | null } | { site: string };\n /**\n * A Dedicated Worker script that serves one loaded Worker (`serveIsolate`): Worker Loader\n * code then runs isolated, one Dedicated Worker per loaded Worker, as celld's isolates.\n * The package ships one: `@statewalker/cellb/isolate-worker`.\n */\n isolateScript?: URL;\n /** An initialized SQLite WASM module (`@sqlite.org/sqlite-wasm`). */\n sqlite3: unknown;\n /** OPFS sahpool name for this host's SQLite files (one pool per worker). */\n pool: string;\n /** OPFS directory for the project's FilesApi (Workers' fs-like bindings, R2 without bucket). */\n filesDir: string;\n assetFiles?: AssetFiles;\n bucket?: BrowserBucket;\n /**\n * Cells this runtime does not host: where to send their events (a `Send` over a MessagePort\n * to the runtime that hosts them, `linkOverPort`), or undefined to host the cell here. With\n * one runtime per worker and `shardOf` as the placement, cells run in parallel threads.\n */\n route?: CellRuntimeOptions[\"route\"];\n /** The OpenAI-compatible endpoint behind the project's `ai` binding (Workers AI). */\n ai?: WorkersAiOptions;\n}\n\nasync function bucketStore(b: BrowserBucket): Promise<ObjectStore> {\n if (\"store\" in b) return b.store;\n if (\"s3\" in b) return s3ObjectStore({ region: \"us-east-1\", ...b.s3 });\n if (\"idb\" in b) return idbObjectStore(b.idb);\n if (\"ltx\" in b) throw new Error(\"an ltx directory is cell storage, not a bucket\");\n const root = await navigator.storage.getDirectory();\n return filesApiObjectStore(\n new BrowserFilesApi({ rootHandle: await root.getDirectoryHandle(b.opfs, { create: true }) }),\n \"\",\n );\n}\n\n/**\n * Cells on the LTX VFS: a store worker owns the OPFS directory; each cell is a SQLite database\n * whose main file is its LTX files, read page by page (src/adapters/ltx-vfs.ts).\n */\nasync function ltxOpener(sqlite3: unknown, dir: string, compactAfter?: number, files?: string) {\n const store = new Worker(\n new URL(\"../ltx/ltx-store-worker.ts\", import.meta.url) /* `.js` in dist/ (scripts/build.mjs) */,\n { type: \"module\" },\n );\n const sab = new SharedArrayBuffer(8 + 16 * 65536); // room for a read-ahead run of 64 KiB pages\n // Wait until the store worker runs before any synchronous call: a nested worker is started\n // (its script fetched) through this worker's event loop, which Atomics.wait would block.\n const ready = new Promise<void>((resolve, reject) => {\n store.addEventListener(\"message\", (e) => e.data?.op === \"ready\" && resolve(), { once: false });\n store.addEventListener(\"error\", (e) => reject(new Error(`ltx store worker: ${e.message}`)));\n });\n store.postMessage({ op: \"init\", sab, dir, compactAfter, files });\n await ready;\n const { name } = installLtxVfs(sqlite3, { sab, post: (m) => store.postMessage(m) });\n const s3 = sqlite3 as { oo1: { DB: new (o: Record<string, unknown>) => any } };\n const open = (cellKey: string) => {\n const db = new s3.oo1.DB({ filename: cellKey, vfs: name, flags: \"c\" });\n db.exec(\"PRAGMA journal_mode=MEMORY; PRAGMA synchronous=FULL;\");\n // SQLite's C API for inTransaction() only (no page hook or session capture on this VFS).\n return new WasmSqliteDriver(db, undefined, undefined, (sqlite3 as { capi: never }).capi);\n };\n return Object.assign(open, {\n release() {\n store.terminate();\n },\n reserve: async (n: number) => n,\n });\n}\n\n/** Installs the Workers globals the code reads, then imports its `main`. */\nasync function importWorkerCode(\n config: WranglerConfig,\n code: BrowserProjectOptions[\"code\"],\n scope: WorkerScope,\n): Promise<WorkerModule> {\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n if (nodeCompat) {\n installNodeGlobals();\n // node:* for bundles built with cellbHostModule (another bundler than bundleWorkerForBrowser);\n // loaded after installNodeGlobals(), as the npm `util` polyfill reads `process`.\n (globalThis as Record<string, unknown>).__cellsNodeModules = (\n await import(\"../node-compat/browser-registry.js\")\n ).nodeRegistryEntries;\n if (populatesProcessEnv(config)) {\n const env = processEnvOf(config);\n // The bundle's own `process` reads it when evaluated; a site's modules use this realm's.\n (globalThis as Record<string, unknown>).__cellsProcessEnv = env;\n Object.assign((globalThis as { process: { env: Record<string, string> } }).process.env, env);\n }\n // node:async_hooks: continuations carry their AsyncLocalStorage stores (with AsyncContext\n // the engine does, and this installs nothing). The code's awaits are lowered so that they go\n // through them: by bundleWorkerForBrowser for a bundle, by createProjectSite (nodeCompat) for\n // a site's modules.\n installAsyncContext();\n }\n const globals = {\n ...workersGlobals,\n Request: workersGlobals.CellsRequest,\n Response: workersGlobals.CellsResponse,\n WebSocketPair: flags.includes(\"websocket_standard_binary_type\")\n ? workersGlobals.StandardWebSocketPair\n : workersGlobals.WebSocketPair,\n };\n if (\"site\" in code) {\n workersHostRegistry({\n workersModule,\n projectWorkersModule: {\n ...workersModule,\n env: scope.env,\n exports: scope.exports,\n waitUntil: scope.waitUntil,\n },\n loadedPrefix: `${code.site}loaded/`,\n emailModule: await import(\"./cloudflare-email.js\"),\n ...globals,\n // Loaded on demand, after installNodeGlobals(): the npm `util` polyfill reads `process`\n // when it is imported.\n node: nodeCompat\n ? (await import(\"../node-compat/browser-registry.js\")).nodeRegistryEntries\n : undefined,\n });\n return config.main\n ? await import(/* @vite-ignore */ `${code.site}modules/~/${config.main}`)\n : { default: {} };\n }\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkersModule = workersModule;\n g.__cellsProjectScope = scope; // `env` and `exports` of the bundle's cloudflare:workers\n g.__cellsGlobals = globals;\n return code.bundle\n ? await import(\n /* @vite-ignore */ URL.createObjectURL(new Blob([code.bundle], { type: \"text/javascript\" }))\n )\n : { default: {} };\n}\n\n/**\n * A project's runtime in this worker: installs the Workers globals, imports the code and\n * builds its Worker Loader; `close()` also releases the node's bucket lease.\n */\nexport async function browserProjectRuntime(opts: BrowserProjectOptions) {\n const scope = workerScope(loadTimeEnv(opts.config, opts.ai));\n const module = await importWorkerCode(opts.config, opts.code, scope);\n const site = \"site\" in opts.code ? opts.code.site : undefined;\n // With an IndexedDB bucket, cells live in memory and in the bucket's logs (no OPFS pool).\n const openSql =\n opts.bucket && \"ltx\" in opts.bucket\n ? await ltxOpener(opts.sqlite3, opts.bucket.ltx, opts.bucket.compactAfter, opts.bucket.files)\n : opts.bucket && \"idb\" in opts.bucket\n ? Object.assign(wasmMemoryOpener(opts.sqlite3 as never), {\n release() {},\n reserve: async (n: number) => n,\n })\n : await sahpoolOpener(opts.sqlite3 as never, {\n name: opts.pool,\n initialCapacity: 64, // grows on demand (sahpoolOpener)\n });\n const root = await navigator.storage.getDirectory();\n const files = new BrowserFilesApi({\n rootHandle: await root.getDirectoryHandle(opts.filesDir, { create: true }),\n });\n // An `ltx` directory is the cells' own storage (the VFS), not a fleet bucket.\n const store = opts.bucket && !(\"ltx\" in opts.bucket) ? await bucketStore(opts.bucket) : undefined;\n const shared =\n opts.bucket && store\n ? celldBucket(store, { node: opts.bucket.node, leaseTtlMs: opts.bucket.leaseTtlMs })\n : undefined;\n const { runtime, unsupported } = createProjectRuntime(opts.config, module, {\n openSql,\n files,\n assetFiles: opts.assetFiles,\n loadModules: site ? siteModuleLoader(site) : browserModuleLoader(),\n isolatedModules: opts.isolateScript\n ? browserIsolatedLoader({\n isolateScript: opts.isolateScript,\n siteBaseUrl: site,\n storagePrefix: `${opts.pool}-iso`,\n storage: () => shared, // facets of loaded code are logged like the root's own\n })\n : undefined,\n storage: shared, // R2 objects in the fleet bucket too, as celld keeps them\n route: opts.route,\n ai: opts.ai,\n });\n scope.bind(runtime);\n return {\n runtime,\n unsupported,\n bucket: shared,\n close: async () => {\n await runtime.close();\n openSql.release(); // the pool's files, for the next worker that opens it\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":"browser-host.js","sourceRoot":"","sources":["../../src/project/browser-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,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,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 { BrowserFilesApi } from \"@statewalker/webrun-files-browser\";\nimport { installLtxVfs } from \"../adapters/ltx-vfs.js\";\nimport {\n sahpoolOpener,\n tuneCellConnection,\n WasmSqliteDriver,\n wasmMemoryOpener,\n} from \"../adapters/wasm-sqlite.js\";\nimport type { AssetFiles } from \"../bindings/assets.js\";\nimport type { WorkersAiOptions } from \"../bindings/workers-ai.js\";\nimport { celldBucket } from \"../bucket/celld-cells.js\";\nimport { idbObjectStore } from \"../bucket/idb-object-store.js\";\nimport { filesApiObjectStore, type ObjectStore } from \"../bucket/object-store.js\";\nimport { s3ObjectStore } from \"../bucket/s3-object-store.js\";\nimport type { CellRuntimeOptions, WorkerModule } from \"../core/runtime.js\";\nimport { browserIsolatedLoader } from \"../isolate/browser.js\";\nimport { installAsyncContext } from \"../node-compat/async_hooks.js\";\nimport { installNodeGlobals } from \"../node-compat/install.js\";\nimport { browserModuleLoader } from \"./browser-modules.js\";\nimport * as workersModule from \"./cloudflare-workers.js\";\nimport { siteModuleLoader, workersHostRegistry } from \"./site-loader.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport * as workersGlobals from \"./workers-globals-module.js\";\nimport { createProjectRuntime, loadTimeEnv, type WranglerConfig } from \"./wrangler.js\";\n\n/**\n * Where a browser-hosted project keeps its cells when they must outlive the page or move to\n * other nodes: a celld fleet bucket. Cells, facets and alarms are then exactly celld's\n * (ownership in `own.json`, LTX logs, wake index) and R2 objects live in it too, so the same\n * cells can be served by this browser, by other browsers and by celld nodes, in turn.\n *\n * - `s3`: an S3-compatible bucket, reached directly (the bucket must allow CORS for the page's\n * origin: methods GET/PUT/DELETE/HEAD, request headers `authorization`, `content-type`,\n * `x-amz-*`, `if-match`, `if-none-match`; exposed headers `etag`, `last-modified`,\n * `x-amz-meta-celld-r2`) or through a same-origin proxy (`endpoint` = the proxy,\n * `signAs` = the real endpoint: SigV4 signs the real host and path).\n * - `opfs`: a bucket in this origin's OPFS — persistence without a server. Conditional writes\n * are atomic only within one writer, so one tab or worker at a time should own its cells.\n * - `store`: any ObjectStore.\n */\nexport type BrowserBucket =\n | {\n s3: {\n endpoint: string;\n signAs?: string;\n bucket: string;\n prefix?: string;\n region?: string;\n accessKeyId: string;\n secretAccessKey: string;\n };\n node: string;\n leaseTtlMs?: number;\n }\n | { opfs: string; node: string; leaseTtlMs?: number }\n /**\n * `idb`: a bucket in this origin's IndexedDB (atomic conditional writes across tabs and\n * workers). Cells then run SQLite in memory and persist through the bucket's page-level logs:\n * no OPFS pool, so any number of workers can serve cells at once.\n */\n | { idb: string; node: string; leaseTtlMs?: number }\n /**\n * `ltx`: cells as celld keeps them, LTX files (a snapshot and one file per commit) in an OPFS\n * directory, read page by page (a SQLite VFS over a store worker): no OPFS pool, and a\n * cell's memory is its page cache, not its database. A cell is folded into one snapshot\n * (streamed) past `compactAfter` files (default 64), or once the files after its snapshot hold\n * more than half of it. See docs/browser-host.md.\n */\n | {\n ltx: string;\n node: string;\n leaseTtlMs?: number;\n compactAfter?: number;\n /**\n * The cells' FilesApi in the store worker: OPFS through synchronous handles (default,\n * `opfs-sync`), OPFS through its asynchronous API (`opfs`), or memory (nothing kept).\n */\n files?: \"opfs\" | \"opfs-sync\" | \"memory\";\n }\n | { store: ObjectStore; node: string; leaseTtlMs?: number };\n\nexport interface BrowserProjectOptions {\n config: WranglerConfig;\n /**\n * The project's Worker code, imported in this realm once its Workers globals (and with\n * nodejs_compat `Buffer` and `process`) are installed:\n * - `bundle`: one ES module built for browsers (`bundleWorkerForBrowser`), whose\n * `cloudflare:workers` is `PROJECT_WORKERS_MODULE_SHIM` and whose Workers globals read\n * `globalThis.__cellsGlobals`\n * (`null`: the project has no `main`). Worker Loader code becomes Blob-URL modules.\n * - `site`: the base URL of the project's site (`createProjectSite`, hosted by\n * webrun-site-host). `main` and Worker Loader code are imported from it.\n */\n code: { bundle: string | null } | { site: string };\n /**\n * A Dedicated Worker script that serves one loaded Worker (`serveIsolate`): Worker Loader\n * code then runs isolated, one Dedicated Worker per loaded Worker, as celld's isolates.\n * The package ships one: `@statewalker/cellb/isolate-worker`.\n */\n isolateScript?: URL;\n /** An initialized SQLite WASM module (`@sqlite.org/sqlite-wasm`). */\n sqlite3: unknown;\n /** OPFS sahpool name for this host's SQLite files (one pool per worker). */\n pool: string;\n /** OPFS directory for the project's FilesApi (Workers' fs-like bindings, R2 without bucket). */\n filesDir: string;\n assetFiles?: AssetFiles;\n bucket?: BrowserBucket;\n /**\n * Cells this runtime does not host: where to send their events (a `Send` over a MessagePort\n * to the runtime that hosts them, `linkOverPort`), or undefined to host the cell here. With\n * one runtime per worker and `shardOf` as the placement, cells run in parallel threads.\n */\n route?: CellRuntimeOptions[\"route\"];\n /** The OpenAI-compatible endpoint behind the project's `ai` binding (Workers AI). */\n ai?: WorkersAiOptions;\n}\n\nasync function bucketStore(b: BrowserBucket): Promise<ObjectStore> {\n if (\"store\" in b) return b.store;\n if (\"s3\" in b) return s3ObjectStore({ region: \"us-east-1\", ...b.s3 });\n if (\"idb\" in b) return idbObjectStore(b.idb);\n if (\"ltx\" in b) throw new Error(\"an ltx directory is cell storage, not a bucket\");\n const root = await navigator.storage.getDirectory();\n return filesApiObjectStore(\n new BrowserFilesApi({ rootHandle: await root.getDirectoryHandle(b.opfs, { create: true }) }),\n \"\",\n );\n}\n\n/**\n * Cells on the LTX VFS: a store worker owns the OPFS directory; each cell is a SQLite database\n * whose main file is its LTX files, read page by page (src/adapters/ltx-vfs.ts).\n */\nasync function ltxOpener(sqlite3: unknown, dir: string, compactAfter?: number, files?: string) {\n const store = new Worker(\n new URL(\"../ltx/ltx-store-worker.ts\", import.meta.url) /* `.js` in dist/ (scripts/build.mjs) */,\n { type: \"module\" },\n );\n const sab = new SharedArrayBuffer(8 + 16 * 65536); // room for a read-ahead run of 64 KiB pages\n // Wait until the store worker runs before any synchronous call: a nested worker is started\n // (its script fetched) through this worker's event loop, which Atomics.wait would block.\n const ready = new Promise<void>((resolve, reject) => {\n store.addEventListener(\"message\", (e) => e.data?.op === \"ready\" && resolve(), { once: false });\n store.addEventListener(\"error\", (e) => reject(new Error(`ltx store worker: ${e.message}`)));\n });\n store.postMessage({ op: \"init\", sab, dir, compactAfter, files });\n await ready;\n const { name } = installLtxVfs(sqlite3, { sab, post: (m) => store.postMessage(m) });\n const s3 = sqlite3 as { oo1: { DB: new (o: Record<string, unknown>) => any } };\n const open = (cellKey: string) => {\n const db = new s3.oo1.DB({ filename: cellKey, vfs: name, flags: \"c\" });\n tuneCellConnection(sqlite3, db);\n db.exec(\"PRAGMA journal_mode=MEMORY; PRAGMA synchronous=FULL;\");\n // SQLite's C API for inTransaction() only (no page hook or session capture on this VFS).\n return new WasmSqliteDriver(db, undefined, undefined, (sqlite3 as { capi: never }).capi);\n };\n return Object.assign(open, {\n release() {\n store.terminate();\n },\n reserve: async (n: number) => n,\n });\n}\n\n/** Installs the Workers globals the code reads, then imports its `main`. */\nasync function importWorkerCode(\n config: WranglerConfig,\n code: BrowserProjectOptions[\"code\"],\n scope: WorkerScope,\n): Promise<WorkerModule> {\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n if (nodeCompat) {\n installNodeGlobals();\n // node:* for bundles built with cellbHostModule (another bundler than bundleWorkerForBrowser);\n // loaded after installNodeGlobals(), as the npm `util` polyfill reads `process`.\n (globalThis as Record<string, unknown>).__cellsNodeModules = (\n await import(\"../node-compat/browser-registry.js\")\n ).nodeRegistryEntries;\n if (populatesProcessEnv(config)) {\n const env = processEnvOf(config);\n // The bundle's own `process` reads it when evaluated; a site's modules use this realm's.\n (globalThis as Record<string, unknown>).__cellsProcessEnv = env;\n Object.assign((globalThis as { process: { env: Record<string, string> } }).process.env, env);\n }\n // node:async_hooks: continuations carry their AsyncLocalStorage stores (with AsyncContext\n // the engine does, and this installs nothing). The code's awaits are lowered so that they go\n // through them: by bundleWorkerForBrowser for a bundle, by createProjectSite (nodeCompat) for\n // a site's modules.\n installAsyncContext();\n }\n const globals = {\n ...workersGlobals,\n Request: workersGlobals.CellsRequest,\n Response: workersGlobals.CellsResponse,\n WebSocketPair: flags.includes(\"websocket_standard_binary_type\")\n ? workersGlobals.StandardWebSocketPair\n : workersGlobals.WebSocketPair,\n };\n if (\"site\" in code) {\n workersHostRegistry({\n workersModule,\n projectWorkersModule: {\n ...workersModule,\n env: scope.env,\n exports: scope.exports,\n waitUntil: scope.waitUntil,\n },\n loadedPrefix: `${code.site}loaded/`,\n emailModule: await import(\"./cloudflare-email.js\"),\n ...globals,\n // Loaded on demand, after installNodeGlobals(): the npm `util` polyfill reads `process`\n // when it is imported.\n node: nodeCompat\n ? (await import(\"../node-compat/browser-registry.js\")).nodeRegistryEntries\n : undefined,\n });\n return config.main\n ? await import(/* @vite-ignore */ `${code.site}modules/~/${config.main}`)\n : { default: {} };\n }\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkersModule = workersModule;\n g.__cellsProjectScope = scope; // `env` and `exports` of the bundle's cloudflare:workers\n g.__cellsGlobals = globals;\n return code.bundle\n ? await import(\n /* @vite-ignore */ URL.createObjectURL(new Blob([code.bundle], { type: \"text/javascript\" }))\n )\n : { default: {} };\n}\n\n/**\n * A project's runtime in this worker: installs the Workers globals, imports the code and\n * builds its Worker Loader; `close()` also releases the node's bucket lease.\n */\nexport async function browserProjectRuntime(opts: BrowserProjectOptions) {\n const scope = workerScope(loadTimeEnv(opts.config, opts.ai));\n const module = await importWorkerCode(opts.config, opts.code, scope);\n const site = \"site\" in opts.code ? opts.code.site : undefined;\n // With an IndexedDB bucket, cells live in memory and in the bucket's logs (no OPFS pool).\n const openSql =\n opts.bucket && \"ltx\" in opts.bucket\n ? await ltxOpener(opts.sqlite3, opts.bucket.ltx, opts.bucket.compactAfter, opts.bucket.files)\n : opts.bucket && \"idb\" in opts.bucket\n ? Object.assign(wasmMemoryOpener(opts.sqlite3 as never), {\n release() {},\n reserve: async (n: number) => n,\n })\n : await sahpoolOpener(opts.sqlite3 as never, {\n name: opts.pool,\n initialCapacity: 64, // grows on demand (sahpoolOpener)\n });\n const root = await navigator.storage.getDirectory();\n const files = new BrowserFilesApi({\n rootHandle: await root.getDirectoryHandle(opts.filesDir, { create: true }),\n });\n // An `ltx` directory is the cells' own storage (the VFS), not a fleet bucket.\n const store = opts.bucket && !(\"ltx\" in opts.bucket) ? await bucketStore(opts.bucket) : undefined;\n const shared =\n opts.bucket && store\n ? celldBucket(store, { node: opts.bucket.node, leaseTtlMs: opts.bucket.leaseTtlMs })\n : undefined;\n const { runtime, unsupported } = createProjectRuntime(opts.config, module, {\n openSql,\n files,\n assetFiles: opts.assetFiles,\n loadModules: site ? siteModuleLoader(site) : browserModuleLoader(),\n isolatedModules: opts.isolateScript\n ? browserIsolatedLoader({\n isolateScript: opts.isolateScript,\n siteBaseUrl: site,\n storagePrefix: `${opts.pool}-iso`,\n storage: () => shared, // facets of loaded code are logged like the root's own\n })\n : undefined,\n storage: shared, // R2 objects in the fleet bucket too, as celld keeps them\n route: opts.route,\n ai: opts.ai,\n });\n scope.bind(runtime);\n return {\n runtime,\n unsupported,\n bucket: shared,\n close: async () => {\n await runtime.close();\n openSql.release(); // the pool's files, for the next worker that opens it\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"]}
|
|
@@ -311,7 +311,8 @@ export function nodeIsolatedLoader(storage) {
|
|
|
311
311
|
}));
|
|
312
312
|
b.onLoad({ filter: /.*/, namespace: "isolate-workers" }, () => ({
|
|
313
313
|
contents: [
|
|
314
|
-
|
|
314
|
+
// cloudflare-workers.js in the published package (dist/), .ts in the sources.
|
|
315
|
+
`export * from ${JSON.stringify(ownModule(import.meta.dirname, "cloudflare-workers"))};`,
|
|
315
316
|
"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);",
|
|
316
317
|
].join("\n"),
|
|
317
318
|
loader: "js",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MA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C,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry: { path: string } | { modules: Record<string, string>; main: string },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: { nodeCompat?: boolean; standardBinaryType?: boolean; scope?: WorkerScope } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n registry[consoleKey] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n // nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires\n // node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's\n // require shim needs a `require` in scope: vitest's module runner provides one, plain Node\n // does not.\n ...(opts.nodeCompat\n ? {\n banner: {\n js: 'import { createRequire as __cellbCreateRequire } from \"node:module\";\\nconst require = __cellbCreateRequire(import.meta.url);',\n },\n }\n : {}),\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules.\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, code, logs) => {\n const outbound = outboundFetch(code);\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (\n nodeCompat &&\n !flags.includes(\"nodejs_compat_do_not_populate_process_env\") &&\n (flags.includes(\"nodejs_compat_populate_process_env\") ||\n (config.compatibility_date ?? \"\") >= \"2025-04-01\")\n )\n for (const [k, v] of Object.entries(config.vars ?? {}))\n if (typeof v === \"string\") process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, code) => {\n isolateEntry ??= buildIsolateEntry();\n await isolateEntry;\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n 'export * from \"./cloudflare-workers.ts\";',\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return { source: out.outputFiles[0].text };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|
|
1
|
+
{"version":3,"file":"node-project.js","sourceRoot":"","sources":["../../src/project/node-project.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,E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QAAQ;KACnB,CAAC,CAAC;IACH,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,wFAAwF;AACxF,SAAS,wBAAwB,CAAC,KAAkB;IAClD,MAAM,CAAC,GAAG,UAAqC,CAAC;IAChD,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,oBAAoB,KAAK,cAAc,CAAC;IAC1C,uEAAuE;IACvE,CAAC,CAAC,kBAAkB,KAAK,IAAI,KAAK,CAChC,EAAE,EACF,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAC5E,CAAC;AACJ,CAAC;AACD,MAAM,cAAc,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC","sourcesContent":["import {\n existsSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { builtinModules, createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { Worker as NodeWorker } from \"node:worker_threads\";\nimport { build } from \"esbuild\";\nimport { applyD1Migrations } from \"../bindings/d1-migrations.js\";\nimport {\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport type { WorkerModule } from \"../core/runtime.js\";\nimport { isolatedModuleLoader } from \"../isolate/host.js\";\nimport type { PortLike } from \"../isolate/protocol.js\";\nimport type { CellStorage } from \"../ports.js\";\nimport * as workersClasses from \"./cloudflare-workers.js\";\nimport { parseJsonc } from \"./jsonc.js\";\nimport { ownModule } from \"./own-module.js\";\nimport { type WorkerScope, workerScope } from \"./worker-scope.js\";\nimport {\n createProjectRuntime,\n loadTimeEnv,\n type ProjectHost,\n type ProjectRuntime,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\n/** Reads `wrangler.jsonc` / `wrangler.json` of a project directory (celld reads the same files). */\nexport function readWranglerConfig(dir: string): WranglerConfig {\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return parseJsonc(readFileSync(p, \"utf8\")) as WranglerConfig;\n }\n throw new Error(`no wrangler.jsonc or wrangler.json in ${dir}`);\n}\n\n/** A bare Node.js built-in specifier (\"path\", \"fs/promises\"), not one of a package. */\nconst nodeBuiltinName = new RegExp(\n `^(${builtinModules\n .filter((m) => !m.startsWith(\"_\") && !m.includes(\":\"))\n .map((m) => m.replace(/[/]/g, \"\\\\/\"))\n .join(\"|\")})$`,\n);\n\n/**\n * Node host: bundles `main` with esbuild (as `celld deploy` does) and builds the runtime.\n * `cloudflare:workers` resolves to cellb's module so user classes extend the\n * runtime's own DurableObject / WorkerEntrypoint.\n */\n/** Bundles Worker code (a file, or in-memory modules) with the runtime's module mappings, then imports it. */\nexport async function bundleWorker(\n entry: { path: string } | { modules: Record<string, string>; main: string },\n logs?: LogSink,\n outbound?: typeof fetch,\n opts: { nodeCompat?: boolean; standardBinaryType?: boolean; scope?: WorkerScope } = {},\n): Promise<WorkerModule> {\n // `env` and `exports` of `cloudflare:workers` belong to one Worker: the bundle reads them\n // from its own scope (empty objects for code that has none).\n const scopeKey = opts.scope ? `s${Math.random().toString(36).slice(2)}` : \"\";\n if (opts.scope) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[scopeKey] = opts.scope;\n }\n // Loaded code gets a bundle-local `fetch` (globalOutbound policy)…\n const outboundKey = outbound ? `o${Math.random().toString(36).slice(2)}` : \"\";\n if (outbound) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[outboundKey] = outbound;\n }\n // …and a bundle-local `console` that also feeds its Tail Workers.\n const consoleKey = logs ? `c${Math.random().toString(36).slice(2)}` : \"\";\n if (logs) {\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const registry = g.__cellsConsoles as Record<string, unknown>;\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n registry[consoleKey] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n }\n const outDir = mkdtempSync(join(tmpdir(), \"cells-worker-\"));\n const out = join(outDir, \"worker.mjs\");\n const cfWorkers = ownModule(import.meta.dirname, \"cloudflare-workers\");\n // This bundle's `cloudflare:workers`: the runtime's classes plus its own `env` and `exports`.\n // A file of its own, kept out of the bundle so it adds no names to the Worker's scope.\n const workersModule = join(outDir, \"cloudflare-workers.mjs\");\n writeFileSync(\n workersModule,\n [\n `export * from ${JSON.stringify(cfWorkers)};`,\n `const scope = globalThis.__cellsWorkerScopes?.[${JSON.stringify(scopeKey)}];`,\n \"export const env = scope ? scope.env : {};\",\n \"export const exports = scope ? scope.exports : {};\",\n \"export const waitUntil = (p) => scope?.waitUntil(p);\",\n ].join(\"\\n\"),\n );\n const memory = \"modules\" in entry ? entry.modules : undefined;\n await build({\n entryPoints: [\n memory ? `memory:${(entry as { main: string }).main}` : (entry as { path: string }).path,\n ],\n outfile: out,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n // As `celld deploy` resolves packages: workerd's conditions, then `module` and `main` (the\n // neutral platform has no main fields, so a package with only `main` would not resolve).\n conditions: [\"workerd\", \"worker\", \"browser\"],\n mainFields: [\"module\", \"main\"],\n target: \"es2022\",\n logLevel: \"silent\",\n // nodejs_compat: CommonJS dependencies `require()` Node's built-ins (mime-types requires\n // node:path), as they may under workerd's nodejs_compat. In an ES module bundle esbuild's\n // require shim needs a `require` in scope: vitest's module runner provides one, plain Node\n // does not.\n ...(opts.nodeCompat\n ? {\n banner: {\n js: 'import { createRequire as __cellbCreateRequire } from \"node:module\";\\nconst require = __cellbCreateRequire(import.meta.url);',\n },\n }\n : {}),\n inject: [\n ownModule(import.meta.dirname, \"workers-globals\"),\n ...(logs ? [\"cellb:console\"] : []),\n ...(outbound ? [\"cellb:fetch\"] : []),\n ],\n plugins: [\n {\n name: \"cells-modules\",\n setup(b) {\n b.onResolve({ filter: /^cellb:console$/ }, () => ({\n path: \"console\",\n namespace: \"cells-console\",\n }));\n // nodejs_compat on a Node host: `node:*` are the real Node.js modules.\n if (opts.nodeCompat) {\n b.onResolve({ filter: /^node:/ }, (a) => ({ path: a.path, external: true }));\n // workerd's nodejs_compat also takes the bare names (\"path\", \"fs/promises\").\n b.onResolve({ filter: nodeBuiltinName }, (a) => ({\n path: `node:${a.path}`,\n external: true,\n }));\n }\n b.onResolve({ filter: /^cellb:compat$/ }, () => ({\n path: \"compat\",\n namespace: \"cells-compat\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-compat\" }, () => ({\n contents: `export const standardBinaryType = ${!!opts.standardBinaryType};`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cellb:fetch$/ }, () => ({\n path: \"fetch\",\n namespace: \"cells-fetch\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-fetch\" }, () => ({\n contents: `export const fetch = globalThis.__cellsOutbound[${JSON.stringify(outboundKey)}];`,\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"cells-console\" }, () => ({\n contents: `export const console = globalThis.__cellsConsoles[${JSON.stringify(consoleKey)}];`,\n loader: \"js\",\n }));\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: workersModule,\n external: true,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n external: true,\n }));\n b.onResolve({ filter: /^cellb:ws$/ }, () => ({\n path: ownModule(import.meta.dirname, \"workers-globals-module\"),\n external: true,\n }));\n if (!memory) return;\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: memory[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return (await import(/* @vite-ignore */ out)) as WorkerModule;\n}\n\n/** Worker Loader on Node: compiles `WorkerCode.modules` with esbuild (as celld compiles loaded code). */\nexport const nodeModuleLoader: ModuleLoader = async (_id, code, logs) => {\n const outbound = outboundFetch(code);\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n // `env` and `exports` of the loaded code's `cloudflare:workers` are its own (WorkerCode.env).\n const env = code.env ?? {};\n const scope = workerScope(env);\n const module = (await bundleWorker({ modules, main: code.mainModule }, logs, outbound, {\n scope,\n })) as Record<string, unknown>;\n scope.bind({ env, exports: ctxExports(module, env) });\n return module;\n};\n\nexport async function loadNodeProject(\n dir: string,\n host: Omit<ProjectHost, \"loadModules\"> & Partial<Pick<ProjectHost, \"loadModules\">>,\n): Promise<ProjectRuntime & { config: WranglerConfig }> {\n const config = readWranglerConfig(dir);\n if (!config.main && !config.assets)\n throw new Error(\"wrangler config has neither `main` nor `assets`\");\n const flags = config.compatibility_flags ?? [];\n const nodeCompat = flags.some((f) => f.startsWith(\"nodejs_compat\"));\n const standardBinaryType = flags.includes(\"websocket_standard_binary_type\");\n // The module reads `env` from `cloudflare:workers` while it is evaluated, before the\n // runtime exists: until then the scope holds the configuration's vars (and `ai`).\n const scope = workerScope(loadTimeEnv(config, host.ai));\n // A bundle built elsewhere for cellb (cellbHostModule: webrun-bundler in a browser, say) reads\n // the runtime from globals, as in the browser realm: set them here too, so the same bundle\n // runs on Node. (One such project per process: the globals are the process's.)\n installHostModuleGlobals(scope);\n // As the browser host: nodejs_compat fills process.env with the text vars (from compatibility\n // date 2025-04-01). Node shares its real process with the Worker, so they land there.\n if (\n nodeCompat &&\n !flags.includes(\"nodejs_compat_do_not_populate_process_env\") &&\n (flags.includes(\"nodejs_compat_populate_process_env\") ||\n (config.compatibility_date ?? \"\") >= \"2025-04-01\")\n )\n for (const [k, v] of Object.entries(config.vars ?? {}))\n if (typeof v === \"string\") process.env[k] ??= v;\n const module = config.main\n ? await bundleWorker({ path: resolve(dir, config.main) }, undefined, undefined, {\n nodeCompat,\n standardBinaryType,\n scope,\n })\n : ({ default: {} } as WorkerModule);\n const assetFiles = config.assets?.directory\n ? readAssetDirectory(resolve(dir, config.assets.directory))\n : undefined;\n const project = createProjectRuntime(config, module, {\n loadModules: nodeModuleLoader,\n // own realm, as celld; facets logged like the root's\n isolatedModules: nodeIsolatedLoader(() => host.storage),\n assetFiles,\n ...host,\n });\n scope.bind(project.runtime);\n return { ...project, config };\n}\n\n/** Reads an assets directory into \"/path\" → bytes (what `celld deploy` uploads). */\nexport function readAssetDirectory(root: string): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n const walk = (dir: string, prefix: string) => {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name);\n if (statSync(full).isDirectory()) walk(full, `${prefix}${name}/`);\n else files.set(`${prefix}${name}`, new Uint8Array(readFileSync(full)));\n }\n };\n walk(root, \"/\");\n return files;\n}\n\n/**\n * `celld d1 migrations apply DATABASE` for a Node-hosted project: reads\n * `migrations_dir` (default \"migrations\") of the `d1_databases` entry and applies what is new.\n */\nexport async function applyNodeD1Migrations(\n dir: string,\n runtime: { env: Record<string, unknown> },\n database: string,\n) {\n const config = readWranglerConfig(dir);\n const d1 = config.d1_databases?.find(\n (d) => d.database_name === database || d.binding === database,\n );\n if (!d1) throw new Error(`no d1_databases entry named ${database}`);\n const mdir = resolve(dir, (d1 as { migrations_dir?: string }).migrations_dir ?? \"migrations\");\n const files: [string, string][] = existsSync(mdir)\n ? readdirSync(mdir).map((f) => [f, readFileSync(join(mdir, f), \"utf8\")])\n : [];\n return applyD1Migrations(\n runtime.env[d1.binding] as never,\n files,\n (d1 as { migrations_table?: string }).migrations_table ?? \"d1_migrations\",\n );\n}\n\n/**\n * Loaded Workers in worker threads (one realm each), like celld's isolates. The code is\n * bundled with esbuild (cloudflare:workers bundled in) and imported in the thread from a\n * data: URL; Durable Object classes for facets still load in this realm.\n */\nlet isolateEntry: Promise<string> | undefined;\nexport function nodeIsolatedLoader(storage?: () => CellStorage | undefined): ModuleLoader {\n return isolatedModuleLoader({\n storage,\n spawn: () => {\n const port = new NodeWorker(new URL(`file://${isolateEntryPathSync()}`));\n port.unref(); // an idle isolate never keeps the process alive\n return { port: port as unknown as PortLike, terminate: () => void port.terminate() };\n },\n prepare: async (_id, code) => {\n isolateEntry ??= buildIsolateEntry();\n await isolateEntry;\n const modules: Record<string, string> = {};\n for (const [name, m] of Object.entries(code.modules)) modules[name] = moduleText(m);\n const out = await build({\n entryPoints: [`memory:${code.mainModule}`],\n write: false,\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2022\",\n logLevel: \"silent\",\n plugins: [\n {\n name: \"isolate-modules\",\n setup(b) {\n // The loaded Worker is its thread's own: `env` and `exports` are the scope\n // serveIsolate keeps for it.\n b.onResolve({ filter: /^cloudflare:workers$/ }, () => ({\n path: \"cloudflare:workers\",\n namespace: \"isolate-workers\",\n }));\n b.onLoad({ filter: /.*/, namespace: \"isolate-workers\" }, () => ({\n contents: [\n // cloudflare-workers.js in the published package (dist/), .ts in the sources.\n `export * from ${JSON.stringify(ownModule(import.meta.dirname, \"cloudflare-workers\"))};`,\n \"export const env = globalThis.__cellsProjectScope.env, exports = globalThis.__cellsProjectScope.exports, waitUntil = (p) => globalThis.__cellsProjectScope.waitUntil(p);\",\n ].join(\"\\n\"),\n loader: \"js\",\n resolveDir: import.meta.dirname,\n }));\n b.onResolve({ filter: /^cloudflare:email$/ }, () => ({\n path: ownModule(import.meta.dirname, \"cloudflare-email\"),\n }));\n b.onResolve({ filter: /^memory:/ }, (a) => ({\n path: a.path.slice(7),\n namespace: \"memory\",\n }));\n b.onResolve({ filter: /^\\.{1,2}\\// }, (a) =>\n a.namespace === \"memory\"\n ? {\n path: new URL(a.path, `file:///${a.importer}`).pathname.slice(1),\n namespace: \"memory\",\n }\n : undefined,\n );\n b.onLoad({ filter: /.*/, namespace: \"memory\" }, (a) => ({\n contents: modules[a.path],\n loader: \"js\",\n }));\n },\n },\n ],\n });\n return { source: out.outputFiles[0].text };\n },\n });\n}\n\nlet isolateEntryFile = \"\";\nfunction isolateEntryPathSync(): string {\n if (!isolateEntryFile) throw new Error(\"isolate entry not built yet\");\n return isolateEntryFile;\n}\nasync function buildIsolateEntry(): Promise<string> {\n isolateEntryFile = join(mkdtempSync(join(tmpdir(), \"cells-isolate-\")), \"isolate.mjs\");\n await build({\n entryPoints: [ownModule(import.meta.dirname, \"../isolate/node-entry\")],\n outfile: isolateEntryFile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: \"node22\",\n logLevel: \"silent\",\n });\n return isolateEntryFile;\n}\n\n/** The globals `@statewalker/cellb/host-modules` bundles read (see host-modules.ts). */\nfunction installHostModuleGlobals(scope: WorkerScope): void {\n const g = globalThis as Record<string, unknown>;\n g.__cellsProjectScope = scope;\n g.__cellsWorkersModule ??= workersClasses;\n // node:* from Node itself (the browser realm gives cellb's polyfills).\n g.__cellsNodeModules ??= new Proxy(\n {},\n { get: (_t, k) => (typeof k === \"string\" ? requireBuiltin(k) : undefined) },\n );\n}\nconst requireBuiltin = createRequire(import.meta.url);\n"]}
|