@statewalker/cellb 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +51 -25
  2. package/dist/adapters/wasm-sqlite.d.ts +11 -0
  3. package/dist/adapters/wasm-sqlite.js +26 -3
  4. package/dist/adapters/wasm-sqlite.js.map +1 -1
  5. package/dist/bindings/assets.js +2 -2
  6. package/dist/bindings/assets.js.map +1 -1
  7. package/dist/bindings/r2.js +2 -2
  8. package/dist/bindings/r2.js.map +1 -1
  9. package/dist/browser.d.ts +0 -1
  10. package/dist/browser.js +0 -1
  11. package/dist/browser.js.map +1 -1
  12. package/dist/bucket/celld-cells.js +1 -1
  13. package/dist/bucket/celld-cells.js.map +1 -1
  14. package/dist/bucket/s3-object-store.js +1 -1
  15. package/dist/bucket/s3-object-store.js.map +1 -1
  16. package/dist/core/handles.d.ts +5 -2
  17. package/dist/core/handles.js +12 -1
  18. package/dist/core/handles.js.map +1 -1
  19. package/dist/core/id.js +3 -3
  20. package/dist/core/id.js.map +1 -1
  21. package/dist/core/namespace.d.ts +1 -1
  22. package/dist/core/namespace.js +2 -1
  23. package/dist/core/namespace.js.map +1 -1
  24. package/dist/core/object-host.d.ts +23 -0
  25. package/dist/core/object-host.js +87 -6
  26. package/dist/core/object-host.js.map +1 -1
  27. package/dist/core/runtime.d.ts +10 -0
  28. package/dist/core/runtime.js +43 -2
  29. package/dist/core/runtime.js.map +1 -1
  30. package/dist/index.d.ts +2 -1
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/isolate/browser.js +1 -1
  34. package/dist/isolate/browser.js.map +1 -1
  35. package/dist/isolate/host.d.ts +5 -1
  36. package/dist/isolate/host.js +29 -2
  37. package/dist/isolate/host.js.map +1 -1
  38. package/dist/isolate/isolate-worker.js +11 -1
  39. package/dist/isolate/isolate-worker.js.map +1 -1
  40. package/dist/isolate/isolate.js +20 -0
  41. package/dist/isolate/isolate.js.map +1 -1
  42. package/dist/isolate/node-entry.js +11 -0
  43. package/dist/isolate/node-entry.js.map +1 -1
  44. package/dist/isolate/protocol.d.ts +5 -0
  45. package/dist/isolate/protocol.js +114 -2
  46. package/dist/isolate/protocol.js.map +1 -1
  47. package/dist/node-compat/crypto.js +3 -3
  48. package/dist/node-compat/crypto.js.map +1 -1
  49. package/dist/peer/celld-peer.d.ts +17 -0
  50. package/dist/peer/celld-peer.js +49 -7
  51. package/dist/peer/celld-peer.js.map +1 -1
  52. package/dist/project/browser-host.js +3 -2
  53. package/dist/project/browser-host.js.map +1 -1
  54. package/dist/project/node-project.js +2 -1
  55. package/dist/project/node-project.js.map +1 -1
  56. package/dist/project/site-loader.d.ts +45 -0
  57. package/dist/project/site-loader.js +97 -0
  58. package/dist/project/site-loader.js.map +1 -0
  59. package/dist/project/site.d.ts +0 -36
  60. package/dist/project/site.js +11 -99
  61. package/dist/project/site.js.map +1 -1
  62. package/dist/project/wrangler.js +10 -0
  63. package/dist/project/wrangler.js.map +1 -1
  64. package/dist/router/cell-router.js +1 -1
  65. package/dist/router/cell-router.js.map +1 -1
  66. package/dist/site.d.ts +1 -0
  67. package/dist/site.js +6 -0
  68. package/dist/site.js.map +1 -0
  69. package/dist/transport/port.d.ts +3 -4
  70. package/dist/transport/port.js +21 -79
  71. package/dist/transport/port.js.map +1 -1
  72. package/dist/ws/client.d.ts +23 -8
  73. package/dist/ws/client.js +50 -189
  74. package/dist/ws/client.js.map +1 -1
  75. package/dist/ws/frames.d.ts +31 -8
  76. package/dist/ws/frames.js +54 -7
  77. package/dist/ws/frames.js.map +1 -1
  78. package/dist/ws/server.d.ts +4 -0
  79. package/dist/ws/server.js +29 -5
  80. package/dist/ws/server.js.map +1 -1
  81. package/package.json +29 -10
