@statewalker/cellb 0.8.9 → 0.9.2
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 +10 -6
- package/dist/adapters/node-sqlite-module.d.ts +6 -0
- package/dist/adapters/node-sqlite-module.js +12 -0
- package/dist/adapters/node-sqlite-module.js.map +1 -1
- package/dist/adapters/node-sqlite.js +3 -3
- package/dist/adapters/node-sqlite.js.map +1 -1
- package/dist/adapters/wasm-sqlite.d.ts +2 -0
- package/dist/adapters/wasm-sqlite.js +15 -0
- package/dist/adapters/wasm-sqlite.js.map +1 -1
- package/dist/bindings/cron.js +9 -2
- package/dist/bindings/cron.js.map +1 -1
- package/dist/bindings/module-registry.d.ts +19 -9
- package/dist/bindings/module-registry.js +42 -30
- package/dist/bindings/module-registry.js.map +1 -1
- package/dist/bucket/sqlite-object-store.js +2 -2
- package/dist/bucket/sqlite-object-store.js.map +1 -1
- package/dist/core/alarms.js +12 -2
- package/dist/core/alarms.js.map +1 -1
- package/dist/isolate/function-imports.d.ts +10 -0
- package/dist/isolate/function-imports.js +93 -0
- package/dist/isolate/function-imports.js.map +1 -0
- package/dist/isolate/isolate-worker.js +5 -1
- package/dist/isolate/isolate-worker.js.map +1 -1
- package/dist/isolate/protocol.js +17 -3
- package/dist/isolate/protocol.js.map +1 -1
- package/dist/project/browser-host.d.ts +2 -0
- package/dist/project/browser-host.js +2 -0
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/browser-load.js +1 -0
- package/dist/project/browser-load.js.map +1 -1
- package/dist/project/browser-modules.d.ts +7 -1
- package/dist/project/browser-modules.js +5 -1
- package/dist/project/browser-modules.js.map +1 -1
- package/dist/project/browser-tabs.d.ts +1 -1
- package/dist/project/browser-tabs.js.map +1 -1
- package/dist/project/built-project.d.ts +7 -0
- package/dist/project/built-project.js.map +1 -1
- package/dist/project/node-project.js +9 -6
- package/dist/project/node-project.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @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AAgB,CAAC,KAAK,EAAE,EAAE;YACxB,MAAM,QAAQ,GAAG,CAAC,IAAa,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,EAAkB,CAAC,CAAC;YACtE,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;YAC5B,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAC1B,CAAC;QACD,mBAAmB,CAAC,KAAK,EAAE,EAAE;YAC3B,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC,CAAC;YAC1C,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { fetchOverDuplex, serveFetchOverDuplex } from \"@statewalker/webrun-http-streams\";\nimport {\n callPort,\n duplexOverPort,\n getPortCloseSignal,\n listenPort,\n type MessageTarget,\n multiplexPort,\n NO_TIMEOUT,\n type PortMux,\n serveDuplexOverPort,\n structuredCodec,\n} from \"@statewalker/webrun-rpc\";\nimport { cross, pipeTo, rpcPromise, STUB } from \"../core/handles.js\";\nimport { withUrl } from \"../core/request-body.js\";\nimport type { Frame } from \"../ws/frames.js\";\nimport { CellsResponse, CfWebSocket, takeClientEnd } from \"../ws/server.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\n\n/**\n * Isolation for loaded Workers (celld runs each in its own V8 isolate): the loaded code runs\n * in a separate realm — a worker thread on Node, a Dedicated Worker in browsers — and talks\n * to the host over one MessagePort, multiplexed with `@statewalker/webrun-rpc`. The host keeps\n * everything else: bindings in the loaded Worker's env are reached through stubs, and its logs\n * come back for Tail Workers. Errors cross with their own properties (`name`, `code`, …).\n * Functions, `RpcTarget`s and stubs anywhere in a call or result cross by reference (as\n * workerd passes them): the far side gets a stub whose calls come back.\n *\n * Calls (one port, both directions; each names an `answer`, which the serving side keeps until\n * the caller has the result, so calls on it can be sent before then — promise pipelining):\n * host → isolate load {source|url, env, outbound} → loaded {exports}\n * call {name, method, args, props} → result\n * isolate → host log {level, args}\n * either way ref {id|on, path, args} (a call on a stub of the other side's value, or\n * on answer `on`: `path` is the property path\n * called, [] the value itself)\n * release {id|answer} (that stub was disposed or collected; the caller\n * has that answer)\n * Fetches: one port per request (meta: its target and URL), HTTP/1.1 with streamed bodies,\n * as cells-http over a port (src/transport/port.ts): host → isolate to an export or facet,\n * isolate → host for the loaded code's global `fetch()` when a `globalOutbound` Fetcher routes it.\n * A WebSocket upgrade (host → isolate) has a port of its own instead, since HTTP/1.1 drops the\n * `Upgrade` header: its meta carries the request's method and headers; the isolate answers with\n * the response's head and closes the port. A 101's head carries the socket's own MessagePort,\n * transferred, and the frames the server sent before the 101 (replayed by the host's end): the\n * socket's frames then go straight between the client and the isolate, outside the multiplexer\n * and through no relay in the isolate, so open sockets hold none of its ports (it allows\n * `maxPorts` at once) and a socket's 1001 reaches its client before the isolate ends.\n */\nexport interface PortLike {\n postMessage(msg: unknown, transfer?: Transferable[]): void;\n addEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n removeEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n on?(type: \"message\", fn: (data: unknown) => void): void;\n off?(type: \"message\", fn: (data: unknown) => void): void;\n start?(): void;\n}\n\n/** Where a fetch goes in the isolate: an export of the loaded Worker, or one of its facets. */\nexport type FetchTarget =\n | { name: string; props?: unknown }\n | { className: string; cellKey: string };\ntype Fetch = (target: FetchTarget, req: Request) => Promise<Response>;\n\nexport type Call = <T = unknown>(msg: object) => Promise<T>;\ntype Handle = (msg: any) => Promise<unknown>;\n\n/**\n * The host's end of an isolate's port: one webrun-rpc multiplexer over it, a calls port on\n * which each side calls the other (`callPort`/`listenPort`, no timeout: a call lasts as long\n * as the work it starts), and a port per fetch. `outbound` serves the loaded code's global\n * `fetch()` (its `globalOutbound` Fetcher).\n */\nexport async function hostPort(\n port: PortLike,\n handle: Handle,\n outbound?: (req: Request) => Promise<Response>,\n): Promise<{ call: Call; fetch: Fetch; close(reason: unknown): Promise<void> }> {\n const bodies = new Bodies();\n const mux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"initiator\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind !== \"outbound\" || !outbound) return false;\n serveFetch(p, m.url, outbound);\n return true;\n },\n });\n const call = callsOver(await mux.openPort({ kind: \"calls\" }), handle, mux, bodies);\n const fetch: Fetch = (target, req) =>\n isUpgrade(req)\n ? upgradeOver(mux, { kind: \"upgrade\", target }, req)\n : fetchOver(mux, { kind: \"fetch\", target }, req);\n // Closing the multiplexer rejects every call in flight, and every later one, with `reason`.\n return { call, fetch, close: (reason) => mux.close(reason) };\n}\n\n/**\n * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host\n * for happens while serving a host call, so the calls port is open by then. `outbound` sends\n * a fetch to the host's `globalOutbound`.\n */\nexport function isolatePort(\n port: PortLike,\n handle: Handle,\n fetch: Fetch,\n): { call: Call; outbound: (req: Request) => Promise<Response> } {\n let calls: Call | undefined;\n const bodies = new Bodies();\n const mux: PortMux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"responder\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; target: FetchTarget; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind === \"fetch\") {\n serveFetch(p, m.url, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind === \"upgrade\") {\n serveUpgrade(p, m as unknown as UpgradeMeta, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind !== \"calls\" || calls) return false;\n calls = callsOver(p, handle, mux, bodies);\n return true;\n },\n });\n return {\n call: (msg) => calls!(msg),\n outbound: (req) => fetchOver(mux, { kind: \"outbound\" }, req),\n };\n}\n\n/** A fetch over a new port of `mux`; the URL rides in the meta (the HTTP/1.1 wire drops its scheme). */\nfunction fetchOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n return fetchOverDuplex(\n (input) =>\n (async function* () {\n yield* duplexOverPort(await mux.openPort({ ...meta, url: req.url }))(input);\n })(),\n req,\n );\n}\n\n/** Serves the fetch on port `p` (its URL from the meta) with `fetch`. */\nfunction serveFetch(p: MessageTarget, url: string, fetch: (req: Request) => Promise<Response>) {\n serveDuplexOverPort(\n p,\n serveFetchOverDuplex((req) => withUrl(req, url).then(fetch).catch(throwOwn)),\n );\n}\n\nconst isUpgrade = (req: Request) => req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\";\n\ninterface UpgradeMeta {\n url: string;\n method: string;\n headers: [string, string][];\n}\n/**\n * Ports of an isolate's multiplexer open at once: the calls port, and one per fetch or upgrade\n * in flight (each closes when its exchange ends). `globalThis.__cellbMaxPorts` overrides it, as\n * for src/transport/port.ts.\n */\nconst maxPorts = () => (globalThis as { __cellbMaxPorts?: number }).__cellbMaxPorts ?? 4096;\n\n/** The isolate's answer to an upgrade: the head of its response, or the error it threw. */\ntype UpgradeHead =\n | {\n status: number;\n statusText?: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n /** A 101's socket: the port of its client end, transferred. */\n socket?: MessagePort;\n /** A 101's frames that reached its client end before the hand-over. */\n frames?: Frame[];\n }\n | { error: unknown };\n\n/** Statuses whose response has no body (`new Response(body, …)` refuses one). */\nconst nullBody = (status: number) => [101, 204, 205, 304].includes(status);\n\n/**\n * A WebSocket upgrade over a port of its own, closed once the isolate's answer is in. A 101\n * becomes a Workers response whose `webSocket` is a client end over the socket's own port.\n */\nasync function upgradeOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n const p = await mux.openPort({\n ...meta,\n url: req.url,\n method: req.method,\n headers: [...req.headers],\n } satisfies UpgradeMeta);\n return new Promise((resolve, reject) => {\n // A port closed without an answer (the isolate refused it, or could not post one)\n // fails the upgrade rather than leaving it pending.\n const closed = getPortCloseSignal(p);\n const onClosed = () => {\n p.removeEventListener(\"message\", onHead);\n reject(\n closed?.reason ?? new Error(\"cellb: the isolate closed the upgrade without an answer\"),\n );\n };\n closed?.addEventListener(\"abort\", onClosed, { once: true });\n const onHead = (e: MessageEvent) => {\n p.removeEventListener(\"message\", onHead);\n closed?.removeEventListener(\"abort\", onClosed);\n void p.close?.();\n try {\n const head = e.data as UpgradeHead;\n if (\"error\" in head) throw head.error;\n if (head.status === 101 && head.socket)\n return resolve(\n new CellsResponse(null, {\n status: 101,\n headers: head.headers,\n webSocket: new CfWebSocket(head.socket, head.frames),\n }),\n );\n resolve(\n new Response(nullBody(head.status) ? null : head.body, {\n status: head.status,\n statusText: head.statusText,\n headers: head.headers,\n }),\n );\n } catch (err) {\n reject(err);\n }\n };\n p.addEventListener(\"message\", onHead);\n void p.start?.();\n });\n}\n\n/** Serves an upgrade on port `p`: a 101 hands over its client end's port; then `p` closes. */\nfunction serveUpgrade(\n p: MessageTarget,\n meta: UpgradeMeta,\n fetch: (req: Request) => Promise<Response>,\n) {\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from `new Request()`: carried over here.\n const headers = new Headers(meta.headers);\n const req = carryWebSocketHeaders(\n headers,\n new Request(meta.url, { method: meta.method, headers }),\n );\n const answer = (head: UpgradeHead, transfer: Transferable[] = []) => {\n try {\n // The multiplexer drops a message it cannot copy, so check before posting; a 101\n // head is not checked, since its socket port is transferred rather than copied.\n if (transfer.length === 0) cloneable(head);\n p.postMessage(head, transfer);\n } catch {\n // An error that cannot be copied (a function in its `cause`, say): its name and message.\n const e = (head as { error?: { name?: unknown; message?: unknown } }).error;\n p.postMessage({\n error: Object.assign(new Error(String(e?.message ?? e)), {\n name: String(e?.name ?? \"Error\"),\n }),\n } satisfies UpgradeHead);\n }\n };\n void (async () => {\n try {\n const res = await fetch(req);\n const ws = (res as { webSocket?: CfWebSocket | null }).webSocket;\n if (res.status === 101 && ws) {\n const { port: socket, frames } = takeClientEnd(ws);\n answer({ status: 101, headers: [...res.headers], body: null, socket, frames }, [socket]);\n } else\n answer({\n status: res.status,\n statusText: res.statusText,\n headers: [...res.headers],\n body: nullBody(res.status) ? null : await res.arrayBuffer(),\n });\n } catch (error) {\n answer({ error });\n }\n void p.close?.();\n })();\n}\n\n/** Marks a Request, Response, Headers or ReadableStream in a message: `{ [WIRE]: kind, … }`. */\nconst WIRE = \"\\u0000cellb.wire\";\n\n// The realm's own classes, before the isolate entry replaces the globals with its subclasses\n// (CellsRequest, CellsResponse): instances of either are instances of these.\nconst NativeRequest = globalThis.Request;\nconst NativeResponse = globalThis.Response;\nconst NativeHeaders = globalThis.Headers;\nconst NativeReadableStream = globalThis.ReadableStream;\n\n/**\n * The bodies one side has sent and the other has not read yet, by id. The reader opens a port\n * `{ kind: \"body\", id }` on the multiplexer when it first pulls, and the body streams over it,\n * as a fetch's body does; a reader that drops the body unread sends `release {body}` instead.\n */\nclass Bodies {\n #last = 0;\n #streams = new Map<number, ReadableStream>();\n add(stream: ReadableStream): number {\n this.#streams.set(++this.#last, stream);\n return this.#last;\n }\n /** The last id handed out, for `releaseSince`. */\n mark(): number {\n return this.#last;\n }\n /** Releases the bodies added after `mark` (a message that could not be sent). */\n releaseSince(mark: number): void {\n for (let id = mark + 1; id <= this.#last; id++) this.release(id);\n }\n release(id: number): void {\n const stream = this.#streams.get(id);\n this.#streams.delete(id);\n void stream?.cancel().catch(() => {});\n }\n /** Serves body `id` on port `p`; false (the port is refused) if there is no such body. */\n serve(p: MessageTarget, id: number): boolean {\n const stream = this.#streams.get(id);\n if (!stream) return false;\n this.#streams.delete(id);\n const encoder = new TextEncoder();\n serveDuplexOverPort(p, async function* () {\n // A reader, not `for await`: not every engine iterates a ReadableStream (Safari).\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value: chunk } = await reader.read();\n if (done) return;\n yield typeof chunk === \"string\"\n ? encoder.encode(chunk)\n : ArrayBuffer.isView(chunk)\n ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n : new Uint8Array(chunk as ArrayBuffer);\n }\n } finally {\n // The reader stopped early (the port was abandoned): the stream is cancelled.\n void reader.cancel().catch(() => {});\n }\n });\n return true;\n }\n}\n\n/**\n * A Request, Response, Headers or ReadableStream as a message can carry it (workerd's RPC passes\n * them; a port cannot clone them): its head copied, its body registered in `bodies` to stream\n * when read. Anything else is returned as it is.\n */\nfunction toWire(v: unknown, bodies: Bodies): unknown {\n if (v instanceof NativeHeaders) return { [WIRE]: \"headers\", entries: [...v] };\n if (v instanceof NativeReadableStream) return { [WIRE]: \"stream\", body: bodies.add(v) };\n if (v instanceof NativeResponse) {\n if ((v as { webSocket?: unknown }).webSocket)\n throw new DOMException(\n \"A WebSocket response cannot be passed in an RPC call; return it from fetch().\",\n \"DataCloneError\",\n );\n return {\n [WIRE]: \"response\",\n status: v.status,\n statusText: v.statusText,\n url: v.url,\n headers: [...v.headers],\n body: v.body ? bodies.add(v.body) : null,\n };\n }\n if (v instanceof NativeRequest)\n return {\n [WIRE]: \"request\",\n url: v.url,\n method: v.method,\n headers: [...v.headers],\n redirect: v.redirect,\n body: v.body ? bodies.add(v.body) : null,\n };\n return v;\n}\n\n/** Releases a body that was never read, once its stream is collected. */\nconst unread = new FinalizationRegistry<() => void>((release) => release());\n\n/**\n * The other side's body `id` as a stream: the first pull opens its port, so a body nobody\n * reads costs nothing but its release.\n */\nfunction remoteBody(mux: PortMux, id: number, release: (id: number) => void): ReadableStream {\n let chunks: AsyncIterator<Uint8Array> | undefined;\n const token = {};\n const stream = new NativeReadableStream<Uint8Array>({\n async pull(controller) {\n if (!chunks) {\n unread.unregister(token);\n const port = await mux.openPort({ kind: \"body\", id });\n chunks = duplexOverPort(port)([])[Symbol.asyncIterator]();\n }\n const { done, value } = await chunks.next();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n async cancel(reason) {\n if (chunks) await chunks.return?.(reason);\n else {\n unread.unregister(token);\n release(id);\n }\n },\n });\n unread.register(stream, () => release(id), token);\n return stream;\n}\n\n/** Statuses whose Response has no body. */\nconst NULL_BODY = [101, 103, 204, 205, 304];\n\n/** The value `toWire` described, rebuilt; its body streams from the other side when read. */\nfunction fromWire(v: any, mux: PortMux, release: (id: number) => void): unknown {\n const body = (id: number | null) => (id === null ? null : remoteBody(mux, id, release));\n switch (v[WIRE]) {\n case \"headers\":\n return new Headers(v.entries);\n case \"stream\":\n return body(v.body);\n case \"response\": {\n if (NULL_BODY.includes(v.status) && v.body !== null) release(v.body);\n const res = new Response(NULL_BODY.includes(v.status) ? null : body(v.body), {\n status: v.status,\n statusText: v.statusText,\n headers: v.headers,\n });\n if (v.url) Object.defineProperty(res, \"url\", { value: v.url, enumerable: true });\n return res;\n }\n case \"request\":\n return new Request(v.url, {\n method: v.method,\n headers: v.headers,\n redirect: v.redirect,\n body: body(v.body),\n duplex: \"half\",\n } as RequestInit);\n }\n return v;\n}\n\n/** Marks a value passed by reference in a message: `{ [REF]: id }`. */\nconst REF = \"\\u0000cellb.ref\";\n\n/**\n * The calls of one port, with values passed by reference: each side keeps the values it\n * passed (by id, and how many ids hold each); the other side calls them through stubs. A\n * stub's `Symbol.dispose` (or its garbage collection) releases its id; the last release of a\n * value runs the value's own `Symbol.dispose`, as workerd does for an `RpcTarget`. A call\n * returns an RpcPromise: calls on it go to the other side at once, naming its answer.\n */\nfunction callsOver(port: MessageTarget, handle: Handle, mux: PortMux, bodies: Bodies): Call {\n const values = new Map<number, any>();\n const answers = new Map<number, unknown>();\n let lastAnswer = 0;\n const holders = new Map<unknown, number>();\n let lastId = 0;\n const encode = (v: unknown) => {\n const mark = bodies.mark();\n try {\n return cloneable(\n cross(\n v,\n (x) => {\n values.set(++lastId, x);\n holders.set(x, (holders.get(x) ?? 0) + 1);\n return { [REF]: lastId };\n },\n (x) => toWire(x, bodies), // Requests, Responses, Headers, streams; the port copies the rest\n ),\n );\n } catch (e) {\n bodies.releaseSince(mark); // the message is not sent: nobody will read its bodies\n throw e;\n }\n };\n const release = (id: number) => {\n const v = values.get(id);\n if (!values.delete(id)) return;\n const n = (holders.get(v) ?? 1) - 1;\n if (n) holders.set(v, n);\n else {\n holders.delete(v);\n v[Symbol.dispose]?.();\n }\n };\n const send = (msg: object) => callPort(port, msg, { timeout: NO_TIMEOUT }).catch(() => {});\n // Stubs of one id held here: `dup()` makes another, and the id is released (and the other\n // side's value with it, once no other id holds it) when the last of them is disposed or\n // collected.\n const local = new Map<number, number>();\n const drop = (id: number) => {\n const n = (local.get(id) ?? 1) - 1;\n if (n) local.set(id, n);\n else {\n local.delete(id);\n send({ type: \"release\", id });\n }\n };\n const collected = new FinalizationRegistry<number>(drop);\n const stubOf = (id: number) => {\n local.set(id, (local.get(id) ?? 0) + 1);\n let disposed = false;\n const live = () => {\n if (disposed) throw new Error(\"A stub was used after it was disposed.\");\n };\n const invoke = (path: string[], args: unknown[]) => {\n live();\n return call({ type: \"ref\", id, path, args });\n };\n const stub: any = new Proxy(() => {}, {\n apply: (_t, _this, args) => invoke([], args),\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === Symbol.dispose)\n return () => {\n if (disposed) return;\n disposed = true;\n collected.unregister(stub);\n drop(id);\n };\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // workerd's `stub.dup()`: another stub of the same value, disposed on its own.\n if (prop === \"dup\")\n return () => {\n live();\n return stubOf(id);\n };\n return (...args: unknown[]) => invoke([prop], args);\n },\n });\n collected.register(stub, id, stub);\n return stub;\n };\n // Messages arrive as fresh copies: stubs replace the markers in place.\n const decode = (v: any): any => {\n if (Array.isArray(v)) for (let i = 0; i < v.length; i++) v[i] = decode(v[i]);\n else if (v && Object.getPrototypeOf(v) === Object.prototype) {\n if (typeof v[WIRE] === \"string\")\n return fromWire(v, mux, (body) => send({ type: \"release\", body }));\n if (typeof v[REF] === \"number\") return stubOf(v[REF]);\n for (const k of Object.keys(v)) v[k] = decode(v[k]);\n }\n return v;\n };\n const run = (m: any): unknown => {\n if (m.type !== \"ref\") return handle(m);\n if (m.on !== undefined) return pipeTo(answers.get(m.on), m.path, m.args);\n const v = values.get(m.id);\n if (v === undefined) throw new Error(\"A stub was used after it was disposed.\");\n return pipeTo(v, m.path, m.args);\n };\n // The answer is kept as the message arrives: a pipelined call on it may arrive before it\n // settles.\n const serve = async (m: any) => {\n if (m.type === \"release\") {\n if (m.body !== undefined) bodies.release(m.body);\n else if (m.answer === undefined) release(m.id);\n else answers.delete(m.answer);\n return;\n }\n let r: unknown;\n try {\n r = run(m);\n } catch (e) {\n r = Promise.reject(e);\n }\n answers.set(m.answer, r);\n return r;\n };\n listenPort(port, (msg) => serve(decode(msg)).then(encode).catch(throwOwn));\n const call: Call = (msg) => {\n const answer = ++lastAnswer;\n const result = (async () =>\n decode(await callPort(port, encode({ ...msg, answer }), { timeout: NO_TIMEOUT })))();\n // Calls on the answer sent before now are ahead of this release on the port.\n const done = () => send({ type: \"release\", answer });\n result.then(done, done);\n return rpcPromise(result, (path, args) => call({ type: \"ref\", on: answer, path, args }));\n };\n return call;\n}\n\n/** Errors cross with their own properties (so `code` does); `name` is inherited, so copy it. */\nfunction throwOwn(e: unknown): never {\n if (e && typeof e === \"object\")\n Object.defineProperty(e, \"name\", { value: (e as Error).name, enumerable: true });\n throw e;\n}\n\n/**\n * Throws `DataCloneError` for a value the port cannot carry: the multiplexer drops a message\n * it fails to post, and the call would wait forever.\n */\nfunction cloneable<T>(value: T): T {\n structuredClone(value);\n return value;\n}\n\n/** A worker_threads Worker is an EventEmitter; MessagePorts and Dedicated Workers are targets. */\nfunction messageTarget(port: PortLike): MessageTarget {\n if (port.addEventListener) return port as MessageTarget;\n const on = port.on!.bind(port);\n const listeners = new Map<unknown, (data: unknown) => void>();\n return {\n postMessage: (msg, transfer) => port.postMessage(msg, transfer),\n addEventListener(_type, fn) {\n const listener = (data: unknown) => void fn({ data } as MessageEvent);\n listeners.set(fn, listener);\n on(\"message\", listener);\n },\n removeEventListener(_type, fn) {\n port.off?.(\"message\", listeners.get(fn)!);\n listeners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serveFetchOverDuplex } from \"@statewalker/webrun-http-streams\";\nimport {\n callPort,\n duplexOverPort,\n getPortCloseSignal,\n listenPort,\n type MessageTarget,\n multiplexPort,\n NO_TIMEOUT,\n type PortMux,\n serveDuplexOverPort,\n structuredCodec,\n} from \"@statewalker/webrun-rpc\";\nimport { cross, pipeTo, rpcPromise, STUB } from \"../core/handles.js\";\nimport { withUrl } from \"../core/request-body.js\";\nimport type { Frame } from \"../ws/frames.js\";\nimport { CellsResponse, CfWebSocket, takeClientEnd } from \"../ws/server.js\";\nimport { carryWebSocketHeaders } from \"../ws/upgrade.js\";\n\n/**\n * Isolation for loaded Workers (celld runs each in its own V8 isolate): the loaded code runs\n * in a separate realm — a worker thread on Node, a Dedicated Worker in browsers — and talks\n * to the host over one MessagePort, multiplexed with `@statewalker/webrun-rpc`. The host keeps\n * everything else: bindings in the loaded Worker's env are reached through stubs, and its logs\n * come back for Tail Workers. Errors cross with their own properties (`name`, `code`, …).\n * Functions, `RpcTarget`s and stubs anywhere in a call or result cross by reference (as\n * workerd passes them): the far side gets a stub whose calls come back.\n *\n * Calls (one port, both directions; each names an `answer`, which the serving side keeps until\n * the caller has the result, so calls on it can be sent before then — promise pipelining):\n * host → isolate load {source|url, env, outbound} → loaded {exports}\n * call {name, method, args, props} → result\n * isolate → host log {level, args}\n * either way ref {id|on, path, args} (a call on a stub of the other side's value, or\n * on answer `on`: `path` is the property path\n * called, [] the value itself)\n * release {id|answer} (that stub was disposed or collected; the caller\n * has that answer)\n * Fetches: one port per request (meta: its target and URL), HTTP/1.1 with streamed bodies,\n * as cells-http over a port (src/transport/port.ts): host → isolate to an export or facet,\n * isolate → host for the loaded code's global `fetch()` when a `globalOutbound` Fetcher routes it.\n * A WebSocket upgrade (host → isolate) has a port of its own instead, since HTTP/1.1 drops the\n * `Upgrade` header: its meta carries the request's method and headers; the isolate answers with\n * the response's head and closes the port. A 101's head carries the socket's own MessagePort,\n * transferred, and the frames the server sent before the 101 (replayed by the host's end): the\n * socket's frames then go straight between the client and the isolate, outside the multiplexer\n * and through no relay in the isolate, so open sockets hold none of its ports (it allows\n * `maxPorts` at once) and a socket's 1001 reaches its client before the isolate ends.\n */\nexport interface PortLike {\n postMessage(msg: unknown, transfer?: Transferable[]): void;\n addEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n removeEventListener?(type: \"message\", fn: (e: { data: unknown }) => void): void;\n on?(type: \"message\", fn: (data: unknown) => void): void;\n off?(type: \"message\", fn: (data: unknown) => void): void;\n start?(): void;\n}\n\n/** Where a fetch goes in the isolate: an export of the loaded Worker, or one of its facets. */\nexport type FetchTarget =\n | { name: string; props?: unknown }\n | { className: string; cellKey: string };\ntype Fetch = (target: FetchTarget, req: Request) => Promise<Response>;\n\nexport type Call = <T = unknown>(msg: object) => Promise<T>;\ntype Handle = (msg: any) => Promise<unknown>;\n\n/**\n * The host's end of an isolate's port: one webrun-rpc multiplexer over it, a calls port on\n * which each side calls the other (`callPort`/`listenPort`, no timeout: a call lasts as long\n * as the work it starts), and a port per fetch. `outbound` serves the loaded code's global\n * `fetch()` (its `globalOutbound` Fetcher).\n */\nexport async function hostPort(\n port: PortLike,\n handle: Handle,\n outbound?: (req: Request) => Promise<Response>,\n): Promise<{ call: Call; fetch: Fetch; close(reason: unknown): Promise<void> }> {\n const bodies = new Bodies();\n const mux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"initiator\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind !== \"outbound\" || !outbound) return false;\n serveFetch(p, m.url, outbound);\n return true;\n },\n });\n const call = callsOver(await mux.openPort({ kind: \"calls\" }), handle, mux, bodies);\n const fetch: Fetch = (target, req) =>\n isUpgrade(req)\n ? upgradeOver(mux, { kind: \"upgrade\", target }, req)\n : fetchOver(mux, { kind: \"fetch\", target }, req);\n // Closing the multiplexer rejects every call in flight, and every later one, with `reason`.\n return { call, fetch, close: (reason) => mux.close(reason) };\n}\n\n/**\n * The isolate's end: accepts the ports the host opens. Everything the isolate calls the host\n * for happens while serving a host call, so the calls port is open by then. `outbound` sends\n * a fetch to the host's `globalOutbound`.\n */\nexport function isolatePort(\n port: PortLike,\n handle: Handle,\n fetch: Fetch,\n): { call: Call; outbound: (req: Request) => Promise<Response> } {\n let calls: Call | undefined;\n const bodies = new Bodies();\n const mux: PortMux = multiplexPort(messageTarget(port), {\n codec: structuredCodec,\n side: \"responder\",\n maxPorts: maxPorts(),\n onPort(p, meta) {\n const m = meta as { kind?: string; target: FetchTarget; url: string; id: number } | undefined;\n if (m?.kind === \"body\") return bodies.serve(p, m.id);\n if (m?.kind === \"fetch\") {\n serveFetch(p, m.url, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind === \"upgrade\") {\n serveUpgrade(p, m as unknown as UpgradeMeta, (r) => fetch(m.target, r));\n return true;\n }\n if (m?.kind !== \"calls\" || calls) return false;\n calls = callsOver(p, handle, mux, bodies);\n return true;\n },\n });\n return {\n call: (msg) => calls!(msg),\n outbound: (req) => fetchOver(mux, { kind: \"outbound\" }, req),\n };\n}\n\n/** A fetch over a new port of `mux`; the URL rides in the meta (the HTTP/1.1 wire drops its scheme). */\nfunction fetchOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n return fetchOverDuplex(\n (input) =>\n (async function* () {\n yield* duplexOverPort(await mux.openPort({ ...meta, url: req.url }))(input);\n })(),\n req,\n );\n}\n\n/** Serves the fetch on port `p` (its URL from the meta) with `fetch`. */\nfunction serveFetch(p: MessageTarget, url: string, fetch: (req: Request) => Promise<Response>) {\n serveDuplexOverPort(\n p,\n serveFetchOverDuplex((req) => withUrl(req, url).then(fetch).catch(throwOwn)),\n );\n}\n\nconst isUpgrade = (req: Request) => req.headers.get(\"upgrade\")?.toLowerCase() === \"websocket\";\n\ninterface UpgradeMeta {\n url: string;\n method: string;\n headers: [string, string][];\n}\n/**\n * Ports of an isolate's multiplexer open at once: the calls port, and one per fetch or upgrade\n * in flight (each closes when its exchange ends). `globalThis.__cellbMaxPorts` overrides it, as\n * for src/transport/port.ts.\n */\nconst maxPorts = () => (globalThis as { __cellbMaxPorts?: number }).__cellbMaxPorts ?? 4096;\n\n/** The isolate's answer to an upgrade: the head of its response, or the error it threw. */\ntype UpgradeHead =\n | {\n status: number;\n statusText?: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n /** A 101's socket: the port of its client end, transferred. */\n socket?: MessagePort;\n /** A 101's frames that reached its client end before the hand-over. */\n frames?: Frame[];\n }\n | { error: unknown };\n\n/** Statuses whose response has no body (`new Response(body, …)` refuses one). */\nconst nullBody = (status: number) => [101, 204, 205, 304].includes(status);\n\n/**\n * A WebSocket upgrade over a port of its own, closed once the isolate's answer is in. A 101\n * becomes a Workers response whose `webSocket` is a client end over the socket's own port.\n */\nasync function upgradeOver(mux: PortMux, meta: object, req: Request): Promise<Response> {\n const p = await mux.openPort({\n ...meta,\n url: req.url,\n method: req.method,\n headers: [...req.headers],\n } satisfies UpgradeMeta);\n return new Promise((resolve, reject) => {\n // A port closed without an answer (the isolate refused it, or could not post one)\n // fails the upgrade rather than leaving it pending.\n const closed = getPortCloseSignal(p);\n const onClosed = () => {\n p.removeEventListener(\"message\", onHead);\n reject(\n closed?.reason ?? new Error(\"cellb: the isolate closed the upgrade without an answer\"),\n );\n };\n closed?.addEventListener(\"abort\", onClosed, { once: true });\n const onHead = (e: MessageEvent) => {\n p.removeEventListener(\"message\", onHead);\n closed?.removeEventListener(\"abort\", onClosed);\n void p.close?.();\n try {\n const head = e.data as UpgradeHead;\n if (\"error\" in head) throw head.error;\n if (head.status === 101 && head.socket)\n return resolve(\n new CellsResponse(null, {\n status: 101,\n headers: head.headers,\n webSocket: new CfWebSocket(head.socket, head.frames),\n }),\n );\n resolve(\n new Response(nullBody(head.status) ? null : head.body, {\n status: head.status,\n statusText: head.statusText,\n headers: head.headers,\n }),\n );\n } catch (err) {\n reject(err);\n }\n };\n p.addEventListener(\"message\", onHead);\n void p.start?.();\n });\n}\n\n/** Serves an upgrade on port `p`: a 101 hands over its client end's port; then `p` closes. */\nfunction serveUpgrade(\n p: MessageTarget,\n meta: UpgradeMeta,\n fetch: (req: Request) => Promise<Response>,\n) {\n // A browser drops `Upgrade` and `Sec-WebSocket-*` from `new Request()`: carried over here.\n const headers = new Headers(meta.headers);\n const req = carryWebSocketHeaders(\n headers,\n new Request(meta.url, { method: meta.method, headers }),\n );\n const answer = (head: UpgradeHead, transfer: Transferable[] = []) => {\n try {\n // The multiplexer drops a message it cannot copy, so check before posting; a 101\n // head is not checked, since its socket port is transferred rather than copied.\n if (transfer.length === 0) cloneable(head);\n p.postMessage(head, transfer);\n } catch {\n // An error that cannot be copied (a function in its `cause`, say): its name and message.\n const e = (head as { error?: { name?: unknown; message?: unknown } }).error;\n p.postMessage({\n error: Object.assign(new Error(String(e?.message ?? e)), {\n name: String(e?.name ?? \"Error\"),\n }),\n } satisfies UpgradeHead);\n }\n };\n void (async () => {\n try {\n const res = await fetch(req);\n const ws = (res as { webSocket?: CfWebSocket | null }).webSocket;\n if (res.status === 101 && ws) {\n const { port: socket, frames } = takeClientEnd(ws);\n answer({ status: 101, headers: [...res.headers], body: null, socket, frames }, [socket]);\n } else\n answer({\n status: res.status,\n statusText: res.statusText,\n headers: [...res.headers],\n body: nullBody(res.status) ? null : await res.arrayBuffer(),\n });\n } catch (error) {\n answer({ error });\n }\n void p.close?.();\n })();\n}\n\n/** Marks a Request, Response, Headers or ReadableStream in a message: `{ [WIRE]: kind, … }`. */\nconst WIRE = \"\\u0000cellb.wire\";\n\n// The realm's own classes, before the isolate entry replaces the globals with its subclasses\n// (CellsRequest, CellsResponse): instances of either are instances of these.\nconst NativeRequest = globalThis.Request;\nconst NativeResponse = globalThis.Response;\nconst NativeHeaders = globalThis.Headers;\nconst NativeReadableStream = globalThis.ReadableStream;\n\n/**\n * The bodies one side has sent and the other has not read yet, by id. The reader opens a port\n * `{ kind: \"body\", id }` on the multiplexer when it first pulls, and the body streams over it,\n * as a fetch's body does; a reader that drops the body unread sends `release {body}` instead.\n */\nclass Bodies {\n #last = 0;\n #streams = new Map<number, ReadableStream>();\n add(stream: ReadableStream): number {\n this.#streams.set(++this.#last, stream);\n return this.#last;\n }\n /** The last id handed out, for `releaseSince`. */\n mark(): number {\n return this.#last;\n }\n /** Releases the bodies added after `mark` (a message that could not be sent). */\n releaseSince(mark: number): void {\n for (let id = mark + 1; id <= this.#last; id++) this.release(id);\n }\n release(id: number): void {\n const stream = this.#streams.get(id);\n this.#streams.delete(id);\n void stream?.cancel().catch(() => {});\n }\n /** Serves body `id` on port `p`; false (the port is refused) if there is no such body. */\n serve(p: MessageTarget, id: number): boolean {\n const stream = this.#streams.get(id);\n if (!stream) return false;\n this.#streams.delete(id);\n const encoder = new TextEncoder();\n serveDuplexOverPort(p, async function* () {\n // A reader, not `for await`: not every engine iterates a ReadableStream (Safari).\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value: chunk } = await reader.read();\n if (done) return;\n yield typeof chunk === \"string\"\n ? encoder.encode(chunk)\n : ArrayBuffer.isView(chunk)\n ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n : new Uint8Array(chunk as ArrayBuffer);\n }\n } finally {\n // The reader stopped early (the port was abandoned): the stream is cancelled.\n void reader.cancel().catch(() => {});\n }\n });\n return true;\n }\n}\n\n/**\n * A Request, Response, Headers or ReadableStream as a message can carry it (workerd's RPC passes\n * them; a port cannot clone them): its head copied, its body registered in `bodies` to stream\n * when read. Anything else is returned as it is.\n */\nfunction toWire(v: unknown, bodies: Bodies): unknown {\n if (v instanceof NativeHeaders) return { [WIRE]: \"headers\", entries: [...v] };\n if (v instanceof NativeReadableStream) return { [WIRE]: \"stream\", body: bodies.add(v) };\n if (v instanceof NativeResponse) {\n if ((v as { webSocket?: unknown }).webSocket)\n throw new DOMException(\n \"A WebSocket response cannot be passed in an RPC call; return it from fetch().\",\n \"DataCloneError\",\n );\n return {\n [WIRE]: \"response\",\n status: v.status,\n statusText: v.statusText,\n url: v.url,\n headers: [...v.headers],\n body: v.body ? bodies.add(v.body) : null,\n };\n }\n if (v instanceof NativeRequest)\n return {\n [WIRE]: \"request\",\n url: v.url,\n method: v.method,\n headers: [...v.headers],\n redirect: v.redirect,\n body: v.body ? bodies.add(v.body) : null,\n };\n return v;\n}\n\n/** Releases a body that was never read, once its stream is collected. */\nconst unread = new FinalizationRegistry<() => void>((release) => release());\n\n/**\n * The other side's body `id` as a stream: the first pull opens its port, so a body nobody\n * reads costs nothing but its release.\n */\nfunction remoteBody(mux: PortMux, id: number, release: (id: number) => void): ReadableStream {\n let chunks: AsyncIterator<Uint8Array> | undefined;\n const token = {};\n const stream = new NativeReadableStream<Uint8Array>({\n async pull(controller) {\n if (!chunks) {\n unread.unregister(token);\n const port = await mux.openPort({ kind: \"body\", id });\n chunks = duplexOverPort(port)([])[Symbol.asyncIterator]();\n }\n const { done, value } = await chunks.next();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n async cancel(reason) {\n if (chunks) await chunks.return?.(reason);\n else {\n unread.unregister(token);\n release(id);\n }\n },\n });\n unread.register(stream, () => release(id), token);\n return stream;\n}\n\n/** Statuses whose Response has no body. */\nconst NULL_BODY = [101, 103, 204, 205, 304];\n\n/** The value `toWire` described, rebuilt; its body streams from the other side when read. */\nfunction fromWire(v: any, mux: PortMux, release: (id: number) => void): unknown {\n const body = (id: number | null) => (id === null ? null : remoteBody(mux, id, release));\n switch (v[WIRE]) {\n case \"headers\":\n return new Headers(v.entries);\n case \"stream\":\n return body(v.body);\n case \"response\": {\n // `Response.error()` (status 0) is rebuilt as one.\n if (v.status === 0) {\n if (v.body !== null) release(v.body);\n return NativeResponse.error();\n }\n // The constructor takes statuses 200-599 only: another one (a 1xx) comes back as a response\n // with no body that still reports its status.\n const constructible = v.status >= 200 && v.status <= 599;\n const noBody = !constructible || NULL_BODY.includes(v.status);\n if (noBody && v.body !== null) release(v.body);\n const res = new Response(noBody ? null : body(v.body), {\n status: constructible ? v.status : 200,\n statusText: v.statusText,\n headers: v.headers,\n });\n if (!constructible) {\n Object.defineProperty(res, \"status\", { value: v.status, enumerable: true });\n Object.defineProperty(res, \"ok\", { value: false, enumerable: true });\n }\n if (v.url) Object.defineProperty(res, \"url\", { value: v.url, enumerable: true });\n return res;\n }\n case \"request\":\n return new Request(v.url, {\n method: v.method,\n headers: v.headers,\n redirect: v.redirect,\n body: body(v.body),\n duplex: \"half\",\n } as RequestInit);\n }\n return v;\n}\n\n/** Marks a value passed by reference in a message: `{ [REF]: id }`. */\nconst REF = \"\\u0000cellb.ref\";\n\n/**\n * The calls of one port, with values passed by reference: each side keeps the values it\n * passed (by id, and how many ids hold each); the other side calls them through stubs. A\n * stub's `Symbol.dispose` (or its garbage collection) releases its id; the last release of a\n * value runs the value's own `Symbol.dispose`, as workerd does for an `RpcTarget`. A call\n * returns an RpcPromise: calls on it go to the other side at once, naming its answer.\n */\nfunction callsOver(port: MessageTarget, handle: Handle, mux: PortMux, bodies: Bodies): Call {\n const values = new Map<number, any>();\n const answers = new Map<number, unknown>();\n let lastAnswer = 0;\n const holders = new Map<unknown, number>();\n let lastId = 0;\n const encode = (v: unknown) => {\n const mark = bodies.mark();\n try {\n return cloneable(\n cross(\n v,\n (x) => {\n values.set(++lastId, x);\n holders.set(x, (holders.get(x) ?? 0) + 1);\n return { [REF]: lastId };\n },\n (x) => toWire(x, bodies), // Requests, Responses, Headers, streams; the port copies the rest\n ),\n );\n } catch (e) {\n bodies.releaseSince(mark); // the message is not sent: nobody will read its bodies\n throw e;\n }\n };\n const release = (id: number) => {\n const v = values.get(id);\n if (!values.delete(id)) return;\n const n = (holders.get(v) ?? 1) - 1;\n if (n) holders.set(v, n);\n else {\n holders.delete(v);\n v[Symbol.dispose]?.();\n }\n };\n const send = (msg: object) => callPort(port, msg, { timeout: NO_TIMEOUT }).catch(() => {});\n // Stubs of one id held here: `dup()` makes another, and the id is released (and the other\n // side's value with it, once no other id holds it) when the last of them is disposed or\n // collected.\n const local = new Map<number, number>();\n const drop = (id: number) => {\n const n = (local.get(id) ?? 1) - 1;\n if (n) local.set(id, n);\n else {\n local.delete(id);\n send({ type: \"release\", id });\n }\n };\n const collected = new FinalizationRegistry<number>(drop);\n const stubOf = (id: number) => {\n local.set(id, (local.get(id) ?? 0) + 1);\n let disposed = false;\n const live = () => {\n if (disposed) throw new Error(\"A stub was used after it was disposed.\");\n };\n const invoke = (path: string[], args: unknown[]) => {\n live();\n return call({ type: \"ref\", id, path, args });\n };\n const stub: any = new Proxy(() => {}, {\n apply: (_t, _this, args) => invoke([], args),\n get(_t, prop) {\n if (prop === STUB) return true;\n if (prop === Symbol.dispose)\n return () => {\n if (disposed) return;\n disposed = true;\n collected.unregister(stub);\n drop(id);\n };\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // workerd's `stub.dup()`: another stub of the same value, disposed on its own.\n if (prop === \"dup\")\n return () => {\n live();\n return stubOf(id);\n };\n return (...args: unknown[]) => invoke([prop], args);\n },\n });\n collected.register(stub, id, stub);\n return stub;\n };\n // Messages arrive as fresh copies: stubs replace the markers in place.\n const decode = (v: any): any => {\n if (Array.isArray(v)) for (let i = 0; i < v.length; i++) v[i] = decode(v[i]);\n else if (v && Object.getPrototypeOf(v) === Object.prototype) {\n if (typeof v[WIRE] === \"string\")\n return fromWire(v, mux, (body) => send({ type: \"release\", body }));\n if (typeof v[REF] === \"number\") return stubOf(v[REF]);\n for (const k of Object.keys(v)) v[k] = decode(v[k]);\n }\n return v;\n };\n const run = (m: any): unknown => {\n if (m.type !== \"ref\") return handle(m);\n if (m.on !== undefined) return pipeTo(answers.get(m.on), m.path, m.args);\n const v = values.get(m.id);\n if (v === undefined) throw new Error(\"A stub was used after it was disposed.\");\n return pipeTo(v, m.path, m.args);\n };\n // The answer is kept as the message arrives: a pipelined call on it may arrive before it\n // settles.\n const serve = async (m: any) => {\n if (m.type === \"release\") {\n if (m.body !== undefined) bodies.release(m.body);\n else if (m.answer === undefined) release(m.id);\n else answers.delete(m.answer);\n return;\n }\n let r: unknown;\n try {\n r = run(m);\n } catch (e) {\n r = Promise.reject(e);\n }\n answers.set(m.answer, r);\n return r;\n };\n listenPort(port, (msg) => serve(decode(msg)).then(encode).catch(throwOwn));\n const call: Call = (msg) => {\n const answer = ++lastAnswer;\n const result = (async () =>\n decode(await callPort(port, encode({ ...msg, answer }), { timeout: NO_TIMEOUT })))();\n // Calls on the answer sent before now are ahead of this release on the port.\n const done = () => send({ type: \"release\", answer });\n result.then(done, done);\n return rpcPromise(result, (path, args) => call({ type: \"ref\", on: answer, path, args }));\n };\n return call;\n}\n\n/** Errors cross with their own properties (so `code` does); `name` is inherited, so copy it. */\nfunction throwOwn(e: unknown): never {\n if (e && typeof e === \"object\")\n Object.defineProperty(e, \"name\", { value: (e as Error).name, enumerable: true });\n throw e;\n}\n\n/**\n * Throws `DataCloneError` for a value the port cannot carry: the multiplexer drops a message\n * it fails to post, and the call would wait forever.\n */\nfunction cloneable<T>(value: T): T {\n structuredClone(value);\n return value;\n}\n\n/** A worker_threads Worker is an EventEmitter; MessagePorts and Dedicated Workers are targets. */\nfunction messageTarget(port: PortLike): MessageTarget {\n if (port.addEventListener) return port as MessageTarget;\n const on = port.on!.bind(port);\n const listeners = new Map<unknown, (data: unknown) => void>();\n return {\n postMessage: (msg, transfer) => port.postMessage(msg, transfer),\n addEventListener(_type, fn) {\n const listener = (data: unknown) => void fn({ data } as MessageEvent);\n listeners.set(fn, listener);\n on(\"message\", listener);\n },\n removeEventListener(_type, fn) {\n port.off?.(\"message\", listeners.get(fn)!);\n listeners.delete(fn);\n },\n };\n}\n"]}
|
|
@@ -192,5 +192,7 @@ export declare function browserProjectRuntime(opts: BrowserProjectOptions): Prom
|
|
|
192
192
|
advertise(address: string): Promise<void>;
|
|
193
193
|
close(): Promise<void>;
|
|
194
194
|
} | undefined;
|
|
195
|
+
/** The cells' databases in the OPFS pool (none with a bucket: there the bucket has them). */
|
|
196
|
+
exportCells: () => Promise<[string, Uint8Array][]>;
|
|
195
197
|
close: () => Promise<void>;
|
|
196
198
|
}>;
|
|
@@ -197,6 +197,8 @@ export async function browserProjectRuntime(opts) {
|
|
|
197
197
|
runtime,
|
|
198
198
|
unsupported,
|
|
199
199
|
bucket: shared,
|
|
200
|
+
/** The cells' databases in the OPFS pool (none with a bucket: there the bucket has them). */
|
|
201
|
+
exportCells: async () => openSql.exportFiles?.() ?? [],
|
|
200
202
|
close: async () => {
|
|
201
203
|
await runtime.close();
|
|
202
204
|
openSql.release(); // the pool's files, for the next worker that opens it
|
|
@@ -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,EACL,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAGpC,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;AAE9D,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,kBAAkB,CAAC;AACzE,OAAO,EAAoB,WAAW,EAAE,MAAM,mB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QAC3E,CAAC;KACF,CAAC;AACJ,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 type { LtxStoreFiles } from \"../ltx/ltx-page-server.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 {\n createProjectRuntime,\n hasNodeCompat,\n loadProjectBindings,\n loadTimeEnv,\n populatesProcessEnv,\n processEnvOf,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\nexport { populatesProcessEnv, processEnvOf };\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. A preset on OPFS directory `ltx`: synchronous\n * handles (default, `opfs-sync`), OPFS's asynchronous API (`opfs`), or memory (nothing\n * kept). Or the app's own FilesApi, opened before cellb starts: `{ port }` from\n * `filesApiPort(files)` (served where the app opened it), or `{ module, args }` (built in\n * the store worker). `ltx` then names the storage (the scope of the cells' Web Locks).\n * A port is transferred to the store worker, so it serves one runtime: give each\n * `browserProjectRuntime` a new `filesApiPort`.\n */\n files?: LtxStoreFiles;\n /**\n * A store already running elsewhere (`serveLtxStore(files)`, on the page): no store\n * worker; the VFS sends its reads and commits there. `files` is then ignored. One store\n * per runtime; the app calls its `close()` when the runtime ends.\n */\n ltxStore?: { sab: SharedArrayBuffer; port: MessagePort };\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`. A function instead starts the\n * Dedicated Worker itself (`() => new Worker(new URL(…, import.meta.url), { type: \"module\" })`,\n * a form bundlers follow).\n */\n isolateScript?: URL | (() => Worker);\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: each cell is a SQLite database whose main file is its LTX files, read\n * page by page (src/adapters/ltx-vfs.ts) from a store: a store worker of this worker's own (on\n * OPFS, memory, or the app's FilesApi through a port or a module), or a store the app runs\n * elsewhere (`ltxStore`).\n */\nexport async function ltxOpener(\n sqlite3: unknown,\n dir: string,\n compactAfter?: number,\n files?: LtxStoreFiles,\n ltxStore?: { sab: SharedArrayBuffer; port: MessagePort },\n) {\n let sab: SharedArrayBuffer;\n let post: (m: unknown) => void;\n let release: () => void;\n if (ltxStore) {\n // The store runs elsewhere (serveLtxStore): only the VFS here.\n sab = ltxStore.sab;\n const port = ltxStore.port;\n post = (m) => port.postMessage(m);\n release = () => port.close();\n } else {\n const store = new Worker(\n new URL(\n \"../ltx/ltx-store-worker.ts\",\n import.meta.url,\n ) /* `.js` in dist/ (scripts/build.mjs) */,\n { type: \"module\" },\n );\n 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) => {\n if (e.data?.op === \"ready\") resolve();\n else if (e.data?.op === \"failed\")\n reject(new Error(`ltx store worker: ${e.data.error as string}`));\n });\n store.addEventListener(\"error\", (e) => reject(new Error(`ltx store worker: ${e.message}`)));\n });\n // A port to the app's FilesApi moves on to the store worker.\n const transfer = files && typeof files === \"object\" && \"port\" in files ? [files.port] : [];\n try {\n store.postMessage({ op: \"init\", sab, dir, compactAfter, files }, transfer);\n await ready;\n } catch (err) {\n store.terminate(); // a store worker that did not start is not left behind\n throw err;\n }\n post = (m) => store.postMessage(m);\n release = () => store.terminate();\n }\n const { name } = installLtxVfs(sqlite3, { sab, post });\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 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 = hasNodeCompat(config);\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(\n opts.sqlite3,\n opts.bucket.ltx,\n opts.bucket.compactAfter,\n opts.bucket.files,\n opts.bucket.ltxStore,\n )\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 bindings: await loadProjectBindings(opts.config),\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"]}
|
|
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,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;AAE9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACp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,EAAE;KACZ,CAAC,CAAC;IACH,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpB,OAAO;QACL,OAAO;QACP,WAAW;QACX,MAAM,EAAE,MAAM;QACd,6FAA6F;QAC7F,WAAW,EAAE,KAAK,IAAqC,EAAE,CACtD,OAA0D,CAAC,WAAW,EAAE,EAAE,IAAI,EAAE;QACnF,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,sDAAsD;QAC3E,CAAC;KACF,CAAC;AACJ,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 type { LtxStoreFiles } from \"../ltx/ltx-page-server.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 {\n createProjectRuntime,\n hasNodeCompat,\n loadProjectBindings,\n loadTimeEnv,\n populatesProcessEnv,\n processEnvOf,\n type WranglerConfig,\n} from \"./wrangler.js\";\n\nexport { populatesProcessEnv, processEnvOf };\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. A preset on OPFS directory `ltx`: synchronous\n * handles (default, `opfs-sync`), OPFS's asynchronous API (`opfs`), or memory (nothing\n * kept). Or the app's own FilesApi, opened before cellb starts: `{ port }` from\n * `filesApiPort(files)` (served where the app opened it), or `{ module, args }` (built in\n * the store worker). `ltx` then names the storage (the scope of the cells' Web Locks).\n * A port is transferred to the store worker, so it serves one runtime: give each\n * `browserProjectRuntime` a new `filesApiPort`.\n */\n files?: LtxStoreFiles;\n /**\n * A store already running elsewhere (`serveLtxStore(files)`, on the page): no store\n * worker; the VFS sends its reads and commits there. `files` is then ignored. One store\n * per runtime; the app calls its `close()` when the runtime ends.\n */\n ltxStore?: { sab: SharedArrayBuffer; port: MessagePort };\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`. A function instead starts the\n * Dedicated Worker itself (`() => new Worker(new URL(…, import.meta.url), { type: \"module\" })`,\n * a form bundlers follow).\n */\n isolateScript?: URL | (() => Worker);\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: each cell is a SQLite database whose main file is its LTX files, read\n * page by page (src/adapters/ltx-vfs.ts) from a store: a store worker of this worker's own (on\n * OPFS, memory, or the app's FilesApi through a port or a module), or a store the app runs\n * elsewhere (`ltxStore`).\n */\nexport async function ltxOpener(\n sqlite3: unknown,\n dir: string,\n compactAfter?: number,\n files?: LtxStoreFiles,\n ltxStore?: { sab: SharedArrayBuffer; port: MessagePort },\n) {\n let sab: SharedArrayBuffer;\n let post: (m: unknown) => void;\n let release: () => void;\n if (ltxStore) {\n // The store runs elsewhere (serveLtxStore): only the VFS here.\n sab = ltxStore.sab;\n const port = ltxStore.port;\n post = (m) => port.postMessage(m);\n release = () => port.close();\n } else {\n const store = new Worker(\n new URL(\n \"../ltx/ltx-store-worker.ts\",\n import.meta.url,\n ) /* `.js` in dist/ (scripts/build.mjs) */,\n { type: \"module\" },\n );\n 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) => {\n if (e.data?.op === \"ready\") resolve();\n else if (e.data?.op === \"failed\")\n reject(new Error(`ltx store worker: ${e.data.error as string}`));\n });\n store.addEventListener(\"error\", (e) => reject(new Error(`ltx store worker: ${e.message}`)));\n });\n // A port to the app's FilesApi moves on to the store worker.\n const transfer = files && typeof files === \"object\" && \"port\" in files ? [files.port] : [];\n try {\n store.postMessage({ op: \"init\", sab, dir, compactAfter, files }, transfer);\n await ready;\n } catch (err) {\n store.terminate(); // a store worker that did not start is not left behind\n throw err;\n }\n post = (m) => store.postMessage(m);\n release = () => store.terminate();\n }\n const { name } = installLtxVfs(sqlite3, { sab, post });\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 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 = hasNodeCompat(config);\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(\n opts.sqlite3,\n opts.bucket.ltx,\n opts.bucket.compactAfter,\n opts.bucket.files,\n opts.bucket.ltxStore,\n )\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 bindings: await loadProjectBindings(opts.config),\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 /** The cells' databases in the OPFS pool (none with a bucket: there the bucket has them). */\n exportCells: async (): Promise<[string, Uint8Array][]> =>\n (openSql as { exportFiles?: () => [string, Uint8Array][] }).exportFiles?.() ?? [],\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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-load.js","sourceRoot":"","sources":["../../src/project/browser-load.ts"],"names":[],"mappings":"AAAA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,EAAE,CAAC;YACxB,CAAC;oBAAS,CAAC;gBACT,MAAM,OAAO,EAAE,EAAE,CAAC;YACpB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAED,IAAI,aAA2C,CAAC;AAChD,8DAA8D;AAC9D,SAAS,cAAc;IACrB,aAAa,KAAK,MAAM,CAAC,yBAAyB,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAC5E,IAAwC,CAAC,EAAE,KAAK,KAAI,CAAC,EAAE,QAAQ,KAAI,CAAC,EAAE,CAAC,CACzE,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/**\n * `loadProject` in a browser (`@statewalker/cellb/browser`), in a Dedicated Worker: fetches a\n * folder written by `cellb build`, or compiles a source folder with the `compile` it is given,\n * and runs it with `browserProjectRuntime`.\n */\n\nimport { type BrowserBucket, browserProjectRuntime } from \"./browser-host.js\";\nimport {\n BUILD_MANIFEST,\n type BuiltProject,\n filesApiReader,\n isFilesApi,\n type LoadedProject,\n type LoadProjectOptions,\n type ProjectSource,\n readBuildManifest,\n readBuiltProject,\n urlReader,\n} from \"./built-project.js\";\nimport {\n type CompiledProject,\n hasNodeCompat,\n type ProjectCompiler,\n readSourceProject,\n WRANGLER_FILES,\n} from \"./source-project.js\";\n\nexport interface BrowserLoadProjectOptions extends LoadProjectOptions<BrowserBucket> {\n /**\n * Where loaded Workers (Worker Loader) run: the package's own isolate worker by default; a\n * script URL or a function starting a Dedicated Worker instead; `false` to run them in this\n * realm.\n */\n isolateScript?: URL | (() => Worker) | false;\n /**\n * How a source folder (`wrangler.jsonc`, `main`, `package.json`, assets) becomes code, for a\n * FilesApi that holds one: `bundleCompiler` (`@statewalker/cellb/bundle`: webrun-bundler and\n * esbuild-wasm, one ES module) or `siteCompiler` (`@statewalker/cellb/site`: modules compiled\n * one by one and served from a ServiceWorker). Without it, only `cellb build` folders load.\n * A folder written by `cellb build` loads as built either way.\n */\n compile?: ProjectCompiler;\n}\n\n/** The isolate worker this package ships (bundlers follow the `new Worker(new URL(…))` form). */\nconst ownIsolate = () =>\n new Worker(new URL(\"../isolate/isolate-worker.ts\", import.meta.url), { type: \"module\" });\n\n/**\n * Loads a project and runs it in this worker.\n *\n * `source`: the URL of a `cellb build` folder (relative URLs resolve against the page or\n * worker), or a FilesApi holding one — or, with `options.compile`, a FilesApi holding the\n * project's sources (`wrangler.jsonc` and `main` at its root, `package.json`, assets).\n * `options.data` names the OPFS pool (`<data>`) and the project's files directory\n * (`<data>-files`); it defaults to the project's `name`.\n */\nexport async function loadProject(\n source: ProjectSource,\n options: BrowserLoadProjectOptions = {},\n): Promise<LoadedProject> {\n let reader: ReturnType<typeof urlReader>;\n let where: string;\n if (isFilesApi(source)) {\n reader = filesApiReader(source);\n where = \"the FilesApi\";\n } else {\n const url = new URL(String(source), (globalThis as { location?: Location }).location?.href);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n reader = urlReader(url);\n where = url.href;\n }\n const manifest = await readBuildManifest(reader);\n let built: BuiltProject;\n let compiled: CompiledProject | undefined;\n if (manifest) built = await readBuiltProject(reader, manifest);\n else if (isFilesApi(source) && options.compile) {\n const project = await readSourceProject(source);\n if (!project)\n throw new Error(\n `the FilesApi has neither ${BUILD_MANIFEST} nor ${WRANGLER_FILES.join(\" nor \")}`,\n );\n const { config } = project;\n compiled = config.main\n ? await options.compile.compile({ files: source, config, nodeCompat: hasNodeCompat(config) })\n : { code: { bundle: null } };\n built = { config, code: null, assets: project.assets ?? new Map() };\n } else\n throw new Error(\n isFilesApi(source)\n ? `${where} has no ${BUILD_MANIFEST}: pass \\`compile\\` to load a source folder, or load a folder written by \\`cellb build\\``\n : `${where} has no ${BUILD_MANIFEST}: browsers load folders written by \\`cellb build\\` by URL (a source folder loads from a FilesApi, with \\`compile\\`)`,\n );\n try {\n const close = compiled?.close?.bind(compiled);\n const release = close && (() => close());\n return await run(built, compiled?.code ?? { bundle: built.code }, options, release);\n } catch (err) {\n await compiled?.close?.().catch(() => {});\n throw err;\n }\n}\n\nasync function run(\n built: BuiltProject,\n code: CompiledProject[\"code\"],\n options: BrowserLoadProjectOptions,\n release?: () => Promise<void>,\n): Promise<LoadedProject> {\n const data = options.data ?? built.config.name ?? \"cellb\";\n const sqlite3 = options.sqlite3 ?? (await defaultSqlite3());\n const isolateScript =\n options.isolateScript === false ? undefined : (options.isolateScript ?? ownIsolate);\n const project = await browserProjectRuntime({\n config: built.config,\n code,\n assetFiles: built.assets,\n sqlite3,\n pool: data,\n filesDir: `${data}-files`,\n bucket: options.bucket,\n ai: options.ai,\n isolateScript,\n });\n const { runtime } = project;\n return {\n config: built.config,\n runtime,\n unsupported: project.unsupported,\n fetch: (req) => runtime.fetch(req),\n close: async () => {\n try {\n await project.close();\n } finally {\n await release?.();\n }\n },\n };\n}\n\nlet sqlite3Module: Promise<unknown> | undefined;\n/** `@sqlite.org/sqlite-wasm`, initialized once per worker. */\nfunction defaultSqlite3(): Promise<unknown> {\n sqlite3Module ??= import(\"@sqlite.org/sqlite-wasm\").then(({ default: init }) =>\n (init as (o: object) => Promise<unknown>)({ print() {}, printErr() {} }),\n );\n return sqlite3Module;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-load.js","sourceRoot":"","sources":["../../src/project/browser-load.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAsB,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EACL,cAAc,EAEd,cAAc,EACd,UAAU,EAIV,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,GACV,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,aAAa,EAEb,iBAAiB,EACjB,cAAc,GACf,MAAM,qBAAqB,CAAC;AAmB7B,iGAAiG;AACjG,MAAM,UAAU,GAAG,GAAG,EAAE,CACtB,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,8BAA8B,EAAE,OAAO,IAAI,CAAC,GAAG,CA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C,EAAE,QAAQ,KAAI,CAAC,EAAE,CAAC,CACzE,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/**\n * `loadProject` in a browser (`@statewalker/cellb/browser`), in a Dedicated Worker: fetches a\n * folder written by `cellb build`, or compiles a source folder with the `compile` it is given,\n * and runs it with `browserProjectRuntime`.\n */\n\nimport { type BrowserBucket, browserProjectRuntime } from \"./browser-host.js\";\nimport {\n BUILD_MANIFEST,\n type BuiltProject,\n filesApiReader,\n isFilesApi,\n type LoadedProject,\n type LoadProjectOptions,\n type ProjectSource,\n readBuildManifest,\n readBuiltProject,\n urlReader,\n} from \"./built-project.js\";\nimport {\n type CompiledProject,\n hasNodeCompat,\n type ProjectCompiler,\n readSourceProject,\n WRANGLER_FILES,\n} from \"./source-project.js\";\n\nexport interface BrowserLoadProjectOptions extends LoadProjectOptions<BrowserBucket> {\n /**\n * Where loaded Workers (Worker Loader) run: the package's own isolate worker by default; a\n * script URL or a function starting a Dedicated Worker instead; `false` to run them in this\n * realm.\n */\n isolateScript?: URL | (() => Worker) | false;\n /**\n * How a source folder (`wrangler.jsonc`, `main`, `package.json`, assets) becomes code, for a\n * FilesApi that holds one: `bundleCompiler` (`@statewalker/cellb/bundle`: webrun-bundler and\n * esbuild-wasm, one ES module) or `siteCompiler` (`@statewalker/cellb/site`: modules compiled\n * one by one and served from a ServiceWorker). Without it, only `cellb build` folders load.\n * A folder written by `cellb build` loads as built either way.\n */\n compile?: ProjectCompiler;\n}\n\n/** The isolate worker this package ships (bundlers follow the `new Worker(new URL(…))` form). */\nconst ownIsolate = () =>\n new Worker(new URL(\"../isolate/isolate-worker.ts\", import.meta.url), { type: \"module\" });\n\n/**\n * Loads a project and runs it in this worker.\n *\n * `source`: the URL of a `cellb build` folder (relative URLs resolve against the page or\n * worker), or a FilesApi holding one — or, with `options.compile`, a FilesApi holding the\n * project's sources (`wrangler.jsonc` and `main` at its root, `package.json`, assets).\n * `options.data` names the OPFS pool (`<data>`) and the project's files directory\n * (`<data>-files`); it defaults to the project's `name`.\n */\nexport async function loadProject(\n source: ProjectSource,\n options: BrowserLoadProjectOptions = {},\n): Promise<LoadedProject> {\n let reader: ReturnType<typeof urlReader>;\n let where: string;\n if (isFilesApi(source)) {\n reader = filesApiReader(source);\n where = \"the FilesApi\";\n } else {\n const url = new URL(String(source), (globalThis as { location?: Location }).location?.href);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n reader = urlReader(url);\n where = url.href;\n }\n const manifest = await readBuildManifest(reader);\n let built: BuiltProject;\n let compiled: CompiledProject | undefined;\n if (manifest) built = await readBuiltProject(reader, manifest);\n else if (isFilesApi(source) && options.compile) {\n const project = await readSourceProject(source);\n if (!project)\n throw new Error(\n `the FilesApi has neither ${BUILD_MANIFEST} nor ${WRANGLER_FILES.join(\" nor \")}`,\n );\n const { config } = project;\n compiled = config.main\n ? await options.compile.compile({ files: source, config, nodeCompat: hasNodeCompat(config) })\n : { code: { bundle: null } };\n built = { config, code: null, assets: project.assets ?? new Map() };\n } else\n throw new Error(\n isFilesApi(source)\n ? `${where} has no ${BUILD_MANIFEST}: pass \\`compile\\` to load a source folder, or load a folder written by \\`cellb build\\``\n : `${where} has no ${BUILD_MANIFEST}: browsers load folders written by \\`cellb build\\` by URL (a source folder loads from a FilesApi, with \\`compile\\`)`,\n );\n try {\n const close = compiled?.close?.bind(compiled);\n const release = close && (() => close());\n return await run(built, compiled?.code ?? { bundle: built.code }, options, release);\n } catch (err) {\n await compiled?.close?.().catch(() => {});\n throw err;\n }\n}\n\nasync function run(\n built: BuiltProject,\n code: CompiledProject[\"code\"],\n options: BrowserLoadProjectOptions,\n release?: () => Promise<void>,\n): Promise<LoadedProject> {\n const data = options.data ?? built.config.name ?? \"cellb\";\n const sqlite3 = options.sqlite3 ?? (await defaultSqlite3());\n const isolateScript =\n options.isolateScript === false ? undefined : (options.isolateScript ?? ownIsolate);\n const project = await browserProjectRuntime({\n config: built.config,\n code,\n assetFiles: built.assets,\n sqlite3,\n pool: data,\n filesDir: `${data}-files`,\n bucket: options.bucket,\n ai: options.ai,\n isolateScript,\n });\n const { runtime } = project;\n return {\n config: built.config,\n runtime,\n unsupported: project.unsupported,\n fetch: (req) => runtime.fetch(req),\n exportCells: () => project.exportCells(),\n close: async () => {\n try {\n await project.close();\n } finally {\n await release?.();\n }\n },\n };\n}\n\nlet sqlite3Module: Promise<unknown> | undefined;\n/** `@sqlite.org/sqlite-wasm`, initialized once per worker. */\nfunction defaultSqlite3(): Promise<unknown> {\n sqlite3Module ??= import(\"@sqlite.org/sqlite-wasm\").then(({ default: init }) =>\n (init as (o: object) => Promise<unknown>)({ print() {}, printErr() {} }),\n );\n return sqlite3Module;\n}\n"]}
|
|
@@ -14,4 +14,10 @@ export declare const PROJECT_WORKERS_MODULE_SHIM = "const m = globalThis.__cells
|
|
|
14
14
|
* `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of
|
|
15
15
|
* sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).
|
|
16
16
|
*/
|
|
17
|
-
export declare function browserModuleLoader(workersModuleShim?: string
|
|
17
|
+
export declare function browserModuleLoader(workersModuleShim?: string, opts?: {
|
|
18
|
+
/**
|
|
19
|
+
* This realm is the loaded Worker's own (an isolate): an `import()` in code it builds with
|
|
20
|
+
* `Function` resolves against its modules too (isolate/function-imports.ts).
|
|
21
|
+
*/
|
|
22
|
+
functionImports?: boolean;
|
|
23
|
+
}): ModuleLoader;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IMPORT_FROM, prefixModule, resolveModuleName, routeDynamicImports, } from "../bindings/module-registry.js";
|
|
2
2
|
import { compileWasmModules, moduleText, outboundFetch, } from "../bindings/worker-loader.js";
|
|
3
3
|
import { ctxExports } from "../core/handles.js";
|
|
4
|
+
import { FUNCTION_IMPORT } from "../isolate/function-imports.js";
|
|
4
5
|
import { rewriteModuleSpecifiers } from "./module-specifiers.js";
|
|
5
6
|
import { workerScope } from "./worker-scope.js";
|
|
6
7
|
const WORKERS_CLASSES = "const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m;";
|
|
@@ -19,7 +20,7 @@ export const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env
|
|
|
19
20
|
* `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of
|
|
20
21
|
* sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).
|
|
21
22
|
*/
|
|
22
|
-
export function browserModuleLoader(workersModuleShim) {
|
|
23
|
+
export function browserModuleLoader(workersModuleShim, opts = {}) {
|
|
23
24
|
const blob = (text) => URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
|
|
24
25
|
const fixedShimUrl = workersModuleShim && blob(workersModuleShim);
|
|
25
26
|
return async (_id, loaded, logs) => {
|
|
@@ -72,6 +73,9 @@ export function browserModuleLoader(workersModuleShim) {
|
|
|
72
73
|
const name = resolveModuleName(String(spec), importer, names);
|
|
73
74
|
return import(/* @vite-ignore */ name === undefined ? String(spec) : urlOf(name));
|
|
74
75
|
};
|
|
76
|
+
// Code built with `Function` has no module of its own: it resolves from the main module.
|
|
77
|
+
if (opts.functionImports)
|
|
78
|
+
g[FUNCTION_IMPORT] = (spec) => imports[importsKey](spec, code.mainModule);
|
|
75
79
|
const routed = (name) => {
|
|
76
80
|
const text = source(name);
|
|
77
81
|
const out = routeDynamicImports(text, name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-modules.js","sourceRoot":"","sources":["../../src/project/browser-modules.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kBAAkB,EAGlB,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC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AI,GAAG,uBAAuB,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC1D,IAAI,IAAI,KAAK,oBAAoB;oBAAE,OAAO,OAAO,CAAC;gBAClD,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;oBACjD,OAAO,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBACnE,OAAO,SAAS,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAC7B,IAAI,IAAI,CAAC,CAAC,cAAc,GAAG,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAC/D,CAAC;YACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,GAAG,CAAC;QACb,CAAC,CAAC;QACF,MAAM,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAGtE,CAAC;QACF,KAAK,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n IMPORT_FROM,\n prefixModule,\n resolveModuleName,\n routeDynamicImports,\n} from \"../bindings/module-registry.js\";\nimport {\n compileWasmModules,\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport { rewriteModuleSpecifiers } from \"./module-specifiers.js\";\nimport { workerScope } from \"./worker-scope.js\";\n\nconst WORKERS_CLASSES =\n \"const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m;\";\n\n/**\n * `cloudflare:workers` for a project's own bundle: the classes, and the project's `env` and\n * `exports` from `globalThis.__cellsProjectScope` (set by `browserProjectRuntime`, and by\n * `serveIsolate` for the loaded Worker an isolate runs). The shim is\n * bundled with the Worker, so it declares no names beyond its exports: esbuild would rename the\n * Worker's own variables of the same name, and those names show in error messages.\n */\nexport const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);`;\n\n/**\n * Worker Loader in a browser realm: each module of a WorkerCode becomes a Blob-URL ES\n * module. `cloudflare:workers` resolves to a shim reading the runtime's own classes from\n * `globalThis.__cellsWorkersModule` and the loaded code's own `env` and `exports` (or to\n * `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of\n * sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).\n */\nexport function browserModuleLoader(workersModuleShim?: string): ModuleLoader {\n const blob = (text: string) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\n const fixedShimUrl = workersModuleShim && blob(workersModuleShim);\n return async (_id: string, loaded: WorkerCode, logs?: LogSink) => {\n const code = await compileWasmModules(loaded);\n const env = code.env ?? {};\n const scope = fixedShimUrl ? undefined : workerScope(env);\n let shimUrl = fixedShimUrl;\n if (scope) {\n const key = `s${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[key] = scope;\n shimUrl = blob(\n `${WORKERS_CLASSES} const s = globalThis.__cellsWorkerScopes[${JSON.stringify(key)}]; export const env = s.env, exports = s.exports, waitUntil = s.waitUntil;`,\n );\n }\n let consolePrelude = \"\";\n if (logs) {\n const key = `c${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n (g.__cellsConsoles as Record<string, unknown>)[key] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n consolePrelude = `const console = globalThis.__cellsConsoles[${JSON.stringify(key)}];\\n`;\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const key = `o${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[key] = outbound;\n consolePrelude += `const fetch = globalThis.__cellsOutbound[${JSON.stringify(key)}];\\n`;\n }\n // `import()` the Blob URLs cannot link (a computed specifier, a module's whole name) resolves\n // against this load's modules at run time (module-registry.ts).\n const names = new Set(Object.keys(code.modules));\n const importsKey = `i${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsImports ??= {};\n const imports = g.__cellsImports as Record<string, unknown>;\n imports[importsKey] = (spec: unknown, importer: string) => {\n const name = resolveModuleName(String(spec), importer, names);\n return import(/* @vite-ignore */ name === undefined ? String(spec) : urlOf(name));\n };\n const routed = (name: string) => {\n const text = source(name);\n const out = routeDynamicImports(text, name);\n return out === undefined\n ? text\n : prefixModule(\n out,\n `const ${IMPORT_FROM} = globalThis.__cellsImports[${JSON.stringify(importsKey)}]; `,\n );\n };\n const urls = new Map<string, string>();\n // Modules whose Blob URL is being made: a Blob URL exists only once its text (with its\n // imports' URLs) does, so modules that import each other cannot be loaded this way.\n const making: string[] = [];\n const source = (name: string) => {\n const m = code.modules[name];\n if (m === undefined) throw new Error(`Worker Loader: module \"${name}\" not found`);\n return moduleText(m, name, names);\n };\n const urlOf = (name: string): string => {\n const known = urls.get(name);\n if (known) return known;\n if (making.includes(name))\n throw new Error(\n `Worker Loader: modules import each other (${[...making.slice(making.indexOf(name)), name].join(\" → \")}); a browser realm loads each module from a Blob URL, which cannot form a cycle`,\n );\n making.push(name);\n const base = name.includes(\"/\") ? name.slice(0, name.lastIndexOf(\"/\") + 1) : \"\";\n // Only the module's own imports: the same words in a string, a template or a comment are\n // not imports (a code generator's template may well contain `from \"cloudflare:workers\"`).\n const text = rewriteModuleSpecifiers(routed(name), (spec) => {\n if (spec === \"cloudflare:workers\") return shimUrl;\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\"))\n return urlOf(new URL(spec, `file:///${base}`).pathname.slice(1));\n return undefined;\n });\n const url = URL.createObjectURL(\n new Blob([consolePrelude + text], { type: \"text/javascript\" }),\n );\n urls.set(name, url);\n making.pop();\n return url;\n };\n const module = (await import(/* @vite-ignore */ urlOf(code.mainModule))) as Record<\n string,\n unknown\n >;\n scope?.bind({ env, exports: ctxExports(module, env) });\n return module;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-modules.js","sourceRoot":"","sources":["../../src/project/browser-modules.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,kBAAkB,EAGlB,UAAU,EACV,aAAa,GAEd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,eAAe,G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yFAAyF;YACzF,0FAA0F;YAC1F,MAAM,IAAI,GAAG,uBAAuB,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC1D,IAAI,IAAI,KAAK,oBAAoB;oBAAE,OAAO,OAAO,CAAC;gBAClD,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;oBACjD,OAAO,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBACnE,OAAO,SAAS,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAC7B,IAAI,IAAI,CAAC,CAAC,cAAc,GAAG,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAC/D,CAAC;YACF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,GAAG,CAAC;QACb,CAAC,CAAC;QACF,MAAM,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAGtE,CAAC;QACF,KAAK,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;QACvD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n IMPORT_FROM,\n prefixModule,\n resolveModuleName,\n routeDynamicImports,\n} from \"../bindings/module-registry.js\";\nimport {\n compileWasmModules,\n type LogSink,\n type ModuleLoader,\n moduleText,\n outboundFetch,\n type WorkerCode,\n} from \"../bindings/worker-loader.js\";\nimport { ctxExports } from \"../core/handles.js\";\nimport { FUNCTION_IMPORT } from \"../isolate/function-imports.js\";\nimport { rewriteModuleSpecifiers } from \"./module-specifiers.js\";\nimport { workerScope } from \"./worker-scope.js\";\n\nconst WORKERS_CLASSES =\n \"const m = globalThis.__cellsWorkersModule; export const DurableObject = m.DurableObject, WorkerEntrypoint = m.WorkerEntrypoint, WorkflowEntrypoint = m.WorkflowEntrypoint, RpcTarget = m.RpcTarget, abortIsolate = m.abortIsolate; export default m;\";\n\n/**\n * `cloudflare:workers` for a project's own bundle: the classes, and the project's `env` and\n * `exports` from `globalThis.__cellsProjectScope` (set by `browserProjectRuntime`, and by\n * `serveIsolate` for the loaded Worker an isolate runs). The shim is\n * bundled with the Worker, so it declares no names beyond its exports: esbuild would rename the\n * Worker's own variables of the same name, and those names show in error messages.\n */\nexport const PROJECT_WORKERS_MODULE_SHIM = `${WORKERS_CLASSES} export const env = globalThis.__cellsProjectScope?.env ?? {}, exports = globalThis.__cellsProjectScope?.exports ?? {}, waitUntil = (p) => globalThis.__cellsProjectScope?.waitUntil(p);`;\n\n/**\n * Worker Loader in a browser realm: each module of a WorkerCode becomes a Blob-URL ES\n * module. `cloudflare:workers` resolves to a shim reading the runtime's own classes from\n * `globalThis.__cellsWorkersModule` and the loaded code's own `env` and `exports` (or to\n * `workersModuleShim`, the same for every load); relative imports resolve to the Blob URLs of\n * sibling modules; with a log sink the module gets a module-scoped `console` (Tail Workers).\n */\nexport function browserModuleLoader(\n workersModuleShim?: string,\n opts: {\n /**\n * This realm is the loaded Worker's own (an isolate): an `import()` in code it builds with\n * `Function` resolves against its modules too (isolate/function-imports.ts).\n */\n functionImports?: boolean;\n } = {},\n): ModuleLoader {\n const blob = (text: string) => URL.createObjectURL(new Blob([text], { type: \"text/javascript\" }));\n const fixedShimUrl = workersModuleShim && blob(workersModuleShim);\n return async (_id: string, loaded: WorkerCode, logs?: LogSink) => {\n const code = await compileWasmModules(loaded);\n const env = code.env ?? {};\n const scope = fixedShimUrl ? undefined : workerScope(env);\n let shimUrl = fixedShimUrl;\n if (scope) {\n const key = `s${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsWorkerScopes ??= {};\n (g.__cellsWorkerScopes as Record<string, unknown>)[key] = scope;\n shimUrl = blob(\n `${WORKERS_CLASSES} const s = globalThis.__cellsWorkerScopes[${JSON.stringify(key)}]; export const env = s.env, exports = s.exports, waitUntil = s.waitUntil;`,\n );\n }\n let consolePrelude = \"\";\n if (logs) {\n const key = `c${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsConsoles ??= {};\n const real = globalThis.console;\n const wrap =\n (level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\") =>\n (...args: unknown[]) => {\n logs(level, args);\n real[level](...args);\n };\n (g.__cellsConsoles as Record<string, unknown>)[key] = Object.assign(Object.create(real), {\n log: wrap(\"log\"),\n info: wrap(\"info\"),\n warn: wrap(\"warn\"),\n error: wrap(\"error\"),\n debug: wrap(\"debug\"),\n });\n consolePrelude = `const console = globalThis.__cellsConsoles[${JSON.stringify(key)}];\\n`;\n }\n const outbound = outboundFetch(code);\n if (outbound) {\n const key = `o${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsOutbound ??= {};\n (g.__cellsOutbound as Record<string, unknown>)[key] = outbound;\n consolePrelude += `const fetch = globalThis.__cellsOutbound[${JSON.stringify(key)}];\\n`;\n }\n // `import()` the Blob URLs cannot link (a computed specifier, a module's whole name) resolves\n // against this load's modules at run time (module-registry.ts).\n const names = new Set(Object.keys(code.modules));\n const importsKey = `i${Math.random().toString(36).slice(2)}`;\n const g = globalThis as Record<string, unknown>;\n g.__cellsImports ??= {};\n const imports = g.__cellsImports as Record<string, unknown>;\n imports[importsKey] = (spec: unknown, importer: string) => {\n const name = resolveModuleName(String(spec), importer, names);\n return import(/* @vite-ignore */ name === undefined ? String(spec) : urlOf(name));\n };\n // Code built with `Function` has no module of its own: it resolves from the main module.\n if (opts.functionImports)\n g[FUNCTION_IMPORT] = (spec: unknown) =>\n (imports[importsKey] as (s: unknown, i: string) => Promise<unknown>)(spec, code.mainModule);\n const routed = (name: string) => {\n const text = source(name);\n const out = routeDynamicImports(text, name);\n return out === undefined\n ? text\n : prefixModule(\n out,\n `const ${IMPORT_FROM} = globalThis.__cellsImports[${JSON.stringify(importsKey)}]; `,\n );\n };\n const urls = new Map<string, string>();\n // Modules whose Blob URL is being made: a Blob URL exists only once its text (with its\n // imports' URLs) does, so modules that import each other cannot be loaded this way.\n const making: string[] = [];\n const source = (name: string) => {\n const m = code.modules[name];\n if (m === undefined) throw new Error(`Worker Loader: module \"${name}\" not found`);\n return moduleText(m, name, names);\n };\n const urlOf = (name: string): string => {\n const known = urls.get(name);\n if (known) return known;\n if (making.includes(name))\n throw new Error(\n `Worker Loader: modules import each other (${[...making.slice(making.indexOf(name)), name].join(\" → \")}); a browser realm loads each module from a Blob URL, which cannot form a cycle`,\n );\n making.push(name);\n const base = name.includes(\"/\") ? name.slice(0, name.lastIndexOf(\"/\") + 1) : \"\";\n // Only the module's own imports: the same words in a string, a template or a comment are\n // not imports (a code generator's template may well contain `from \"cloudflare:workers\"`).\n const text = rewriteModuleSpecifiers(routed(name), (spec) => {\n if (spec === \"cloudflare:workers\") return shimUrl;\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\"))\n return urlOf(new URL(spec, `file:///${base}`).pathname.slice(1));\n return undefined;\n });\n const url = URL.createObjectURL(\n new Blob([consolePrelude + text], { type: \"text/javascript\" }),\n );\n urls.set(name, url);\n making.pop();\n return url;\n };\n const module = (await import(/* @vite-ignore */ urlOf(code.mainModule))) as Record<\n string,\n unknown\n >;\n scope?.bind({ env, exports: ctxExports(module, env) });\n return module;\n };\n}\n"]}
|
|
@@ -73,7 +73,7 @@ export interface ServiceWorkerScope {
|
|
|
73
73
|
readonly origin: string;
|
|
74
74
|
};
|
|
75
75
|
readonly clients: unknown;
|
|
76
|
-
addEventListener(type: string, listener: (event:
|
|
76
|
+
addEventListener(type: string, listener: (event: Event) => unknown): void;
|
|
77
77
|
}
|
|
78
78
|
/**
|
|
79
79
|
* The ServiceWorker side: webrun-http-browser's dispatcher, with the project as its key and the
|