@@ -1 +1 @@
1
- {"version":3,"file":"id.js","sourceRoot":"","sources":["../../src/core/id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CA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,IAAI,UAAU,CAAC,EAAE,EAAE,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG;QACtD,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAC;IAC3E,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\n\n/** 64-hex-char object id. idFromName is SYNCHRONOUS (as on CF), hence noble instead of crypto.subtle. */\nexport class DurableObjectId {\n readonly #hex: string;\n readonly name?: string;\n constructor(hex: string, name?: string) {\n if (!/^[0-9a-f]{64}$/.test(hex))\n throw new TypeError(\"Invalid Durable Object ID: must be 64 hex digits\");\n this.#hex = hex;\n if (name !== undefined) this.name = name;\n }\n toString(): string {\n return this.#hex;\n }\n equals(other: DurableObjectId): boolean {\n return other.toString() === this.#hex;\n }\n}\n\n/**\n * Ids as celld derives them (engine_api.rs), so one name reaches the same object id on\n * celld and on cellb: namespace key `cells:v1:<len(script)>:<script>:<class>`;\n * key = SHA-256(namespace key); id = HMAC(key, name)[0..16] ‖ HMAC(key, first half)[0..16].\n * The second half authenticates the first, so idFromString() rejects ids of other namespaces.\n */\nexport function namespaceKey(scriptName: string, className: string): string {\n return `cells:v1:${scriptName.length}:${scriptName}:${className}`;\n}\n\nconst keys = new Map<string, Uint8Array>();\nconst keyOf = (ns: string) => {\n let k = keys.get(ns);\n if (!k) {\n k = sha256(new TextEncoder().encode(ns));\n keys.set(ns, k);\n }\n return k;\n};\nconst half = (key: Uint8Array, data: Uint8Array) => hmac(sha256, key, data).subarray(0, 16);\nconst withSuffix = (ns: string, first: Uint8Array) => {\n const id = new Uint8Array(32);\n id.set(first, 0);\n id.set(half(keyOf(ns), first), 16);\n return bytesToHex(id);\n};\n\nexport function idFromName(ns: string, name: string): DurableObjectId {\n const hex = withSuffix(ns, half(keyOf(ns), new TextEncoder().encode(name)));\n // ctx.id.name holds names up to 1024 UTF-8 bytes, as on Cloudflare and celld.\n return new DurableObjectId(\n hex,\n new TextEncoder().encode(name).byteLength <= 1024 ? name : undefined,\n );\n}\n\nexport function newUniqueId(ns: string): DurableObjectId {\n const first = new Uint8Array(16);\n crypto.getRandomValues(first);\n return new DurableObjectId(withSuffix(ns, first));\n}\n\n/** idFromString(): 64 hex digits whose second half authenticates the first for `ns`. */\nexport function validateId(ns: string, hex: string): DurableObjectId {\n const id = new DurableObjectId(hex);\n if (withSuffix(ns, hexToBytes(hex.slice(0, 32))) !== hex)\n throw new TypeError(\"Durable Object ID is not valid for this namespace\");\n return id;\n}\n"]}
1
+ {"version":3,"file":"id.js","sourceRoot":"","sources":["../../src/core/id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEhE,yGAAyG;AACzG,MAAM,OAAO,eAAe;IACjB,IAAI,CAAS;IACb,IAAI,CAAU;IACvB,YAAY,GAAW,EAAE,IAAa;QACpC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC;YAC7B,MAAM,IAAI,SAAS,CAAC,kDAAkD,CAAC,CAAC;QAC1E,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAC3C,CAAC;IACD,QAAQ;QACN,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IACD,MAAM,CAAC,KAAsB;QAC3B,OAAO,KAAK,CAAC,QAAQ,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC;IACxC,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,UAAkB,EAA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IAC9E,OAAO,IAAI,eAAe,CACxB,GAAG,EACH,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CACrE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,EAAU;IACpC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACjC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAC9B,OAAO,IAAI,eAAe,CAAC,UAAU,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,EAAU,EAAE,GAAW;IAChD,MAAM,EAAE,GAAG,IAAI,eAAe,CAAC,GAAG,CAAC,CAAC;IACpC,IAAI,UAAU,CAAC,EAAE,EAAE,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG;QACtD,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAC;IAC3E,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\n\n/** 64-hex-char object id. idFromName is SYNCHRONOUS (as on CF), hence noble instead of crypto.subtle. */\nexport class DurableObjectId {\n readonly #hex: string;\n readonly name?: string;\n constructor(hex: string, name?: string) {\n if (!/^[0-9a-f]{64}$/.test(hex))\n throw new TypeError(\"Invalid Durable Object ID: must be 64 hex digits\");\n this.#hex = hex;\n if (name !== undefined) this.name = name;\n }\n toString(): string {\n return this.#hex;\n }\n equals(other: DurableObjectId): boolean {\n return other.toString() === this.#hex;\n }\n}\n\n/**\n * Ids as celld derives them (engine_api.rs), so one name reaches the same object id on\n * celld and on cellb: namespace key `cells:v1:<len(script)>:<script>:<class>`;\n * key = SHA-256(namespace key); id = HMAC(key, name)[0..16] ‖ HMAC(key, first half)[0..16].\n * The second half authenticates the first, so idFromString() rejects ids of other namespaces.\n */\nexport function namespaceKey(scriptName: string, className: string): string {\n return `cells:v1:${scriptName.length}:${scriptName}:${className}`;\n}\n\nconst keys = new Map<string, Uint8Array>();\nconst keyOf = (ns: string) => {\n let k = keys.get(ns);\n if (!k) {\n k = sha256(new TextEncoder().encode(ns));\n keys.set(ns, k);\n }\n return k;\n};\nconst half = (key: Uint8Array, data: Uint8Array) => hmac(sha256, key, data).subarray(0, 16);\nconst withSuffix = (ns: string, first: Uint8Array) => {\n const id = new Uint8Array(32);\n id.set(first, 0);\n id.set(half(keyOf(ns), first), 16);\n return bytesToHex(id);\n};\n\nexport function idFromName(ns: string, name: string): DurableObjectId {\n const hex = withSuffix(ns, half(keyOf(ns), new TextEncoder().encode(name)));\n // ctx.id.name holds names up to 1024 UTF-8 bytes, as on Cloudflare and celld.\n return new DurableObjectId(\n hex,\n new TextEncoder().encode(name).byteLength <= 1024 ? name : undefined,\n );\n}\n\nexport function newUniqueId(ns: string): DurableObjectId {\n const first = new Uint8Array(16);\n crypto.getRandomValues(first);\n return new DurableObjectId(withSuffix(ns, first));\n}\n\n/** idFromString(): 64 hex digits whose second half authenticates the first for `ns`. */\nexport function validateId(ns: string, hex: string): DurableObjectId {\n const id = new DurableObjectId(hex);\n if (withSuffix(ns, hexToBytes(hex.slice(0, 32))) !== hex)\n throw new TypeError(\"Durable Object ID is not valid for this namespace\");\n return id;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type DurableObjectId } from "./id.js";
2
- import type { ObjectHost } from "./object-host.js";
2
+ import { type ObjectHost } from "./object-host.js";
3
3
  import type { DurableObjectState } from "./state.js";
4
4
  /** What a stub talks to: a local ObjectHost or a remote cell host behind a port. */
5
5
  export interface ObjectEndpoint {
@@ -1,6 +1,7 @@
1
1
  import { carryWebSocketHeaders } from "../ws/upgrade.js";
2
2
  import { cross, rpcCall, STUB } from "./handles.js";
3
3
  import { idFromName, newUniqueId, validateId } from "./id.js";
4
+ import { closingWith } from "./object-host.js";
4
5
  /**
5
6
  * An in-process object. `ready` (for a cell not open yet): a promise its first events await
6
7
  * before the host opens the cell's database (its store is making room), or undefined.
@@ -34,7 +35,7 @@ function endpointOf(h) {
34
35
  throw new Error("Handler does not export a fetch() function.");
35
36
  let res;
36
37
  try {
37
- const r = await obj.fetch(req);
38
+ const r = await obj.fetch(closingWith(req, h.closing));
38
39
  res = r instanceof Response ? r : new Response(String(r)); // a non-Response is sent as text (celld)
39
40
  }
40
41
  catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"namespace.js","sourceRoot":"","sources":["../../src/core/namespace.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAwB,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAYpF;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,IAAsB,EACtB,KAAuC;IAEvC,OAAO,GAAG,EAAE;QACV,MAAM,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;QACvB,IAAI,CAAC,IAAI;YAAE,OAAO,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;QACrC,OAAO;YACL,IAAI,KAAK;gBACP,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YACD,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC;gBACX,OAAO,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACvC,CAAC;YACD,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;gBAC3B,MAAM,MAAM,GAAG,KAAK,C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\nimport { cross, rpcCall, STUB } from \"./handles.js\";\nimport { type DurableObjectId, idFromName, newUniqueId, validateId } from \"./id.js\";\nimport type { ObjectHost } from \"./object-host.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\n/** What a stub talks to: a local ObjectHost or a remote cell host behind a port. */\nexport interface ObjectEndpoint {\n fetch(req: Request): Promise<Response>;\n call(method: string, args: unknown[]): Promise<unknown>;\n /** Present only for in-process objects (enables runInDurableObject). */\n local?: ObjectHost;\n}\n\n/**\n * An in-process object. `ready` (for a cell not open yet): a promise its first events await\n * before the host opens the cell's database (its store is making room), or undefined.\n */\nexport function localEndpoint(\n host: () => ObjectHost,\n ready?: () => Promise<void> | undefined,\n): () => ObjectEndpoint {\n return () => {\n const wait = ready?.();\n if (!wait) return endpointOf(host());\n return {\n get local() {\n return host();\n },\n fetch: async (req) => {\n await wait;\n return endpointOf(host()).fetch(req);\n },\n call: async (method, args) => {\n const copied = cross(args); // the arguments as they are now, as for an open cell\n await wait;\n return deliverCall(host(), method, copied);\n },\n };\n };\n}\n\nfunction endpointOf(h: ObjectHost): ObjectEndpoint {\n return {\n local: h,\n fetch: (req) =>\n h.deliver(async (obj) => {\n if (typeof obj.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n let res: Response;\n try {\n const r = await obj.fetch(req);\n res = r instanceof Response ? r : new Response(String(r)); // a non-Response is sent as text (celld)\n } catch (e) {\n // celld: the stub's fetch() rejects with \"rejected: <name>: <message> [at …]\".\n const err = e as Error;\n throw new Error(`rejected: ${err?.name ?? \"Error\"}: ${err?.message ?? String(e)}`, {\n cause: e,\n });\n }\n // A WebSocket answer to a request that did not ask for one fails (workerd, celld):\n // the stub rejects and the server end sees an abnormal close.\n const ws = (res as { webSocket?: unknown }).webSocket;\n if (res.status === 101 && ws && req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\")\n throw new Error(\n \"rejected: Error: a WebSocket response to a request without Upgrade: websocket\",\n );\n return res;\n }),\n call: async (method, args) => deliverCall(h, method, cross(args)),\n };\n}\n\nasync function deliverCall(h: ObjectHost, method: string, copied: unknown[]): Promise<unknown> {\n const r = await h.deliver((obj) => {\n const m = obj[method];\n if (typeof m !== \"function\") throw new TypeError(`${method} is not a function`); // celld's wording\n return m.apply(obj, copied);\n });\n return cross(r);\n}\n\nexport class DurableObjectNamespace {\n readonly #key: string;\n readonly #endpoint: (id: DurableObjectId) => () => ObjectEndpoint;\n\n constructor(namespaceKey: string, endpoint: (id: DurableObjectId) => () => ObjectEndpoint) {\n this.#key = namespaceKey;\n this.#endpoint = endpoint;\n }\n idFromName(name: string): DurableObjectId {\n return idFromName(this.#key, name);\n }\n newUniqueId(opts?: { jurisdiction?: string }): DurableObjectId {\n if (opts?.jurisdiction != null)\n throw new Error(\"Jurisdiction restrictions are not implemented\");\n return newUniqueId(this.#key);\n }\n idFromString(hex: string): DurableObjectId {\n return validateId(this.#key, hex);\n }\n /** The key ids of this namespace derive from (see id.ts). */\n get namespaceKey(): string {\n return this.#key;\n }\n get(id: DurableObjectId): DurableObjectStub {\n return createStub(id, this.#endpoint(id));\n }\n getByName(name: string): DurableObjectStub {\n return this.get(this.idFromName(name));\n }\n}\n\nexport type DurableObjectStub = {\n readonly id: DurableObjectId;\n readonly name?: string;\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n} & Record<string, any>;\n\nconst kEndpoint = Symbol(\"cellb.endpoint\");\n\n/**\n * Test hook (same idea as vitest-pool-workers' runInDurableObject): runs `fn`\n * inside a LOCAL object, through the input/output gates, without cloning `fn`.\n */\nexport function runInDurableObject<T>(\n stub: DurableObjectStub,\n fn: (instance: any, state: DurableObjectState) => T | Promise<T>,\n): Promise<T> {\n const ep = (stub as any)[kEndpoint] as (() => ObjectEndpoint) | undefined;\n const local = ep?.().local;\n if (!local) throw new TypeError(\"runInDurableObject needs a stub of an in-process cellb object\");\n return local.deliver(fn);\n}\n\n/** Stub = Proxy: `fetch` → fetch handler, any other property → JS-RPC call (an RpcPromise). */\nfunction createStub(id: DurableObjectId, endpoint: () => ObjectEndpoint): DurableObjectStub {\n const target = { id, name: id.name };\n // Only id and name are own enumerable keys, as in workerd and celld: Object.keys(stub) is\n // [id, name], and two stubs of one object are deep-equal.\n Object.defineProperty(target, kEndpoint, { value: endpoint });\n Object.defineProperty(target, STUB, { value: true });\n Object.defineProperty(target, \"fetch\", {\n value(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const req = new Request(input as any, init);\n // Cloudflare's `cf` request property (RequestInit.cf or Request#cf) is not part of\n // the Fetch standard: re-attach it so objects can read `request.cf`.\n const cf = (init as { cf?: unknown } | undefined)?.cf ?? (input as { cf?: unknown }).cf;\n if (cf !== undefined) Object.defineProperty(req, \"cf\", { value: cf, enumerable: true });\n // Keep a WebSocket upgrade that browsers strip from new Request() (forbidden headers).\n const source = init?.headers\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return endpoint().fetch(source ? carryWebSocketHeaders(source, req) : req);\n },\n });\n return new Proxy(target, {\n get(t, prop, recv) {\n if (prop in t) return Reflect.get(t, prop, recv);\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => rpcCall(() => endpoint().call(String(prop), args));\n },\n }) as unknown as DurableObjectStub;\n}\n"]}
1
+ {"version":3,"file":"namespace.js","sourceRoot":"","sources":["../../src/core/namespace.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAwB,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACpF,OAAO,EAAE,WAAW,EAAmB,MAAM,kBAAkB,CAAC;AAWhE;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,IAAsB,EACtB,KAAuC;IAEvC,OAAO,GAAG,EAAE;QACV,MAAM,IAAI,GAAG,KA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AI,EAAE,IAAI;YACf,IAAI,IAAI,IAAI,CAAC;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,IAAI,KAAK,MAAM,IAAI,OAAO,IAAI,KAAK,QAAQ;gBAAE,OAAO,SAAS,CAAC;YAClE,OAAO,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;QACpF,CAAC;KACF,CAAiC,CAAC;AACrC,CAAC","sourcesContent":["import { carryWebSocketHeaders } from \"../ws/upgrade.js\";\nimport { cross, rpcCall, STUB } from \"./handles.js\";\nimport { type DurableObjectId, idFromName, newUniqueId, validateId } from \"./id.js\";\nimport { closingWith, type ObjectHost } from \"./object-host.js\";\nimport type { DurableObjectState } from \"./state.js\";\n\n/** What a stub talks to: a local ObjectHost or a remote cell host behind a port. */\nexport interface ObjectEndpoint {\n fetch(req: Request): Promise<Response>;\n call(method: string, args: unknown[]): Promise<unknown>;\n /** Present only for in-process objects (enables runInDurableObject). */\n local?: ObjectHost;\n}\n\n/**\n * An in-process object. `ready` (for a cell not open yet): a promise its first events await\n * before the host opens the cell's database (its store is making room), or undefined.\n */\nexport function localEndpoint(\n host: () => ObjectHost,\n ready?: () => Promise<void> | undefined,\n): () => ObjectEndpoint {\n return () => {\n const wait = ready?.();\n if (!wait) return endpointOf(host());\n return {\n get local() {\n return host();\n },\n fetch: async (req) => {\n await wait;\n return endpointOf(host()).fetch(req);\n },\n call: async (method, args) => {\n const copied = cross(args); // the arguments as they are now, as for an open cell\n await wait;\n return deliverCall(host(), method, copied);\n },\n };\n };\n}\n\nfunction endpointOf(h: ObjectHost): ObjectEndpoint {\n return {\n local: h,\n fetch: (req) =>\n h.deliver(async (obj) => {\n if (typeof obj.fetch !== \"function\")\n throw new Error(\"Handler does not export a fetch() function.\");\n let res: Response;\n try {\n const r = await obj.fetch(closingWith(req, h.closing));\n res = r instanceof Response ? r : new Response(String(r)); // a non-Response is sent as text (celld)\n } catch (e) {\n // celld: the stub's fetch() rejects with \"rejected: <name>: <message> [at …]\".\n const err = e as Error;\n throw new Error(`rejected: ${err?.name ?? \"Error\"}: ${err?.message ?? String(e)}`, {\n cause: e,\n });\n }\n // A WebSocket answer to a request that did not ask for one fails (workerd, celld):\n // the stub rejects and the server end sees an abnormal close.\n const ws = (res as { webSocket?: unknown }).webSocket;\n if (res.status === 101 && ws && req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\")\n throw new Error(\n \"rejected: Error: a WebSocket response to a request without Upgrade: websocket\",\n );\n return res;\n }),\n call: async (method, args) => deliverCall(h, method, cross(args)),\n };\n}\n\nasync function deliverCall(h: ObjectHost, method: string, copied: unknown[]): Promise<unknown> {\n const r = await h.deliver((obj) => {\n const m = obj[method];\n if (typeof m !== \"function\") throw new TypeError(`${method} is not a function`); // celld's wording\n return m.apply(obj, copied);\n });\n return cross(r);\n}\n\nexport class DurableObjectNamespace {\n readonly #key: string;\n readonly #endpoint: (id: DurableObjectId) => () => ObjectEndpoint;\n\n constructor(namespaceKey: string, endpoint: (id: DurableObjectId) => () => ObjectEndpoint) {\n this.#key = namespaceKey;\n this.#endpoint = endpoint;\n }\n idFromName(name: string): DurableObjectId {\n return idFromName(this.#key, name);\n }\n newUniqueId(opts?: { jurisdiction?: string }): DurableObjectId {\n if (opts?.jurisdiction != null)\n throw new Error(\"Jurisdiction restrictions are not implemented\");\n return newUniqueId(this.#key);\n }\n idFromString(hex: string): DurableObjectId {\n return validateId(this.#key, hex);\n }\n /** The key ids of this namespace derive from (see id.ts). */\n get namespaceKey(): string {\n return this.#key;\n }\n get(id: DurableObjectId): DurableObjectStub {\n return createStub(id, this.#endpoint(id));\n }\n getByName(name: string): DurableObjectStub {\n return this.get(this.idFromName(name));\n }\n}\n\nexport type DurableObjectStub = {\n readonly id: DurableObjectId;\n readonly name?: string;\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n} & Record<string, any>;\n\nconst kEndpoint = Symbol(\"cellb.endpoint\");\n\n/**\n * Test hook (same idea as vitest-pool-workers' runInDurableObject): runs `fn`\n * inside a LOCAL object, through the input/output gates, without cloning `fn`.\n */\nexport function runInDurableObject<T>(\n stub: DurableObjectStub,\n fn: (instance: any, state: DurableObjectState) => T | Promise<T>,\n): Promise<T> {\n const ep = (stub as any)[kEndpoint] as (() => ObjectEndpoint) | undefined;\n const local = ep?.().local;\n if (!local) throw new TypeError(\"runInDurableObject needs a stub of an in-process cellb object\");\n return local.deliver(fn);\n}\n\n/** Stub = Proxy: `fetch` → fetch handler, any other property → JS-RPC call (an RpcPromise). */\nfunction createStub(id: DurableObjectId, endpoint: () => ObjectEndpoint): DurableObjectStub {\n const target = { id, name: id.name };\n // Only id and name are own enumerable keys, as in workerd and celld: Object.keys(stub) is\n // [id, name], and two stubs of one object are deep-equal.\n Object.defineProperty(target, kEndpoint, { value: endpoint });\n Object.defineProperty(target, STUB, { value: true });\n Object.defineProperty(target, \"fetch\", {\n value(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const req = new Request(input as any, init);\n // Cloudflare's `cf` request property (RequestInit.cf or Request#cf) is not part of\n // the Fetch standard: re-attach it so objects can read `request.cf`.\n const cf = (init as { cf?: unknown } | undefined)?.cf ?? (input as { cf?: unknown }).cf;\n if (cf !== undefined) Object.defineProperty(req, \"cf\", { value: cf, enumerable: true });\n // Keep a WebSocket upgrade that browsers strip from new Request() (forbidden headers).\n const source = init?.headers\n ? new Headers(init.headers)\n : input instanceof Request\n ? input.headers\n : undefined;\n return endpoint().fetch(source ? carryWebSocketHeaders(source, req) : req);\n },\n });\n return new Proxy(target, {\n get(t, prop, recv) {\n if (prop in t) return Reflect.get(t, prop, recv);\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n return (...args: unknown[]) => rpcCall(() => endpoint().call(String(prop), args));\n },\n }) as unknown as DurableObjectStub;\n}\n"]}
@@ -3,6 +3,17 @@ import type { AsyncRoot } from "./async-context.js";
3
3
  import { type DurableObjectClass } from "./handles.js";
4
4
  import { type DurableObjectId } from "./id.js";
5
5
  import { DurableObjectState } from "./state.js";
6
+ /**
7
+ * The request as the object sees it: its signal also aborts when the host closes (the runtime
8
+ * shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that
9
+ * waits on it then ends instead of running on into a closed database.
10
+ */
11
+ export declare function closingWith(req: Request, closing: AbortSignal): Request;
12
+ /** The object's host was closed for good: its storage and events fail with this. */
13
+ export declare class ObjectClosedError extends Error {
14
+ name: string;
15
+ constructor(cellKey: string);
16
+ }
6
17
  export declare class BrokenObjectError extends Error {
7
18
  constructor(cause: unknown, reason?: string);
8
19
  }
@@ -64,6 +75,18 @@ export declare class ObjectHost {
64
75
  * late — every queued continuation would see it open).
65
76
  */
66
77
  deliver<T>(fn: (instance: any, state: DurableObjectState) => T | Promise<T>): Promise<T>;
78
+ /**
79
+ * Settles once no event is in flight or queued (a response body still streaming is not an
80
+ * event: its handler has returned). The runtime waits for it, within a grace period, before
81
+ * it closes the database on shutdown.
82
+ */
83
+ /** No event in flight or queued. */
84
+ get idle(): boolean;
85
+ settled(): Promise<void>;
86
+ /** Aborts when the host is shutting down: the signal of the requests it is handed. */
87
+ get closing(): AbortSignal;
88
+ /** The first step of a shutdown: requests in flight see their signal abort. */
89
+ shutdown(): void;
67
90
  /** Settles once the cell lease is released (a store closed earlier would keep it held). */
68
91
  close(): Promise<void>;
69
92
  /** Time of the last event's completion (the runtime's idle sweep reads it). */
@@ -1,5 +1,5 @@
1
- import { sha256 } from "@noble/hashes/sha2";
2
- import { bytesToHex } from "@noble/hashes/utils";
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
3
  import { CELLD_SCHEMA, LOG_SEQ_READ, LOG_SEQ_WRITE, LOG_TABLE, scopeOf } from "./celld-schema.js";
4
4
  import { InputGate, OutputGate } from "./gates.js";
5
5
  import { asyncStub, isClassHandle, } from "./handles.js";
@@ -7,6 +7,31 @@ import { DurableObjectId as DurableObjectIdClass } from "./id.js";
7
7
  import { SqlStorage } from "./sql-storage.js";
8
8
  import { DurableObjectState } from "./state.js";
9
9
  import { DurableObjectStorage, SyncKvStorage } from "./storage.js";
10
+ /**
11
+ * The request as the object sees it: its signal also aborts when the host closes (the runtime
12
+ * shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that
13
+ * waits on it then ends instead of running on into a closed database.
14
+ */
15
+ export function closingWith(req, closing) {
16
+ if (closing.aborted)
17
+ return req;
18
+ const r = new Request(req, { signal: AbortSignal.any([req.signal, closing]) });
19
+ // What cellb set on the request itself (`cf`; `headers` carrying a WebSocket upgrade's
20
+ // headers, which a Request would drop) stays as it was.
21
+ for (const k of ["cf", "headers"]) {
22
+ const d = Object.getOwnPropertyDescriptor(req, k);
23
+ if (d)
24
+ Object.defineProperty(r, k, d);
25
+ }
26
+ return r;
27
+ }
28
+ /** The object's host was closed for good: its storage and events fail with this. */
29
+ export class ObjectClosedError extends Error {
30
+ name = "ObjectClosedError";
31
+ constructor(cellKey) {
32
+ super(`Durable Object ${cellKey} was closed (its runtime shut down, or it moved or was reset)`);
33
+ }
34
+ }
10
35
  export class BrokenObjectError extends Error {
11
36
  constructor(cause, reason = "its storage failed to commit durably") {
12
37
  const detail = cause instanceof Error ? `: ${cause.message}` : "";
@@ -27,6 +52,12 @@ export class ObjectHost {
27
52
  #db;
28
53
  #driver = new Proxy({}, {
29
54
  get: (_t, k) => {
55
+ // Closed for good (its runtime or shard shut down): code still running in the object
56
+ // learns why, instead of SQLite's "DB has been closed".
57
+ if (this.#closed && k !== "close")
58
+ return () => {
59
+ throw new ObjectClosedError(this.cellKey);
60
+ };
30
61
  const v = this.#db[k];
31
62
  return typeof v === "function" ? v.bind(this.#db) : v;
32
63
  },
@@ -201,10 +232,14 @@ export class ObjectHost {
201
232
  * late — every queued continuation would see it open).
202
233
  */
203
234
  deliver(fn) {
235
+ if (this.#closed)
236
+ return Promise.reject(new ObjectClosedError(this.cellKey));
204
237
  if (this.broken)
205
238
  return Promise.reject(new BrokenObjectError(undefined));
206
239
  return new Promise((resolve, reject) => {
207
240
  this.#queue.push(() => {
241
+ if (this.#closed)
242
+ return reject(new ObjectClosedError(this.cellKey));
208
243
  if (this.broken)
209
244
  return reject(new BrokenObjectError(this.#brokenCause, "its initialization failed"));
210
245
  let started;
@@ -218,6 +253,8 @@ export class ObjectHost {
218
253
  const done = () => {
219
254
  this.#active--;
220
255
  this.lastActive = Date.now();
256
+ if (!this.#active && !this.#queue.length)
257
+ this.#notifyIdle();
221
258
  };
222
259
  started.then((r) => {
223
260
  this.#pinIfStandardWebSocket(r);
@@ -272,13 +309,55 @@ export class ObjectHost {
272
309
  throw new BrokenObjectError(e);
273
310
  }
274
311
  }
312
+ /**
313
+ * Settles once no event is in flight or queued (a response body still streaming is not an
314
+ * event: its handler has returned). The runtime waits for it, within a grace period, before
315
+ * it closes the database on shutdown.
316
+ */
317
+ /** No event in flight or queued. */
318
+ get idle() {
319
+ return !this.#active && !this.#queue.length;
320
+ }
321
+ settled() {
322
+ if (!this.#active && !this.#queue.length)
323
+ return Promise.resolve();
324
+ return new Promise((resolve) => this.#idleWaiters.push(resolve));
325
+ }
326
+ #idleWaiters = [];
327
+ #notifyIdle() {
328
+ const waiters = this.#idleWaiters;
329
+ this.#idleWaiters = [];
330
+ for (const w of waiters)
331
+ w();
332
+ }
333
+ /** Closed for good: storage calls throw ObjectClosedError. */
334
+ #closed = false;
335
+ #closing = new AbortController();
336
+ /** Aborts when the host is shutting down: the signal of the requests it is handed. */
337
+ get closing() {
338
+ return this.#closing.signal;
339
+ }
340
+ /** The first step of a shutdown: requests in flight see their signal abort. */
341
+ shutdown() {
342
+ if (this.#closing.signal.aborted)
343
+ return;
344
+ this.#closing.abort(new ObjectClosedError(this.cellKey));
345
+ for (const facet of this.#facets)
346
+ facet.shutdown();
347
+ }
275
348
  /** Settles once the cell lease is released (a store closed earlier would keep it held). */
276
349
  close() {
350
+ this.shutdown();
351
+ this.#closed = true;
277
352
  for (const facet of this.#facets)
278
353
  void facet.close();
279
354
  this.#facets.clear();
280
355
  if (!this.#dbClosed)
281
356
  this.#db.close();
357
+ // Events still queued fail (each checks #closed first); nothing more runs here.
358
+ for (const queued of this.#queue.splice(0))
359
+ queued();
360
+ this.#notifyIdle();
282
361
  // Hand the cell over at once instead of letting the lease expire.
283
362
  const released = this.#release?.().catch(() => { });
284
363
  this.#release = undefined;
@@ -529,7 +608,7 @@ function createFacets(parent, spawn) {
529
608
  throw new TypeError(`${method} is not a function`);
530
609
  return fn.apply(obj, args);
531
610
  }),
532
- fetch: (req) => h.deliver((obj) => obj.fetch(req)),
611
+ fetch: (req) => h.deliver((obj) => obj.fetch(closingWith(req, h.closing))),
533
612
  restart: () => h.restart(),
534
613
  delete: async () => {
535
614
  await h.deliver((_o, state) => state.storage.deleteAll());
@@ -537,8 +616,8 @@ function createFacets(parent, spawn) {
537
616
  },
538
617
  });
539
618
  /** A class of isolated loaded code: the facet's instance and SQLite live in the isolate. */
540
- const isolated = (iso, cellKey) => {
541
- const attached = iso.attach?.(cellKey, parent.epoch?.());
619
+ const isolated = (iso, cellKey, idName) => {
620
+ const attached = iso.attach?.(cellKey, parent.epoch?.(), idName);
542
621
  const ready = async () => attached;
543
622
  return {
544
623
  call: async (method, args) => (await ready(), iso.call(cellKey, method, args)),
@@ -560,7 +639,9 @@ function createFacets(parent, spawn) {
560
639
  if (isClassHandle(info.class)) {
561
640
  const r = await info.class.resolve();
562
641
  if ("isolated" in r)
563
- return isolated(r.isolated, `${parent.cellKey}/facets/${facetSegment(name)}`);
642
+ return isolated(r.isolated, `${parent.cellKey}/facets/${facetSegment(name)}`,
643
+ // The facet's own `ctx.id` (partyserver's `this.name` reads its name).
644
+ info.id instanceof DurableObjectIdClass ? info.id.name : undefined);
564
645
  ({ cls, env, props }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CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport type {\n BackupInfo,\n CellBackup,\n CellDurability,\n Lease,\n OpenCellSql,\n SyncSqlDriver,\n ValueCodec,\n} from \"../ports.js\";\nimport type { AsyncRoot } from \"./async-context.js\";\nimport { CELLD_SCHEMA, LOG_SEQ_READ, LOG_SEQ_WRITE, LOG_TABLE, scopeOf } from \"./celld-schema.js\";\nimport { InputGate, OutputGate } from \"./gates.js\";\nimport {\n asyncStub,\n type DurableObjectClass,\n type IsolatedClass,\n isClassHandle,\n} from \"./handles.js\";\nimport { type DurableObjectId, DurableObjectId as DurableObjectIdClass } from \"./id.js\";\nimport { SqlStorage } from \"./sql-storage.js\";\nimport { DurableObjectState } from \"./state.js\";\nimport { DurableObjectStorage, SyncKvStorage } from \"./storage.js\";\n\nexport class BrokenObjectError extends Error {\n constructor(cause: unknown, reason = \"its storage failed to commit durably\") {\n const detail = cause instanceof Error ? `: ${cause.message}` : \"\";\n super(`Durable Object reset because ${reason}${detail}`, { cause });\n this.name = \"BrokenObjectError\";\n }\n}\n\n/**\n * One live instance of one Durable Object: its SQLite, gates and dispatcher.\n * Everything that reaches the object (fetch, RPC, later alarms/WebSockets)\n * goes through `deliver()`.\n */\nexport class ObjectHost {\n readonly cellKey: string;\n readonly #gate = new InputGate();\n readonly #out = new OutputGate();\n /** The open database; `#driver` follows it, so it can be closed while idle and reopened. */\n #db!: SyncSqlDriver;\n readonly #driver: SyncSqlDriver = new Proxy({} as SyncSqlDriver, {\n get: (_t, k) => {\n const v = (this.#db as unknown as Record<PropertyKey, unknown>)[k];\n return typeof v === \"function\" ? v.bind(this.#db) : v;\n },\n });\n readonly #sql: SqlStorage;\n #instance: any;\n readonly #backup?: CellBackup;\n #backedUpSeq = 0;\n #saving: Promise<void> | undefined;\n readonly state: DurableObjectState;\n #seq = 0;\n broken = false;\n #brokenCause: unknown;\n\n /** blockConcurrencyWhile() rejected (CF: the object is reset; queued events fail). */\n #breakOn(e: unknown): void {\n this.broken = true;\n this.#brokenCause = e;\n }\n\n constructor(opts: {\n cellKey: string;\n id: DurableObjectId;\n cls: DurableObjectClass;\n env: unknown;\n openSql: OpenCellSql;\n durability: CellDurability;\n codec: ValueCodec;\n waitUntil: (p: Promise<unknown>) => void;\n backup?: CellBackup;\n /** The stored alarm changed (null = cleared). */\n onAlarmChange?: (at: number | null) => void;\n /** `ctx.exports` (loopback handles of the Worker's exports). */\n exports?: Record<string, unknown>;\n /** `ctx.props` of a facet started from a class handle with `{ props }`. */\n props?: unknown;\n /** SQLite extensions to load into every cell database (e.g. \"sqlite_vec\"). */\n sqlExtensions?: string[];\n /** storage.deleteAll() keeps the alarm (`delete_all_preserves_alarm`). */\n deleteAllPreservesAlarm?: boolean;\n /**\n * Ownership: acquire the cell's lease before restoring it. No lease → the cell is owned\n * elsewhere (the host refuses events). The lease epoch fences the cell's log segments;\n * losing the lease breaks the host so it stops serving.\n */\n /** Owner epoch when no lease is taken (facets inherit their root's). */\n epoch?: number;\n /** A facet: on open its rows move to this run's scope, as celld does. */\n facet?: boolean;\n acquire?: Lease[\"tryAcquire\"];\n /** The async context events start in (`asyncRoot()`): not the caller's, as on Cloudflare. */\n asyncRoot?: AsyncRoot;\n }) {\n this.#backup = opts.backup;\n this.cellKey = opts.cellKey;\n this.#epoch = opts.epoch;\n this.#opts = opts;\n this.#open = () => {\n this.#db = opts.openSql(opts.cellKey);\n for (const ext of opts.sqlExtensions ?? []) this.#db.loadExtension(ext);\n };\n this.#open();\n this.#sql = new SqlStorage(\n this.#driver,\n (changes) => {\n if (changes && this.#epoch !== undefined) changes.epoch = this.#epoch;\n // Page-level logs (LTX): the changed pages straight from the page hook when the driver\n // has one; the image only on demand (a generation's first snapshot, or no hook).\n const d = this.#driver;\n const seq = ++this.#seq;\n const pages = opts.durability.capturePages ? d.takeDirtyPages() : undefined;\n const snap = () => d.pageImage?.() ?? d.image?.();\n // The log runs later, after the next event may have opened its transaction, and an\n // image cannot be taken inside one (VACUUM INTO). When the log will surely need it\n // (no page hook) or likely does (this host's first commit), take it now.\n const image = opts.durability.capturePages\n ? !pages || seq === 1\n ? snap()\n : snap\n : undefined;\n const durable = opts.durability.committed(this.cellKey, {\n seq,\n changes,\n image,\n pages,\n epoch: this.#epoch,\n });\n const wake = this.#wakeAfterCommit();\n return this.#out.track(wake ? durable.then(wake) : durable);\n },\n { capture: !!opts.durability.captureChanges },\n );\n // The cell's scope in celld's tables (\"Class:idhex\"), so its database is celld's format.\n const kv = new SyncKvStorage(this.#sql, opts.codec, scopeOf(opts.cellKey));\n if (!opts.facet) kv.actorName = opts.id.name;\n const storage = new DurableObjectStorage(this.#sql, kv, this.#gate, () => this.#barrier());\n if (opts.onAlarmChange) storage.onAlarmChange = opts.onAlarmChange;\n storage.deleteAllPreservesAlarm = !!opts.deleteAllPreservesAlarm;\n const state = new DurableObjectState(opts.id, storage, this.#gate, opts.waitUntil, (e) =>\n this.#breakOn(e),\n );\n this.state = state;\n state.attachDispatcher((fn) => this.deliver(fn));\n // ctx.abort(reason) (workerd, celld): the object resets — a fresh instance on the same\n // database serves the next event; the calling event fails with the reason. Writes the event\n // already made still commit (celld: celld's workflow cell aborts after its delete commit).\n (state as unknown as { abort(reason?: unknown): never }).abort = (reason?: unknown): never => {\n queueMicrotask(() => this.restart());\n throw reason ?? new Error(\"Durable Object reset because its code calls abort()\");\n };\n state.exports = opts.exports ?? {};\n state.props = opts.props;\n state.facets = createFacets(\n { ...opts, epoch: () => this.#epoch },\n (name, cls, env, id, props) => {\n const facet = new ObjectHost({\n ...opts,\n // celld's facet stream: <parent>/facets/<SHA-256(name)[0..16] hex> (engine_api.rs)\n cellKey: `${opts.cellKey}/facets/${facetSegment(name)}`,\n id,\n cls,\n env,\n props,\n onAlarmChange: undefined,\n // A facet is part of its root's cell: no lease of its own, the root's epoch.\n acquire: undefined,\n epoch: this.#epoch,\n facet: true,\n });\n this.#facets.add(facet); // closed with its root\n return facet;\n },\n );\n const root = opts.asyncRoot ?? ((fn) => fn());\n this.#root = root;\n const construct = () => root(() => (this.#instance = new opts.cls(state, opts.env)));\n this.#construct = construct;\n const load = opts.backup?.load;\n const replay = opts.backup?.replay;\n const acquire = opts.acquire;\n if (!load && !replay && !acquire) {\n this.#nameFromMetadata(state);\n construct();\n return;\n }\n // Restore-on-open: events queue behind the closed gate until the image is in.\n void this.#gate\n .runClosed(async () => {\n if (acquire) {\n const lease = await acquire(this.cellKey);\n if (!lease) throw new CellOwnedElsewhereError(this.cellKey);\n this.#epoch = lease.epoch;\n this.#release = lease.release;\n lease.lost.addEventListener(\n \"abort\",\n () => this.#breakOn(new Error(`lease of ${this.cellKey} lost`)),\n {\n once: true,\n },\n );\n }\n // Under a lease (the cell's own, or its root's for a facet) the bucket is the cell's\n // truth: a local file kept from an earlier ownership is older than what other owners\n // wrote since, and may hold commits that never became durable.\n await this.#catchUp(this.#epoch !== undefined);\n if (opts.facet) this.#rescope(scopeOf(opts.cellKey));\n else {\n this.#initWake();\n this.#scheduleRestoredAlarm(opts.onAlarmChange);\n }\n this.#nameFromMetadata(state);\n construct();\n })\n .catch((e) => this.#breakOn(e));\n }\n\n /**\n * Takes an image if the cell changed since the last successful save and hands\n * it to `backup.save`. Taken synchronously between events → a consistent image.\n * Skipped while an async transaction() holds the database or a save is running.\n */\n backupIfDirty(reason: BackupInfo[\"reason\"], now: number): Promise<void> {\n const b = this.#backup;\n if (!b || this.broken || this.#saving || this.#seq === this.#backedUpSeq)\n return this.#saving ?? Promise.resolve();\n if (!this.#driver.image)\n return Promise.reject(new Error(\"SyncSqlDriver has no image(): cannot back up\"));\n if (this.#sql.held) return Promise.resolve(); // mid-transaction: next round\n this.#sql.commit();\n const seq = this.#seq;\n let logSeq = 0;\n try {\n logSeq = Number(this.#driver.exec(LOG_SEQ_READ, []).rows[0]?.[0] ?? 0);\n } catch {\n // no _cf_LOG yet\n }\n const image = this.#driver.image();\n this.#saving = b\n .save(this.cellKey, image, { seq, takenAt: now, reason, logSeq })\n .then(\n () => {\n this.#backedUpSeq = Math.max(this.#backedUpSeq, seq);\n },\n (e) => b.onError?.(this.cellKey, e),\n )\n .finally(() => (this.#saving = undefined));\n return this.#saving;\n }\n\n /**\n * Input gate → handler → commit → output gate (durability) → result.\n *\n * Events are queued and STARTED synchronously by a pump only while the gate\n * is open: the first storage op of a handler closes the gate before the\n * next event can start (checking the gate in an `await` continuation is too\n * late — every queued continuation would see it open).\n */\n deliver<T>(fn: (instance: any, state: DurableObjectState) => T | Promise<T>): Promise<T> {\n if (this.broken) return Promise.reject(new BrokenObjectError(undefined));\n return new Promise<T>((resolve, reject) => {\n this.#queue.push(() => {\n if (this.broken)\n return reject(new BrokenObjectError(this.#brokenCause, \"its initialization failed\"));\n let started: Promise<T>;\n this.#active++;\n try {\n started = Promise.resolve(this.#root(() => fn(this.#instance, this.state)));\n } catch (e) {\n started = Promise.reject(e);\n }\n const done = () => {\n this.#active--;\n this.lastActive = Date.now();\n };\n started.then(\n (r) => {\n this.#pinIfStandardWebSocket(r);\n this.#barrier().then(\n () => (done(), resolve(r)),\n (e) => (done(), reject(e)),\n );\n },\n (e) =>\n this.#barrier().then(\n () => (done(), reject(e)),\n (e2) => (done(), reject(e2)),\n ),\n );\n });\n this.#pump();\n });\n }\n\n #queue: (() => void)[] = [];\n #pumpWaiting = false;\n #pump = (): void => {\n this.#pumpWaiting = false;\n while (this.#queue.length && this.#gate.isOpen) {\n // A database closed while idle: reopen it (and catch up) before anything runs.\n if (this.#dbClosed) {\n this.#dbClosed = false;\n void this.#gate\n .runClosed(async () => {\n this.#open();\n // The lease was held throughout: a kept file is current, an empty one is restored.\n await this.#catchUp(false);\n })\n .catch((e) => this.#breakOn(e));\n continue;\n }\n // Waking from hibernation: the constructor runs again before the event (and may\n // close the gate with blockConcurrencyWhile, which the loop then respects).\n if (this.#hibernated) {\n this.#hibernated = false;\n this.#construct?.();\n continue;\n }\n this.#queue.shift()!();\n }\n if (this.#queue.length && !this.#pumpWaiting) {\n this.#pumpWaiting = true;\n this.#gate.onOpen(this.#pump);\n }\n };\n\n async #barrier(): Promise<void> {\n try {\n this.#sql.commit();\n await this.#out.barrier();\n } catch (e) {\n this.broken = true;\n try {\n this.#sql.rollback();\n } catch {}\n throw new BrokenObjectError(e);\n }\n }\n\n /** Settles once the cell lease is released (a store closed earlier would keep it held). */\n close(): Promise<void> {\n for (const facet of this.#facets) void facet.close();\n this.#facets.clear();\n if (!this.#dbClosed) this.#db.close();\n // Hand the cell over at once instead of letting the lease expire.\n const released = this.#release?.().catch(() => {});\n this.#release = undefined;\n return released ?? Promise.resolve();\n }\n #release: (() => Promise<void>) | undefined;\n /** The hosts of this cell's facets: their databases close with the root's. */\n readonly #facets = new Set<ObjectHost>();\n\n /**\n * Brings the local database to the storage's state: restores the image, then replays the log.\n * Without `rebuild` only an empty database is restored (the local file is the primary copy);\n * with it, a non-empty one is replaced too — dropped first when the storage has no image.\n */\n async #catchUp(rebuild: boolean): Promise<void> {\n const { load, replay } = this.#backup ?? {};\n if (!load && !replay) return;\n const d = this.#driver;\n const empty = Number(d.exec(\"SELECT count(*) FROM sqlite_master\", []).rows[0][0]) === 0;\n if (!empty && !rebuild) return;\n const image = await load?.(this.cellKey);\n if (image) {\n if (!d.restore) throw new Error(\"SyncSqlDriver has no restore(): cannot restore a backup\");\n d.restore(image);\n } else if (!empty) {\n // Indexes and triggers go with their tables; sqlite_* tables cannot be dropped. Foreign\n // keys are off meanwhile, so a parent table can go before its children.\n const objects = d.exec(\n \"SELECT type, name FROM sqlite_master WHERE type IN ('view', 'table') AND name NOT LIKE 'sqlite_%'\",\n [],\n ).rows;\n const fk = Number(d.exec(\"PRAGMA foreign_keys\", []).rows[0][0]);\n d.exec(\"PRAGMA foreign_keys = OFF\", []);\n try {\n for (const [type, name] of objects)\n d.exec(`DROP ${type} IF EXISTS \"${String(name).replace(/\"/g, '\"\"')}\"`, []);\n } finally {\n d.exec(`PRAGMA foreign_keys = ${fk}`, []);\n }\n }\n // Then every logged transaction the image does not contain, in order.\n if (replay) await this.#replayLog(replay);\n }\n\n /** Applies log segments newer than the database's own log sequence (restore path). */\n async #replayLog(replay: NonNullable<CellBackup[\"replay\"]>): Promise<void> {\n const d = this.#driver;\n d.exec(LOG_TABLE, []);\n const row = d.exec(LOG_SEQ_READ, []).rows[0];\n const after = Number(row?.[0] ?? 0);\n for await (const seg of replay(this.cellKey, after)) {\n if (!d.applyChangeset)\n throw new Error(\"SyncSqlDriver cannot apply changesets: cannot replay a log\");\n d.exec(\"BEGIN\", []);\n try {\n for (const ddl of seg.ddl) d.exec(ddl, []);\n d.applyChangeset(seg.changeset);\n for (const [sql, params] of seg.statements) d.exec(sql, params);\n d.exec(LOG_SEQ_WRITE, [seg.logSeq]);\n d.exec(\"COMMIT\", []);\n } catch (e) {\n d.exec(\"ROLLBACK\", []);\n throw e;\n }\n }\n }\n\n #construct?: () => unknown;\n #root: AsyncRoot = (fn) => fn();\n readonly #open: () => void;\n #epoch: number | undefined;\n\n /**\n * celld gives each run of a facet its own scope and moves the facet database's rows to it\n * on open (storage.rs open_embedded); doing the same here reads a facet database celld\n * wrote, whatever scope it used.\n */\n /**\n * celld's alarm publication identity (storage/wake_record.rs initialize): one `_cf_WAKE`\n * row per cell carrying the writer epoch; triggers bump its sequence on every alarm change.\n */\n #initWake(): void {\n if (!this.#epoch || !this.#opts.durability.publishWake) return;\n const scope = scopeOf(this.cellKey);\n for (const ddl of CELLD_SCHEMA) this.#driver.exec(ddl, []);\n this.#driver.exec(\n `INSERT INTO _cf_WAKE(scope,epoch,sequence,at_ms)\n VALUES(?1,?2,0,(SELECT at_ms FROM _cf_ALARM WHERE scope=?1))\n ON CONFLICT(scope) DO UPDATE SET epoch=excluded.epoch WHERE excluded.epoch>_cf_WAKE.epoch`,\n [scope, this.#epoch.toString(16).padStart(16, \"0\")],\n );\n this.#wakeSeq = this.#wakeRow()?.sequence;\n }\n /**\n * A cell restored on open may carry an alarm armed by its previous owner (another node, or\n * celld). This node owns the cell now, so the alarm is its to fire: hand it to the scheduler,\n * which otherwise only hears of alarms set here (or of a later wake-index poll).\n */\n #scheduleRestoredAlarm(onAlarmChange?: (at: number) => void): void {\n let at: unknown;\n try {\n at = this.#driver.exec(\"SELECT at_ms FROM _cf_ALARM WHERE scope = ?\", [scopeOf(this.cellKey)])\n .rows[0]?.[0];\n } catch {\n return; // no alarm table: the cell never had an alarm\n }\n if (at != null) onAlarmChange?.(Number(at));\n }\n #wakeSeq: number | undefined;\n #wakeRow(): { epoch: number; sequence: number; at: number | null } | undefined {\n try {\n const r = this.#driver.exec(\"SELECT epoch, sequence, at_ms FROM _cf_WAKE WHERE scope = ?\", [\n scopeOf(this.cellKey),\n ]).rows[0];\n return r\n ? {\n epoch: Number.parseInt(String(r[0]), 16),\n sequence: Number(r[1]),\n at: r[2] == null ? null : Number(r[2]),\n }\n : undefined;\n } catch {\n return undefined;\n }\n }\n /**\n * After a commit: if it changed the alarm, a publication to run once the commit is durable\n * (celld publishes after replication).\n */\n #wakeAfterCommit(): (() => Promise<void>) | undefined {\n const publish = this.#opts.durability.publishWake;\n if (!publish || this.#opts.facet || !this.#epoch) return undefined;\n const row = this.#wakeRow();\n if (!row || row.sequence === this.#wakeSeq) return undefined;\n this.#wakeSeq = row.sequence;\n return () => publish(this.cellKey, row);\n }\n readonly #opts: { durability: CellDurability; facet?: boolean };\n\n /**\n * celld records the name an object was addressed by (`_cf_METADATA.actor_name`) and gives it\n * back as `ctx.id.name` when the object is woken by id alone (an alarm, a wake entry) —\n * celld's own queue cells rely on it. Both directions here: restore it, and record it.\n */\n #nameFromMetadata(state: { id: DurableObjectId }): void {\n if (this.#opts.facet) return;\n const scope = scopeOf(this.cellKey);\n // Reading only: no DDL or write outside a logged transaction (a changeset log replays\n // only what it captured). The name is recorded with the cell's first storage write.\n if (state.id.name !== undefined) return;\n try {\n const r = this.#driver.exec(\"SELECT actor_name FROM _cf_METADATA WHERE scope = ?\", [scope])\n .rows[0];\n if (r?.[0] != null)\n (state as { id: DurableObjectId }).id = new DurableObjectIdClass(\n state.id.toString(),\n String(r[0]),\n );\n } catch {\n // no _cf_METADATA yet\n }\n }\n\n #rescope(scope: string): void {\n for (const table of [\"_cf_KV\", \"_cf_ALARM\", \"_cf_METADATA\"])\n try {\n this.#driver.exec(`UPDATE ${table} SET scope = ? WHERE scope <> ?`, [scope, scope]);\n } catch {\n // table not created yet\n }\n }\n\n // ---- hibernation ---------------------------------------------------------------------\n #active = 0;\n #hibernated = false;\n #pinned = 0;\n /** Time of the last event's completion (the runtime's idle sweep reads it). */\n lastActive = Date.now();\n\n get hibernated(): boolean {\n return this.#hibernated;\n }\n\n /**\n * A 101 response whose server end was accepted with `accept()` (not acceptWebSocket)\n * holds a standard WebSocket: the object cannot hibernate until that socket closes —\n * as on Cloudflare, only the hibernation API lets an object sleep with open sockets.\n */\n #pinIfStandardWebSocket(r: unknown): void {\n const server = (\n r as { webSocket?: { peer?: { accepted: boolean; hibernatable: boolean } & EventTarget } }\n )?.webSocket?.peer;\n if (!server || server.hibernatable || !server.accepted) return;\n this.#pinned++;\n server.addEventListener(\"close\", () => this.#pinned--, { once: true });\n }\n\n /**\n * Drops the instance when nothing runs: no event in flight or queued, no open async\n * transaction, no standard WebSocket. Storage, alarms and hibernatable sockets stay; the\n * next event constructs the class again. Returns whether it hibernated.\n */\n hibernate(): boolean {\n if (\n this.#hibernated ||\n this.broken ||\n this.#active ||\n this.#queue.length ||\n this.#sql.held ||\n this.#pinned\n )\n return false;\n if (!this.#gate.isOpen) return false;\n this.#sql.commit();\n this.#instance = undefined;\n this.#hibernated = true;\n return true;\n }\n #dbClosed = false;\n /**\n * Closes the database of a hibernated cell (the cell lease stays); the next event reopens it.\n * A cell with changes its backup has not taken yet stays open. Returns whether it closed.\n */\n closeDatabase(): boolean {\n if (!this.#hibernated || this.#dbClosed || this.#queue.length || !this.#gate.isOpen)\n return false;\n if (this.#backup && (this.#saving || this.#seq !== this.#backedUpSeq)) return false;\n this.#db.close();\n this.#dbClosed = true;\n return true;\n }\n /** Replaces the instance with a fresh one on the SAME database (facet abort/delete). */\n restart(): void {\n if (this.#dbClosed) return; // the next event reopens it with a fresh instance\n this.#construct?.();\n }\n}\n\n/**\n * `ctx.facets` (celld docs/services/durable-object-facets.md): named child objects with a\n * SQLite database of their own (`<cellKey>/facets/<name>`), started on first call from a\n * class (or class handle) returned by the callback; the name alone selects the database.\n */\ninterface FacetTarget {\n call(method: string, args: unknown[]): Promise<unknown>;\n fetch(req: Request): Promise<Response>;\n restart(): void | Promise<void>;\n delete(): Promise<void>;\n}\n\nfunction createFacets(\n parent: { id: DurableObjectId; env: unknown; cellKey: string; epoch?: () => number | undefined },\n spawn: (\n name: string,\n cls: DurableObjectClass,\n env: unknown,\n id: DurableObjectId,\n props?: unknown,\n ) => ObjectHost,\n) {\n const running = new Map<string, Promise<FacetTarget>>();\n // abort() stops the stubs handed out so far (their calls throw the reason); a later\n // get() starts the facet again on the same database — as celld does.\n const generation = new Map<string, { n: number; reason?: unknown }>();\n const local = (h: ObjectHost): FacetTarget => ({\n call: (method, args) =>\n h.deliver((obj) => {\n const fn = obj[method];\n if (typeof fn !== \"function\") throw new TypeError(`${method} is not a function`);\n return fn.apply(obj, args);\n }),\n fetch: (req) => h.deliver((obj) => obj.fetch(req)),\n restart: () => h.restart(),\n delete: async () => {\n await h.deliver((_o, state) => state.storage.deleteAll());\n h.restart();\n },\n });\n /** A class of isolated loaded code: the facet's instance and SQLite live in the isolate. */\n const isolated = (iso: IsolatedClass, cellKey: string): FacetTarget => {\n const attached = iso.attach?.(cellKey, parent.epoch?.());\n const ready = async () => attached;\n return {\n call: async (method, args) => (await ready(), iso.call(cellKey, method, args)),\n fetch: async (req) => (await ready(), iso.fetch(cellKey, req)),\n restart: async () => (await ready(), iso.restart(cellKey)),\n delete: async () => (await ready(), iso.delete(cellKey)),\n };\n };\n\n const targetOf = (name: string, start?: () => unknown): Promise<FacetTarget> => {\n let p = running.get(name);\n if (!p) {\n if (!start) return Promise.reject(new Error(`Facet \"${name}\" is not running`));\n p = (async () => {\n const info = (await start()) as { class: unknown; id?: unknown };\n let cls: DurableObjectClass;\n let env = parent.env;\n let props: unknown;\n if (isClassHandle(info.class)) {\n const r = await info.class.resolve();\n if (\"isolated\" in r)\n return isolated(r.isolated, `${parent.cellKey}/facets/${facetSegment(name)}`);\n ({ cls, env, props } = r);\n } else cls = info.class as DurableObjectClass;\n const id = info.id instanceof DurableObjectIdClass ? info.id : parent.id;\n return local(spawn(name, cls, env, id, props));\n })();\n p.catch(() => running.delete(name));\n running.set(name, p);\n }\n return p;\n };\n return {\n get(name: string, start: () => unknown) {\n if (new TextEncoder().encode(name).byteLength > 256)\n throw new Error(\"A facet name has a limit of 256 bytes\");\n const gen = generation.get(name)?.n ?? 0;\n const live = () => {\n const g = generation.get(name);\n if (g && g.n !== gen) throw g.reason;\n };\n return asyncStub(\n async (method, args) => (live(), await targetOf(name, start)).call(method, args),\n async (req) => (live(), await targetOf(name, start)).fetch(req),\n );\n },\n abort(name: string, reason?: unknown) {\n const n = (generation.get(name)?.n ?? 0) + 1;\n generation.set(name, { n, reason: reason ?? new Error(`Facet \"${name}\" was aborted`) });\n // The database stays: the next call on a new stub gets a fresh instance over it.\n void running.get(name)?.then((t) => t.restart());\n },\n async delete(name: string) {\n const p = running.get(name);\n generation.set(name, {\n n: (generation.get(name)?.n ?? 0) + 1,\n reason: new Error(`Facet \"${name}\" was deleted`),\n });\n if (p) await (await p).delete();\n },\n };\n}\n\n/** The cell's lease is held by another owner (route the request there, or retry later). */\nexport class CellOwnedElsewhereError extends Error {\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} is owned by another node`);\n this.name = \"CellOwnedElsewhereError\";\n }\n}\n\n/** celld's path segment for a facet name: the first 16 bytes of SHA-256(name), hex. */\nexport function facetSegment(name: string): string {\n return bytesToHex(sha256(new TextEncoder().encode(name)).subarray(0, 16));\n}\n"]}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F,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAChD,YAAY,OAAe;QACzB,KAAK,CAAC,kBAAkB,OAAO,2BAA2B,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED,uFAAuF;AACvF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport type {\n BackupInfo,\n CellBackup,\n CellDurability,\n Lease,\n OpenCellSql,\n SyncSqlDriver,\n ValueCodec,\n} from \"../ports.js\";\nimport type { AsyncRoot } from \"./async-context.js\";\nimport { CELLD_SCHEMA, LOG_SEQ_READ, LOG_SEQ_WRITE, LOG_TABLE, scopeOf } from \"./celld-schema.js\";\nimport { InputGate, OutputGate } from \"./gates.js\";\nimport {\n asyncStub,\n type DurableObjectClass,\n type IsolatedClass,\n isClassHandle,\n} from \"./handles.js\";\nimport { type DurableObjectId, DurableObjectId as DurableObjectIdClass } from \"./id.js\";\nimport { SqlStorage } from \"./sql-storage.js\";\nimport { DurableObjectState } from \"./state.js\";\nimport { DurableObjectStorage, SyncKvStorage } from \"./storage.js\";\n\n/**\n * The request as the object sees it: its signal also aborts when the host closes (the runtime\n * shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that\n * waits on it then ends instead of running on into a closed database.\n */\nexport function closingWith(req: Request, closing: AbortSignal): Request {\n if (closing.aborted) return req;\n const r = new Request(req, { signal: AbortSignal.any([req.signal, closing]) });\n // What cellb set on the request itself (`cf`; `headers` carrying a WebSocket upgrade's\n // headers, which a Request would drop) stays as it was.\n for (const k of [\"cf\", \"headers\"]) {\n const d = Object.getOwnPropertyDescriptor(req, k);\n if (d) Object.defineProperty(r, k, d);\n }\n return r;\n}\n\n/** The object's host was closed for good: its storage and events fail with this. */\nexport class ObjectClosedError extends Error {\n override name = \"ObjectClosedError\";\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} was closed (its runtime shut down, or it moved or was reset)`);\n }\n}\n\nexport class BrokenObjectError extends Error {\n constructor(cause: unknown, reason = \"its storage failed to commit durably\") {\n const detail = cause instanceof Error ? `: ${cause.message}` : \"\";\n super(`Durable Object reset because ${reason}${detail}`, { cause });\n this.name = \"BrokenObjectError\";\n }\n}\n\n/**\n * One live instance of one Durable Object: its SQLite, gates and dispatcher.\n * Everything that reaches the object (fetch, RPC, later alarms/WebSockets)\n * goes through `deliver()`.\n */\nexport class ObjectHost {\n readonly cellKey: string;\n readonly #gate = new InputGate();\n readonly #out = new OutputGate();\n /** The open database; `#driver` follows it, so it can be closed while idle and reopened. */\n #db!: SyncSqlDriver;\n readonly #driver: SyncSqlDriver = new Proxy({} as SyncSqlDriver, {\n get: (_t, k) => {\n // Closed for good (its runtime or shard shut down): code still running in the object\n // learns why, instead of SQLite's \"DB has been closed\".\n if (this.#closed && k !== \"close\")\n return () => {\n throw new ObjectClosedError(this.cellKey);\n };\n const v = (this.#db as unknown as Record<PropertyKey, unknown>)[k];\n return typeof v === \"function\" ? v.bind(this.#db) : v;\n },\n });\n readonly #sql: SqlStorage;\n #instance: any;\n readonly #backup?: CellBackup;\n #backedUpSeq = 0;\n #saving: Promise<void> | undefined;\n readonly state: DurableObjectState;\n #seq = 0;\n broken = false;\n #brokenCause: unknown;\n\n /** blockConcurrencyWhile() rejected (CF: the object is reset; queued events fail). */\n #breakOn(e: unknown): void {\n this.broken = true;\n this.#brokenCause = e;\n }\n\n constructor(opts: {\n cellKey: string;\n id: DurableObjectId;\n cls: DurableObjectClass;\n env: unknown;\n openSql: OpenCellSql;\n durability: CellDurability;\n codec: ValueCodec;\n waitUntil: (p: Promise<unknown>) => void;\n backup?: CellBackup;\n /** The stored alarm changed (null = cleared). */\n onAlarmChange?: (at: number | null) => void;\n /** `ctx.exports` (loopback handles of the Worker's exports). */\n exports?: Record<string, unknown>;\n /** `ctx.props` of a facet started from a class handle with `{ props }`. */\n props?: unknown;\n /** SQLite extensions to load into every cell database (e.g. \"sqlite_vec\"). */\n sqlExtensions?: string[];\n /** storage.deleteAll() keeps the alarm (`delete_all_preserves_alarm`). */\n deleteAllPreservesAlarm?: boolean;\n /**\n * Ownership: acquire the cell's lease before restoring it. No lease → the cell is owned\n * elsewhere (the host refuses events). The lease epoch fences the cell's log segments;\n * losing the lease breaks the host so it stops serving.\n */\n /** Owner epoch when no lease is taken (facets inherit their root's). */\n epoch?: number;\n /** A facet: on open its rows move to this run's scope, as celld does. */\n facet?: boolean;\n acquire?: Lease[\"tryAcquire\"];\n /** The async context events start in (`asyncRoot()`): not the caller's, as on Cloudflare. */\n asyncRoot?: AsyncRoot;\n }) {\n this.#backup = opts.backup;\n this.cellKey = opts.cellKey;\n this.#epoch = opts.epoch;\n this.#opts = opts;\n this.#open = () => {\n this.#db = opts.openSql(opts.cellKey);\n for (const ext of opts.sqlExtensions ?? []) this.#db.loadExtension(ext);\n };\n this.#open();\n this.#sql = new SqlStorage(\n this.#driver,\n (changes) => {\n if (changes && this.#epoch !== undefined) changes.epoch = this.#epoch;\n // Page-level logs (LTX): the changed pages straight from the page hook when the driver\n // has one; the image only on demand (a generation's first snapshot, or no hook).\n const d = this.#driver;\n const seq = ++this.#seq;\n const pages = opts.durability.capturePages ? d.takeDirtyPages() : undefined;\n const snap = () => d.pageImage?.() ?? d.image?.();\n // The log runs later, after the next event may have opened its transaction, and an\n // image cannot be taken inside one (VACUUM INTO). When the log will surely need it\n // (no page hook) or likely does (this host's first commit), take it now.\n const image = opts.durability.capturePages\n ? !pages || seq === 1\n ? snap()\n : snap\n : undefined;\n const durable = opts.durability.committed(this.cellKey, {\n seq,\n changes,\n image,\n pages,\n epoch: this.#epoch,\n });\n const wake = this.#wakeAfterCommit();\n return this.#out.track(wake ? durable.then(wake) : durable);\n },\n { capture: !!opts.durability.captureChanges },\n );\n // The cell's scope in celld's tables (\"Class:idhex\"), so its database is celld's format.\n const kv = new SyncKvStorage(this.#sql, opts.codec, scopeOf(opts.cellKey));\n if (!opts.facet) kv.actorName = opts.id.name;\n const storage = new DurableObjectStorage(this.#sql, kv, this.#gate, () => this.#barrier());\n if (opts.onAlarmChange) storage.onAlarmChange = opts.onAlarmChange;\n storage.deleteAllPreservesAlarm = !!opts.deleteAllPreservesAlarm;\n const state = new DurableObjectState(opts.id, storage, this.#gate, opts.waitUntil, (e) =>\n this.#breakOn(e),\n );\n this.state = state;\n state.attachDispatcher((fn) => this.deliver(fn));\n // ctx.abort(reason) (workerd, celld): the object resets — a fresh instance on the same\n // database serves the next event; the calling event fails with the reason. Writes the event\n // already made still commit (celld: celld's workflow cell aborts after its delete commit).\n (state as unknown as { abort(reason?: unknown): never }).abort = (reason?: unknown): never => {\n queueMicrotask(() => this.restart());\n throw reason ?? new Error(\"Durable Object reset because its code calls abort()\");\n };\n state.exports = opts.exports ?? {};\n state.props = opts.props;\n state.facets = createFacets(\n { ...opts, epoch: () => this.#epoch },\n (name, cls, env, id, props) => {\n const facet = new ObjectHost({\n ...opts,\n // celld's facet stream: <parent>/facets/<SHA-256(name)[0..16] hex> (engine_api.rs)\n cellKey: `${opts.cellKey}/facets/${facetSegment(name)}`,\n id,\n cls,\n env,\n props,\n onAlarmChange: undefined,\n // A facet is part of its root's cell: no lease of its own, the root's epoch.\n acquire: undefined,\n epoch: this.#epoch,\n facet: true,\n });\n this.#facets.add(facet); // closed with its root\n return facet;\n },\n );\n const root = opts.asyncRoot ?? ((fn) => fn());\n this.#root = root;\n const construct = () => root(() => (this.#instance = new opts.cls(state, opts.env)));\n this.#construct = construct;\n const load = opts.backup?.load;\n const replay = opts.backup?.replay;\n const acquire = opts.acquire;\n if (!load && !replay && !acquire) {\n this.#nameFromMetadata(state);\n construct();\n return;\n }\n // Restore-on-open: events queue behind the closed gate until the image is in.\n void this.#gate\n .runClosed(async () => {\n if (acquire) {\n const lease = await acquire(this.cellKey);\n if (!lease) throw new CellOwnedElsewhereError(this.cellKey);\n this.#epoch = lease.epoch;\n this.#release = lease.release;\n lease.lost.addEventListener(\n \"abort\",\n () => this.#breakOn(new Error(`lease of ${this.cellKey} lost`)),\n {\n once: true,\n },\n );\n }\n // Under a lease (the cell's own, or its root's for a facet) the bucket is the cell's\n // truth: a local file kept from an earlier ownership is older than what other owners\n // wrote since, and may hold commits that never became durable.\n await this.#catchUp(this.#epoch !== undefined);\n if (opts.facet) this.#rescope(scopeOf(opts.cellKey));\n else {\n this.#initWake();\n this.#scheduleRestoredAlarm(opts.onAlarmChange);\n }\n this.#nameFromMetadata(state);\n construct();\n })\n .catch((e) => this.#breakOn(e));\n }\n\n /**\n * Takes an image if the cell changed since the last successful save and hands\n * it to `backup.save`. Taken synchronously between events → a consistent image.\n * Skipped while an async transaction() holds the database or a save is running.\n */\n backupIfDirty(reason: BackupInfo[\"reason\"], now: number): Promise<void> {\n const b = this.#backup;\n if (!b || this.broken || this.#saving || this.#seq === this.#backedUpSeq)\n return this.#saving ?? Promise.resolve();\n if (!this.#driver.image)\n return Promise.reject(new Error(\"SyncSqlDriver has no image(): cannot back up\"));\n if (this.#sql.held) return Promise.resolve(); // mid-transaction: next round\n this.#sql.commit();\n const seq = this.#seq;\n let logSeq = 0;\n try {\n logSeq = Number(this.#driver.exec(LOG_SEQ_READ, []).rows[0]?.[0] ?? 0);\n } catch {\n // no _cf_LOG yet\n }\n const image = this.#driver.image();\n this.#saving = b\n .save(this.cellKey, image, { seq, takenAt: now, reason, logSeq })\n .then(\n () => {\n this.#backedUpSeq = Math.max(this.#backedUpSeq, seq);\n },\n (e) => b.onError?.(this.cellKey, e),\n )\n .finally(() => (this.#saving = undefined));\n return this.#saving;\n }\n\n /**\n * Input gate → handler → commit → output gate (durability) → result.\n *\n * Events are queued and STARTED synchronously by a pump only while the gate\n * is open: the first storage op of a handler closes the gate before the\n * next event can start (checking the gate in an `await` continuation is too\n * late — every queued continuation would see it open).\n */\n deliver<T>(fn: (instance: any, state: DurableObjectState) => T | Promise<T>): Promise<T> {\n if (this.#closed) return Promise.reject(new ObjectClosedError(this.cellKey));\n if (this.broken) return Promise.reject(new BrokenObjectError(undefined));\n return new Promise<T>((resolve, reject) => {\n this.#queue.push(() => {\n if (this.#closed) return reject(new ObjectClosedError(this.cellKey));\n if (this.broken)\n return reject(new BrokenObjectError(this.#brokenCause, \"its initialization failed\"));\n let started: Promise<T>;\n this.#active++;\n try {\n started = Promise.resolve(this.#root(() => fn(this.#instance, this.state)));\n } catch (e) {\n started = Promise.reject(e);\n }\n const done = () => {\n this.#active--;\n this.lastActive = Date.now();\n if (!this.#active && !this.#queue.length) this.#notifyIdle();\n };\n started.then(\n (r) => {\n this.#pinIfStandardWebSocket(r);\n this.#barrier().then(\n () => (done(), resolve(r)),\n (e) => (done(), reject(e)),\n );\n },\n (e) =>\n this.#barrier().then(\n () => (done(), reject(e)),\n (e2) => (done(), reject(e2)),\n ),\n );\n });\n this.#pump();\n });\n }\n\n #queue: (() => void)[] = [];\n #pumpWaiting = false;\n #pump = (): void => {\n this.#pumpWaiting = false;\n while (this.#queue.length && this.#gate.isOpen) {\n // A database closed while idle: reopen it (and catch up) before anything runs.\n if (this.#dbClosed) {\n this.#dbClosed = false;\n void this.#gate\n .runClosed(async () => {\n this.#open();\n // The lease was held throughout: a kept file is current, an empty one is restored.\n await this.#catchUp(false);\n })\n .catch((e) => this.#breakOn(e));\n continue;\n }\n // Waking from hibernation: the constructor runs again before the event (and may\n // close the gate with blockConcurrencyWhile, which the loop then respects).\n if (this.#hibernated) {\n this.#hibernated = false;\n this.#construct?.();\n continue;\n }\n this.#queue.shift()!();\n }\n if (this.#queue.length && !this.#pumpWaiting) {\n this.#pumpWaiting = true;\n this.#gate.onOpen(this.#pump);\n }\n };\n\n async #barrier(): Promise<void> {\n try {\n this.#sql.commit();\n await this.#out.barrier();\n } catch (e) {\n this.broken = true;\n try {\n this.#sql.rollback();\n } catch {}\n throw new BrokenObjectError(e);\n }\n }\n\n /**\n * Settles once no event is in flight or queued (a response body still streaming is not an\n * event: its handler has returned). The runtime waits for it, within a grace period, before\n * it closes the database on shutdown.\n */\n /** No event in flight or queued. */\n get idle(): boolean {\n return !this.#active && !this.#queue.length;\n }\n settled(): Promise<void> {\n if (!this.#active && !this.#queue.length) return Promise.resolve();\n return new Promise((resolve) => this.#idleWaiters.push(resolve));\n }\n #idleWaiters: (() => void)[] = [];\n #notifyIdle(): void {\n const waiters = this.#idleWaiters;\n this.#idleWaiters = [];\n for (const w of waiters) w();\n }\n\n /** Closed for good: storage calls throw ObjectClosedError. */\n #closed = false;\n readonly #closing = new AbortController();\n /** Aborts when the host is shutting down: the signal of the requests it is handed. */\n get closing(): AbortSignal {\n return this.#closing.signal;\n }\n /** The first step of a shutdown: requests in flight see their signal abort. */\n shutdown(): void {\n if (this.#closing.signal.aborted) return;\n this.#closing.abort(new ObjectClosedError(this.cellKey));\n for (const facet of this.#facets) facet.shutdown();\n }\n\n /** Settles once the cell lease is released (a store closed earlier would keep it held). */\n close(): Promise<void> {\n this.shutdown();\n this.#closed = true;\n for (const facet of this.#facets) void facet.close();\n this.#facets.clear();\n if (!this.#dbClosed) this.#db.close();\n // Events still queued fail (each checks #closed first); nothing more runs here.\n for (const queued of this.#queue.splice(0)) queued();\n this.#notifyIdle();\n // Hand the cell over at once instead of letting the lease expire.\n const released = this.#release?.().catch(() => {});\n this.#release = undefined;\n return released ?? Promise.resolve();\n }\n #release: (() => Promise<void>) | undefined;\n /** The hosts of this cell's facets: their databases close with the root's. */\n readonly #facets = new Set<ObjectHost>();\n\n /**\n * Brings the local database to the storage's state: restores the image, then replays the log.\n * Without `rebuild` only an empty database is restored (the local file is the primary copy);\n * with it, a non-empty one is replaced too — dropped first when the storage has no image.\n */\n async #catchUp(rebuild: boolean): Promise<void> {\n const { load, replay } = this.#backup ?? {};\n if (!load && !replay) return;\n const d = this.#driver;\n const empty = Number(d.exec(\"SELECT count(*) FROM sqlite_master\", []).rows[0][0]) === 0;\n if (!empty && !rebuild) return;\n const image = await load?.(this.cellKey);\n if (image) {\n if (!d.restore) throw new Error(\"SyncSqlDriver has no restore(): cannot restore a backup\");\n d.restore(image);\n } else if (!empty) {\n // Indexes and triggers go with their tables; sqlite_* tables cannot be dropped. Foreign\n // keys are off meanwhile, so a parent table can go before its children.\n const objects = d.exec(\n \"SELECT type, name FROM sqlite_master WHERE type IN ('view', 'table') AND name NOT LIKE 'sqlite_%'\",\n [],\n ).rows;\n const fk = Number(d.exec(\"PRAGMA foreign_keys\", []).rows[0][0]);\n d.exec(\"PRAGMA foreign_keys = OFF\", []);\n try {\n for (const [type, name] of objects)\n d.exec(`DROP ${type} IF EXISTS \"${String(name).replace(/\"/g, '\"\"')}\"`, []);\n } finally {\n d.exec(`PRAGMA foreign_keys = ${fk}`, []);\n }\n }\n // Then every logged transaction the image does not contain, in order.\n if (replay) await this.#replayLog(replay);\n }\n\n /** Applies log segments newer than the database's own log sequence (restore path). */\n async #replayLog(replay: NonNullable<CellBackup[\"replay\"]>): Promise<void> {\n const d = this.#driver;\n d.exec(LOG_TABLE, []);\n const row = d.exec(LOG_SEQ_READ, []).rows[0];\n const after = Number(row?.[0] ?? 0);\n for await (const seg of replay(this.cellKey, after)) {\n if (!d.applyChangeset)\n throw new Error(\"SyncSqlDriver cannot apply changesets: cannot replay a log\");\n d.exec(\"BEGIN\", []);\n try {\n for (const ddl of seg.ddl) d.exec(ddl, []);\n d.applyChangeset(seg.changeset);\n for (const [sql, params] of seg.statements) d.exec(sql, params);\n d.exec(LOG_SEQ_WRITE, [seg.logSeq]);\n d.exec(\"COMMIT\", []);\n } catch (e) {\n d.exec(\"ROLLBACK\", []);\n throw e;\n }\n }\n }\n\n #construct?: () => unknown;\n #root: AsyncRoot = (fn) => fn();\n readonly #open: () => void;\n #epoch: number | undefined;\n\n /**\n * celld gives each run of a facet its own scope and moves the facet database's rows to it\n * on open (storage.rs open_embedded); doing the same here reads a facet database celld\n * wrote, whatever scope it used.\n */\n /**\n * celld's alarm publication identity (storage/wake_record.rs initialize): one `_cf_WAKE`\n * row per cell carrying the writer epoch; triggers bump its sequence on every alarm change.\n */\n #initWake(): void {\n if (!this.#epoch || !this.#opts.durability.publishWake) return;\n const scope = scopeOf(this.cellKey);\n for (const ddl of CELLD_SCHEMA) this.#driver.exec(ddl, []);\n this.#driver.exec(\n `INSERT INTO _cf_WAKE(scope,epoch,sequence,at_ms)\n VALUES(?1,?2,0,(SELECT at_ms FROM _cf_ALARM WHERE scope=?1))\n ON CONFLICT(scope) DO UPDATE SET epoch=excluded.epoch WHERE excluded.epoch>_cf_WAKE.epoch`,\n [scope, this.#epoch.toString(16).padStart(16, \"0\")],\n );\n this.#wakeSeq = this.#wakeRow()?.sequence;\n }\n /**\n * A cell restored on open may carry an alarm armed by its previous owner (another node, or\n * celld). This node owns the cell now, so the alarm is its to fire: hand it to the scheduler,\n * which otherwise only hears of alarms set here (or of a later wake-index poll).\n */\n #scheduleRestoredAlarm(onAlarmChange?: (at: number) => void): void {\n let at: unknown;\n try {\n at = this.#driver.exec(\"SELECT at_ms FROM _cf_ALARM WHERE scope = ?\", [scopeOf(this.cellKey)])\n .rows[0]?.[0];\n } catch {\n return; // no alarm table: the cell never had an alarm\n }\n if (at != null) onAlarmChange?.(Number(at));\n }\n #wakeSeq: number | undefined;\n #wakeRow(): { epoch: number; sequence: number; at: number | null } | undefined {\n try {\n const r = this.#driver.exec(\"SELECT epoch, sequence, at_ms FROM _cf_WAKE WHERE scope = ?\", [\n scopeOf(this.cellKey),\n ]).rows[0];\n return r\n ? {\n epoch: Number.parseInt(String(r[0]), 16),\n sequence: Number(r[1]),\n at: r[2] == null ? null : Number(r[2]),\n }\n : undefined;\n } catch {\n return undefined;\n }\n }\n /**\n * After a commit: if it changed the alarm, a publication to run once the commit is durable\n * (celld publishes after replication).\n */\n #wakeAfterCommit(): (() => Promise<void>) | undefined {\n const publish = this.#opts.durability.publishWake;\n if (!publish || this.#opts.facet || !this.#epoch) return undefined;\n const row = this.#wakeRow();\n if (!row || row.sequence === this.#wakeSeq) return undefined;\n this.#wakeSeq = row.sequence;\n return () => publish(this.cellKey, row);\n }\n readonly #opts: { durability: CellDurability; facet?: boolean };\n\n /**\n * celld records the name an object was addressed by (`_cf_METADATA.actor_name`) and gives it\n * back as `ctx.id.name` when the object is woken by id alone (an alarm, a wake entry) —\n * celld's own queue cells rely on it. Both directions here: restore it, and record it.\n */\n #nameFromMetadata(state: { id: DurableObjectId }): void {\n if (this.#opts.facet) return;\n const scope = scopeOf(this.cellKey);\n // Reading only: no DDL or write outside a logged transaction (a changeset log replays\n // only what it captured). The name is recorded with the cell's first storage write.\n if (state.id.name !== undefined) return;\n try {\n const r = this.#driver.exec(\"SELECT actor_name FROM _cf_METADATA WHERE scope = ?\", [scope])\n .rows[0];\n if (r?.[0] != null)\n (state as { id: DurableObjectId }).id = new DurableObjectIdClass(\n state.id.toString(),\n String(r[0]),\n );\n } catch {\n // no _cf_METADATA yet\n }\n }\n\n #rescope(scope: string): void {\n for (const table of [\"_cf_KV\", \"_cf_ALARM\", \"_cf_METADATA\"])\n try {\n this.#driver.exec(`UPDATE ${table} SET scope = ? WHERE scope <> ?`, [scope, scope]);\n } catch {\n // table not created yet\n }\n }\n\n // ---- hibernation ---------------------------------------------------------------------\n #active = 0;\n #hibernated = false;\n #pinned = 0;\n /** Time of the last event's completion (the runtime's idle sweep reads it). */\n lastActive = Date.now();\n\n get hibernated(): boolean {\n return this.#hibernated;\n }\n\n /**\n * A 101 response whose server end was accepted with `accept()` (not acceptWebSocket)\n * holds a standard WebSocket: the object cannot hibernate until that socket closes —\n * as on Cloudflare, only the hibernation API lets an object sleep with open sockets.\n */\n #pinIfStandardWebSocket(r: unknown): void {\n const server = (\n r as { webSocket?: { peer?: { accepted: boolean; hibernatable: boolean } & EventTarget } }\n )?.webSocket?.peer;\n if (!server || server.hibernatable || !server.accepted) return;\n this.#pinned++;\n server.addEventListener(\"close\", () => this.#pinned--, { once: true });\n }\n\n /**\n * Drops the instance when nothing runs: no event in flight or queued, no open async\n * transaction, no standard WebSocket. Storage, alarms and hibernatable sockets stay; the\n * next event constructs the class again. Returns whether it hibernated.\n */\n hibernate(): boolean {\n if (\n this.#hibernated ||\n this.broken ||\n this.#active ||\n this.#queue.length ||\n this.#sql.held ||\n this.#pinned\n )\n return false;\n if (!this.#gate.isOpen) return false;\n this.#sql.commit();\n this.#instance = undefined;\n this.#hibernated = true;\n return true;\n }\n #dbClosed = false;\n /**\n * Closes the database of a hibernated cell (the cell lease stays); the next event reopens it.\n * A cell with changes its backup has not taken yet stays open. Returns whether it closed.\n */\n closeDatabase(): boolean {\n if (!this.#hibernated || this.#dbClosed || this.#queue.length || !this.#gate.isOpen)\n return false;\n if (this.#backup && (this.#saving || this.#seq !== this.#backedUpSeq)) return false;\n this.#db.close();\n this.#dbClosed = true;\n return true;\n }\n /** Replaces the instance with a fresh one on the SAME database (facet abort/delete). */\n restart(): void {\n if (this.#dbClosed) return; // the next event reopens it with a fresh instance\n this.#construct?.();\n }\n}\n\n/**\n * `ctx.facets` (celld docs/services/durable-object-facets.md): named child objects with a\n * SQLite database of their own (`<cellKey>/facets/<name>`), started on first call from a\n * class (or class handle) returned by the callback; the name alone selects the database.\n */\ninterface FacetTarget {\n call(method: string, args: unknown[]): Promise<unknown>;\n fetch(req: Request): Promise<Response>;\n restart(): void | Promise<void>;\n delete(): Promise<void>;\n}\n\nfunction createFacets(\n parent: { id: DurableObjectId; env: unknown; cellKey: string; epoch?: () => number | undefined },\n spawn: (\n name: string,\n cls: DurableObjectClass,\n env: unknown,\n id: DurableObjectId,\n props?: unknown,\n ) => ObjectHost,\n) {\n const running = new Map<string, Promise<FacetTarget>>();\n // abort() stops the stubs handed out so far (their calls throw the reason); a later\n // get() starts the facet again on the same database — as celld does.\n const generation = new Map<string, { n: number; reason?: unknown }>();\n const local = (h: ObjectHost): FacetTarget => ({\n call: (method, args) =>\n h.deliver((obj) => {\n const fn = obj[method];\n if (typeof fn !== \"function\") throw new TypeError(`${method} is not a function`);\n return fn.apply(obj, args);\n }),\n fetch: (req) => h.deliver((obj) => obj.fetch(closingWith(req, h.closing))),\n restart: () => h.restart(),\n delete: async () => {\n await h.deliver((_o, state) => state.storage.deleteAll());\n h.restart();\n },\n });\n /** A class of isolated loaded code: the facet's instance and SQLite live in the isolate. */\n const isolated = (iso: IsolatedClass, cellKey: string, idName?: string): FacetTarget => {\n const attached = iso.attach?.(cellKey, parent.epoch?.(), idName);\n const ready = async () => attached;\n return {\n call: async (method, args) => (await ready(), iso.call(cellKey, method, args)),\n fetch: async (req) => (await ready(), iso.fetch(cellKey, req)),\n restart: async () => (await ready(), iso.restart(cellKey)),\n delete: async () => (await ready(), iso.delete(cellKey)),\n };\n };\n\n const targetOf = (name: string, start?: () => unknown): Promise<FacetTarget> => {\n let p = running.get(name);\n if (!p) {\n if (!start) return Promise.reject(new Error(`Facet \"${name}\" is not running`));\n p = (async () => {\n const info = (await start()) as { class: unknown; id?: unknown };\n let cls: DurableObjectClass;\n let env = parent.env;\n let props: unknown;\n if (isClassHandle(info.class)) {\n const r = await info.class.resolve();\n if (\"isolated\" in r)\n return isolated(\n r.isolated,\n `${parent.cellKey}/facets/${facetSegment(name)}`,\n // The facet's own `ctx.id` (partyserver's `this.name` reads its name).\n info.id instanceof DurableObjectIdClass ? info.id.name : undefined,\n );\n ({ cls, env, props } = r);\n } else cls = info.class as DurableObjectClass;\n const id = info.id instanceof DurableObjectIdClass ? info.id : parent.id;\n return local(spawn(name, cls, env, id, props));\n })();\n p.catch(() => running.delete(name));\n running.set(name, p);\n }\n return p;\n };\n return {\n get(name: string, start: () => unknown) {\n if (new TextEncoder().encode(name).byteLength > 256)\n throw new Error(\"A facet name has a limit of 256 bytes\");\n const gen = generation.get(name)?.n ?? 0;\n const live = () => {\n const g = generation.get(name);\n if (g && g.n !== gen) throw g.reason;\n };\n return asyncStub(\n async (method, args) => (live(), await targetOf(name, start)).call(method, args),\n async (req) => (live(), await targetOf(name, start)).fetch(req),\n );\n },\n abort(name: string, reason?: unknown) {\n const n = (generation.get(name)?.n ?? 0) + 1;\n generation.set(name, { n, reason: reason ?? new Error(`Facet \"${name}\" was aborted`) });\n // The database stays: the next call on a new stub gets a fresh instance over it.\n void running.get(name)?.then((t) => t.restart());\n },\n async delete(name: string) {\n const p = running.get(name);\n generation.set(name, {\n n: (generation.get(name)?.n ?? 0) + 1,\n reason: new Error(`Facet \"${name}\" was deleted`),\n });\n if (p) await (await p).delete();\n },\n };\n}\n\n/** The cell's lease is held by another owner (route the request there, or retry later). */\nexport class CellOwnedElsewhereError extends Error {\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} is owned by another node`);\n this.name = \"CellOwnedElsewhereError\";\n }\n}\n\n/** celld's path segment for a facet name: the first 16 bytes of SHA-256(name), hex. */\nexport function facetSegment(name: string): string {\n return bytesToHex(sha256(new TextEncoder().encode(name)).subarray(0, 16));\n}\n"]}
@@ -38,6 +38,11 @@ export interface CellRuntimeOptions {
38
38
  wakePollMs?: number;
39
39
  /** Every object of this runtime is a facet of an outer cell (an isolate's runtime). */
40
40
  facets?: boolean;
41
+ /**
42
+ * The `ctx.id` an object sees, when it is not the id that addresses it (a facet given an `id`
43
+ * by `ctx.facets.get`): its storage, cell key and alarms stay the addressing id's.
44
+ */
45
+ ctxIdOf?: (cellKey: string) => DurableObjectId | undefined;
41
46
  /** The Worker script's name (wrangler `name`): object ids derive from it, as on celld. */
42
47
  scriptName?: string;
43
48
  /** Namespace keys overriding the script-scoped default, per class (celld's fleet-wide ones). */
@@ -65,6 +70,11 @@ export interface CellRuntimeOptions {
65
70
  * restores the cell (a log or a backup).
66
71
  */
67
72
  closeDatabaseAfterMs?: number;
73
+ /**
74
+ * On `close()`, how long (ms) events still running and `waitUntil` work may take to finish
75
+ * before the databases close under them (they then fail with ObjectClosedError). Default 2000.
76
+ */
77
+ closeGraceMs?: number;
68
78
  /** SQLite extensions loaded into every cell database (celld's `sqlite_vec` flag). */
69
79
  sqlExtensions?: string[];
70
80
  /** `delete_all_preserves_alarm`: storage.deleteAll() keeps the alarm (default: deletes it). */