| 1 | // The DO object model and the Cloudflare-compatible runtime surface, run |
| 2 | // once per isolate by `js.rs::install_harness` after the Web-API prelude. |
| 3 | // Lived as a 4,000-line raw string inside js.rs until 2026-07-29; it is a |
| 4 | // JavaScript program and belongs in a .js file, like the rest of src/js/. |
| 5 | function __bodyBytes(body) { |
| 6 | if (body == null) return new Uint8Array(); |
| 7 | if (body && body.__celldBodyBytes instanceof Uint8Array) |
| 8 | return body.__celldBodyBytes.slice(); |
| 9 | if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0)); |
| 10 | if (ArrayBuffer.isView(body)) |
| 11 | return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice(); |
| 12 | return new TextEncoder().encode(String(body)); |
| 13 | } |
| 14 | function __chunkBytes(chunk) { |
| 15 | if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk); |
| 16 | if (ArrayBuffer.isView(chunk)) |
| 17 | return new Uint8Array( |
| 18 | chunk.buffer, chunk.byteOffset, chunk.byteLength); |
| 19 | throw new TypeError( |
| 20 | "Iterable bodies must produce ArrayBuffer or " + |
| 21 | "ArrayBufferView chunks"); |
| 22 | } |
| 23 | // Workerd's "gen" bodies: async iterables become a body stream; |
| 24 | // sync iterables of buffers/views concatenate eagerly. Called only |
| 25 | // for object bodies that are not streams or Blobs — an object with |
| 26 | // a custom toString/@@toPrimitive stringifies instead, unless it is |
| 27 | // an array or async-iterable (Workerd's precedence). Returns null |
| 28 | // for the string-coercion path. |
| 29 | function __iterableBody(body) { |
| 30 | if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) |
| 31 | return null; |
| 32 | const asyncIter = body[Symbol.asyncIterator]; |
| 33 | if (typeof asyncIter === "function") { |
| 34 | const iterator = asyncIter.call(body); |
| 35 | return new ReadableStream({ |
| 36 | async pull(controller) { |
| 37 | const result = await iterator.next(); |
| 38 | if (result.done) { controller.close(); return; } |
| 39 | controller.enqueue(__chunkBytes(result.value)); |
| 40 | }, |
| 41 | cancel(reason) { |
| 42 | if (typeof iterator.return === "function") |
| 43 | iterator.return(reason); |
| 44 | }, |
| 45 | }, { highWaterMark: 0 }); |
| 46 | } |
| 47 | if (!Array.isArray(body) && |
| 48 | (body.toString !== Object.prototype.toString || |
| 49 | body[Symbol.toPrimitive] !== undefined)) |
| 50 | return null; |
| 51 | if (typeof body[Symbol.iterator] !== "function") return null; |
| 52 | const chunks = []; |
| 53 | let length = 0; |
| 54 | for (const chunk of body) { |
| 55 | if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk)) |
| 56 | return null; |
| 57 | const view = __chunkBytes(chunk); |
| 58 | chunks.push(view); |
| 59 | length += view.byteLength; |
| 60 | } |
| 61 | const bytes = new Uint8Array(length); |
| 62 | let offset = 0; |
| 63 | for (const view of chunks) { |
| 64 | bytes.set(view, offset); |
| 65 | offset += view.byteLength; |
| 66 | } |
| 67 | return bytes; |
| 68 | } |
| 69 | // Drain a Request/Response body stream, caching the result on the |
| 70 | // instance so later consumers see the materialized bytes. |
| 71 | async function __drainBody(target) { |
| 72 | const chunks = []; |
| 73 | let length = 0; |
| 74 | const reader = target.body.getReader(); |
| 75 | for (;;) { |
| 76 | const result = await reader.read(); |
| 77 | if (result.done) break; |
| 78 | chunks.push(result.value); |
| 79 | length += result.value.byteLength; |
| 80 | } |
| 81 | const bytes = new Uint8Array(length); |
| 82 | let offset = 0; |
| 83 | for (const chunk of chunks) { |
| 84 | bytes.set(chunk, offset); |
| 85 | offset += chunk.byteLength; |
| 86 | } |
| 87 | target._bodyBytes = bytes; |
| 88 | target._body = new TextDecoder().decode(bytes); |
| 89 | return bytes; |
| 90 | } |
| 91 | class CelldBodyStream extends ReadableStream { |
| 92 | constructor(body) { |
| 93 | const bytes = __bodyBytes(body); |
| 94 | const st = { bytes, off: 0 }; |
| 95 | super({ |
| 96 | pull(controller) { |
| 97 | if (st.off >= st.bytes.byteLength) { |
| 98 | controller.close(); |
| 99 | return; |
| 100 | } |
| 101 | const end = Math.min(st.off + 64 * 1024, st.bytes.byteLength); |
| 102 | controller.enqueue(st.bytes.subarray(st.off, end)); |
| 103 | st.off = end; |
| 104 | }, |
| 105 | }, { highWaterMark: 0 }); |
| 106 | this._st = st; |
| 107 | this.__celldBodyBytes = bytes; |
| 108 | // Known length, so re-using this stream as a subrequest body |
| 109 | // still advertises Content-Length. |
| 110 | this._expectedLength = bytes.byteLength; |
| 111 | } |
| 112 | get __celldBodyText() { return new TextDecoder().decode(this.__celldBodyBytes); } |
| 113 | // Workerd body streams are internal streams, so BYOB readers |
| 114 | // work on them. Naming ReadableStreamBYOBReader compiles the |
| 115 | // lazy byte-stream prelude; a worker that never asks for byob |
| 116 | // mode never pays for it. |
| 117 | getReader(options) { |
| 118 | if (options !== undefined && options !== null && |
| 119 | options.mode !== undefined) { |
| 120 | if (String(options.mode) !== "byob") |
| 121 | throw new TypeError(`Invalid reader mode '${options.mode}'`); |
| 122 | if (this._ictl === undefined) |
| 123 | this._ictl = ReadableStreamBYOBReader._buffered(this._st); |
| 124 | return new ReadableStreamBYOBReader(this); |
| 125 | } |
| 126 | return super.getReader(options); |
| 127 | } |
| 128 | // Cancelling a body stream poisons later consumption: text() |
| 129 | // and friends reject, as they would over a real socket. |
| 130 | _cancel(reason) { |
| 131 | this._cancelled = true; |
| 132 | return super._cancel(reason); |
| 133 | } |
| 134 | } |
| 135 | class CelldHttpBodyStream extends ReadableStream { |
| 136 | constructor(streamId) { |
| 137 | const id = Number(streamId); |
| 138 | super({ |
| 139 | async pull(controller) { |
| 140 | const chunk = JSON.parse(await __http_stream_read(id)); |
| 141 | if (chunk.done) controller.close(); |
| 142 | else controller.enqueue(Uint8Array.from(chunk.bytes || [])); |
| 143 | }, |
| 144 | cancel() { __http_stream_cancel(id); }, |
| 145 | }, { highWaterMark: 0 }); |
| 146 | this.__celldStreamId = id; |
| 147 | } |
| 148 | tee() { |
| 149 | if (this.locked) throw new TypeError("ReadableStream is locked"); |
| 150 | this._locked = true; |
| 151 | this._disturbed = true; |
| 152 | const [left, right] = JSON.parse( |
| 153 | __http_stream_tee(this.__celldStreamId), |
| 154 | ); |
| 155 | return [ |
| 156 | new CelldHttpBodyStream(left), |
| 157 | new CelldHttpBodyStream(right), |
| 158 | ]; |
| 159 | } |
| 160 | } |
| 161 | globalThis.Response = class Response { |
| 162 | constructor(body, init = {}) { |
| 163 | // Streaming/iterable detection runs only for object bodies, so |
| 164 | // the common string path skips every instanceof below. |
| 165 | let stream = null; |
| 166 | let blob = null; |
| 167 | if (body !== null && typeof body === "object") { |
| 168 | if (body instanceof ReadableStream) stream = body; |
| 169 | else if (globalThis.Blob && body instanceof Blob) blob = body; |
| 170 | else { |
| 171 | const iterable = __iterableBody(body); |
| 172 | if (iterable instanceof ReadableStream) stream = iterable; |
| 173 | else if (iterable !== null) body = iterable; |
| 174 | } |
| 175 | } |
| 176 | this._bodyBytes = stream !== null |
| 177 | ? null |
| 178 | : blob ? blob._bytes.slice() : __bodyBytes(body); |
| 179 | this._body = stream !== null |
| 180 | ? null |
| 181 | : new TextDecoder().decode(this._bodyBytes); |
| 182 | // Hono rebuilds a response after middleware with |
| 183 | // `new Response(response.body, response)`; the held stream (or a |
| 184 | // fresh CelldBodyStream) preserves the payload across that |
| 185 | // standard clone shape. |
| 186 | this.body = body == null |
| 187 | ? null |
| 188 | : stream !== null |
| 189 | ? stream |
| 190 | : new CelldBodyStream(this._bodyBytes); |
| 191 | this.status = init.status === undefined ? 200 : Number(init.status); |
| 192 | this.statusText = init.statusText === undefined ? "" : String(init.statusText); |
| 193 | this.headers = new Headers(init.headers); |
| 194 | if (blob && blob.type && !this.headers.has("content-type")) |
| 195 | this.headers.set("content-type", blob.type); |
| 196 | this.webSocket = init.webSocket; |
| 197 | this._wsTarget = init.__wsTarget || init._wsTarget || null; |
| 198 | this.ok = this.status >= 200 && this.status <= 299; |
| 199 | this.redirected = false; |
| 200 | this.type = "default"; |
| 201 | this.url = ""; |
| 202 | this.bodyUsed = false; |
| 203 | if (init.cf !== undefined) this.cf = init.cf; |
| 204 | } |
| 205 | static json(data, init = {}) { |
| 206 | const headers = new Headers(init.headers || {}); |
| 207 | if (!headers.has("content-type")) |
| 208 | headers.set("content-type", "application/json"); |
| 209 | return new Response(JSON.stringify(data), { ...init, headers }); |
| 210 | } |
| 211 | async _consume() { |
| 212 | if (this._bodyBytes !== null) { |
| 213 | if (this.body !== null && this.body._cancelled) |
| 214 | throw new TypeError( |
| 215 | "Body has already been used. It can only be used once. " + |
| 216 | "Use tee() first if you need to read it multiple times."); |
| 217 | return this._bodyBytes; |
| 218 | } |
| 219 | return __drainBody(this); |
| 220 | } |
| 221 | async text() { |
| 222 | this.bodyUsed = true; |
| 223 | return new TextDecoder().decode(await this._consume()); |
| 224 | } |
| 225 | async json() { return JSON.parse(await this.text()); } |
| 226 | async formData() { |
| 227 | return __parseFormData( |
| 228 | await this.text(), this.headers.get('content-type')); |
| 229 | } |
| 230 | async arrayBuffer() { |
| 231 | this.bodyUsed = true; |
| 232 | return (await this._consume()).slice().buffer; |
| 233 | } |
| 234 | async blob() { |
| 235 | return new Blob([await this.arrayBuffer()], |
| 236 | { type: this.headers.get("content-type") || "" }); |
| 237 | } |
| 238 | clone() { |
| 239 | if (this.bodyUsed) throw new TypeError("Body has already been consumed"); |
| 240 | if (this._bodyBytes === null) |
| 241 | throw new TypeError("Cannot clone a streaming response before consumption"); |
| 242 | return new Response(this._bodyBytes, { |
| 243 | status: this.status, statusText: this.statusText, headers: this.headers, |
| 244 | webSocket: this.webSocket, __wsTarget: this._wsTarget, cf: this.cf, |
| 245 | }); |
| 246 | } |
| 247 | }; |
| 248 | // Hoisted: this would otherwise allocate an array and scan it on |
| 249 | // every Request construction, which is the HTTP hot path. |
| 250 | const __HTTP_METHODS = new Set( |
| 251 | ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]); |
| 252 | globalThis.Request = class Request { |
| 253 | constructor(input, init = {}) { |
| 254 | const prior = input instanceof Request ? input : null; |
| 255 | const suppliedSignal = init.signal !== undefined; |
| 256 | // The cache option needs the cache_option_enabled compat flag, |
| 257 | // which Cells does not implement (Workerd's cache-disabled path). |
| 258 | if (init.cache !== undefined) |
| 259 | throw new Error("The 'cache' field on 'RequestInitializerDict' " + |
| 260 | "is not implemented."); |
| 261 | this.url = prior ? prior.url : String(input); |
| 262 | { |
| 263 | // Workers upper-cases every method (the |
| 264 | // upper_case_all_http_methods flag) but rejects anything outside |
| 265 | // the known set, reporting the original casing. |
| 266 | const raw = String(init.method === undefined |
| 267 | ? (prior ? prior.method : "GET") : init.method); |
| 268 | const upper = raw.toUpperCase(); |
| 269 | if (!__HTTP_METHODS.has(upper)) |
| 270 | throw new TypeError(`Invalid HTTP method string: ${raw}`); |
| 271 | this.method = upper; |
| 272 | } |
| 273 | const hasBody = |
| 274 | Object.prototype.hasOwnProperty.call(init, "body"); |
| 275 | let body = hasBody ? init.body : null; |
| 276 | let stream = null; |
| 277 | let blob = null; |
| 278 | if (hasBody && body !== null && typeof body === "object") { |
| 279 | if (body instanceof ReadableStream) stream = body; |
| 280 | else if (globalThis.Blob && body instanceof Blob) blob = body; |
| 281 | else { |
| 282 | const iterable = __iterableBody(body); |
| 283 | if (iterable instanceof ReadableStream) stream = iterable; |
| 284 | else if (iterable !== null) body = iterable; |
| 285 | } |
| 286 | } |
| 287 | if (!hasBody && prior && prior._bodyBytes === null) { |
| 288 | // Adopt the prior request's stream; per spec the prior body |
| 289 | // is disturbed by the new request. |
| 290 | stream = prior.body; |
| 291 | prior.bodyUsed = true; |
| 292 | } |
| 293 | this._bodyBytes = stream !== null |
| 294 | ? null |
| 295 | : hasBody |
| 296 | ? (blob ? blob._bytes.slice() : __bodyBytes(body)) |
| 297 | : (prior ? prior._bodyBytes.slice() : new Uint8Array()); |
| 298 | this._body = this._bodyBytes === null |
| 299 | ? null |
| 300 | : new TextDecoder().decode(this._bodyBytes); |
| 301 | this.headers = new Headers(init.headers === undefined && prior ? prior.headers : init.headers); |
| 302 | if (blob && blob.type && !this.headers.has("content-type")) |
| 303 | this.headers.set("content-type", blob.type); |
| 304 | this.bodyUsed = false; |
| 305 | this.body = stream !== null |
| 306 | ? stream |
| 307 | : ["GET", "HEAD"].includes(this.method) |
| 308 | ? null : new CelldBodyStream(this._bodyBytes); |
| 309 | this.redirect = init.redirect || (prior ? prior.redirect : "follow"); |
| 310 | const cf = init.cf === undefined |
| 311 | ? (prior ? prior.cf : undefined) : init.cf; |
| 312 | if (cf !== undefined) this.cf = cf; |
| 313 | this.signal = suppliedSignal |
| 314 | ? init.signal |
| 315 | : (prior ? prior.signal : new AbortController().signal); |
| 316 | this._signalForSubrequests = init.__celldIncomingSignal |
| 317 | ? null |
| 318 | : suppliedSignal |
| 319 | ? this.signal |
| 320 | : (prior ? prior._signalForSubrequests : null); |
| 321 | } |
| 322 | async _consume() { |
| 323 | if (this._bodyBytes !== null) return this._bodyBytes; |
| 324 | return __drainBody(this); |
| 325 | } |
| 326 | async text() { |
| 327 | this.bodyUsed = true; |
| 328 | if (this._body !== null) return this._body; |
| 329 | await this._consume(); |
| 330 | return this._body; |
| 331 | } |
| 332 | async json() { return JSON.parse(await this.text()); } |
| 333 | async formData() { |
| 334 | return __parseFormData( |
| 335 | await this.text(), this.headers.get('content-type')); |
| 336 | } |
| 337 | async arrayBuffer() { |
| 338 | this.bodyUsed = true; |
| 339 | return (await this._consume()).slice().buffer; |
| 340 | } |
| 341 | async blob() { |
| 342 | return new Blob([await this.arrayBuffer()], |
| 343 | { type: this.headers.get("content-type") || "" }); |
| 344 | } |
| 345 | clone() { |
| 346 | if (this.bodyUsed) throw new TypeError("Body has already been consumed"); |
| 347 | if (this._bodyBytes === null) { |
| 348 | // Streaming body: tee, keep one branch, clone the other. |
| 349 | const [left, right] = this.body.tee(); |
| 350 | this.body = left; |
| 351 | return new Request(this, { body: right }); |
| 352 | } |
| 353 | return new Request(this); |
| 354 | } |
| 355 | }; |
| 356 | globalThis.__makeRequest = ( |
| 357 | url, method, body, headersJson = "[]", signal = undefined, |
| 358 | incomingSignal = false, |
| 359 | ) => new Request(url, { |
| 360 | method, body, headers: JSON.parse(headersJson), signal, |
| 361 | __celldIncomingSignal: incomingSignal, |
| 362 | }); |
| 363 | const __fmt = (a) => a.map((x) => { |
| 364 | if (typeof x === "string") return x; |
| 365 | if (x instanceof Error) return x.stack || (x.name + ": " + x.message); |
| 366 | try { return JSON.stringify(x); } catch { return String(x); } |
| 367 | }).join(" "); |
| 368 | globalThis.console = { |
| 369 | log: (...a) => __log(__fmt(a)), info: (...a) => __log(__fmt(a)), |
| 370 | error: (...a) => __log("ERROR " + __fmt(a)), warn: (...a) => __log("WARN " + __fmt(a)), |
| 371 | debug() {}, trace() {}, group() {}, groupEnd() {}, table() {}, |
| 372 | }; |
| 373 | |
| 374 | // async-op shims: outbound fetch + timers, driven by the host event loop. |
| 375 | globalThis.fetch = async (input, init) => { |
| 376 | const req = new Request(input, init); |
| 377 | // `fetch(url, { headers: { Upgrade: "websocket" } })` is the other way |
| 378 | // Cloudflare opens an outbound socket, and the one most examples use. |
| 379 | if ((req.headers.get("upgrade") ?? "").toLowerCase() === "websocket") { |
| 380 | return await __fetchWebSocketUpgrade(req); |
| 381 | } |
| 382 | const bytes = ["GET", "HEAD"].includes(req.method) |
| 383 | ? null : await req._consume(); |
| 384 | const body = bytes === null |
| 385 | ? undefined : JSON.stringify(Array.from(bytes)); |
| 386 | const r = JSON.parse(await __op_fetch( |
| 387 | req.method, req.url, body, JSON.stringify(Array.from(req.headers)), req.redirect, |
| 388 | )); |
| 389 | const response = new Response( |
| 390 | new CelldHttpBodyStream(r.streamId), |
| 391 | { status: r.status, headers: r.headers }, |
| 392 | ); |
| 393 | response.url = req.url; |
| 394 | return response; |
| 395 | }; |
| 396 | globalThis.__fetchWebSocketUpgrade = async (req) => { |
| 397 | const scope = __actorEventStack[__actorEventStack.length - 1] || ""; |
| 398 | const id = __ws_alloc(); |
| 399 | const socket = __makeSocket(id); |
| 400 | socket._outbound = true; |
| 401 | socket._polled = !scope; |
| 402 | socket.url = req.url; |
| 403 | socket.readyState = WebSocket.READY_STATE_CONNECTING; |
| 404 | __sockets.set(id, socket); |
| 405 | let raw; |
| 406 | try { |
| 407 | raw = JSON.parse(await __ws_upgrade( |
| 408 | id, |
| 409 | scope, |
| 410 | req.url, |
| 411 | JSON.stringify(Array.from(req.headers)), |
| 412 | )); |
| 413 | } catch (error) { |
| 414 | __sockets.delete(id); |
| 415 | throw error; |
| 416 | } |
| 417 | if (!raw.upgraded) { |
| 418 | // The server answered without upgrading. That is an ordinary response, |
| 419 | // not a connection error, and it is returned unchanged. |
| 420 | __sockets.delete(id); |
| 421 | const response = new Response(new Uint8Array(raw.body), { |
| 422 | status: raw.status, |
| 423 | headers: raw.headers, |
| 424 | }); |
| 425 | response.url = req.url; |
| 426 | return response; |
| 427 | } |
| 428 | socket.protocol = raw.protocol ?? ""; |
| 429 | const response = new Response(null, { status: 101 }); |
| 430 | response.webSocket = socket; |
| 431 | response.url = req.url; |
| 432 | return response; |
| 433 | }; |
| 434 | globalThis.__makeAssetsBinding = (script) => ({ |
| 435 | async fetch(input, init) { |
| 436 | const req = input instanceof Request ? new Request(input, init) : new Request(input, init); |
| 437 | const r = JSON.parse(await __asset_fetch( |
| 438 | script, |
| 439 | req.method, |
| 440 | req.url, |
| 441 | JSON.stringify(Array.from(req.headers)), |
| 442 | )); |
| 443 | const response = new Response( |
| 444 | new CelldHttpBodyStream(r.streamId), |
| 445 | { status: r.status, headers: r.headers }, |
| 446 | ); |
| 447 | response.url = req.url; |
| 448 | return response; |
| 449 | }, |
| 450 | }); |
| 451 | // R2 is deliberately not implemented. The binding exists so a worker |
| 452 | // that declares r2_buckets still loads, but every method fails loudly |
| 453 | // instead of pretending to be a bucket. |
| 454 | globalThis.__makeR2Bucket = (name) => { |
| 455 | const fail = (method) => () => { |
| 456 | throw new Error( |
| 457 | `R2 is not implemented in celld (binding ${name}, ` + |
| 458 | `method ${method})`, |
| 459 | ); |
| 460 | }; |
| 461 | const bucket = {}; |
| 462 | for (const method of ["head", "get", "put", "delete", "list", |
| 463 | "createMultipartUpload", "resumeMultipartUpload"]) { |
| 464 | bucket[method] = fail(method); |
| 465 | } |
| 466 | return bucket; |
| 467 | }; |
| 468 | globalThis.__makeAiBinding = (url) => ({ |
| 469 | async run(model, input) { |
| 470 | const response = await fetch(url, { |
| 471 | method: "POST", |
| 472 | headers: { "content-type": "application/json" }, |
| 473 | body: JSON.stringify({ model, input }), |
| 474 | }); |
| 475 | if (!response.ok) throw new Error(`AI binding returned ${response.status}`); |
| 476 | return response.json(); |
| 477 | }, |
| 478 | }); |
| 479 | const __timers = new Map(); |
| 480 | globalThis.setTimeout = (cb, ms, ...a) => { |
| 481 | const id = __timer_alloc(); |
| 482 | __timers.set(id, true); |
| 483 | __op_timer(id, ms | 0).then(() => { |
| 484 | if (!__timers.delete(id)) return; |
| 485 | cb(...a); |
| 486 | }); |
| 487 | return id; |
| 488 | }; |
| 489 | globalThis.clearTimeout = (id) => { |
| 490 | if (!__timers.delete(id)) return; |
| 491 | __timer_cancel(id); |
| 492 | }; |
| 493 | globalThis.setInterval = () => { |
| 494 | throw new Error("setInterval is not implemented in celld"); |
| 495 | }; |
| 496 | globalThis.clearInterval = () => {}; |
| 497 | |
| 498 | const __sqlCursorFinalizer = typeof FinalizationRegistry === "function" |
| 499 | ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId)) |
| 500 | : null; |
| 501 | |
| 502 | // A `SqlStorageCursor` over one exec's result (Cloudflare DO SQL API). |
| 503 | class SqlCursor { |
| 504 | constructor(res) { |
| 505 | if (res.error) throw new Error("SQL error: " + res.error); |
| 506 | this._decode = (value) => value && typeof value === "object" && |
| 507 | Array.isArray(value.__celld_bytes) |
| 508 | ? Uint8Array.from(value.__celld_bytes).buffer |
| 509 | : value; |
| 510 | this.columns = res.columns; |
| 511 | this.rowsWritten = Number(res.rowsWritten || 0); |
| 512 | this.reusedCachedQueryForTest = Boolean(res.reusedCachedQuery); |
| 513 | this._deferredError = null; |
| 514 | if (res.native) { |
| 515 | this._native = true; |
| 516 | this._cursorId = Number(res.cursorId || 0); |
| 517 | this._prefetched = res.row === null |
| 518 | ? null |
| 519 | : res.row.map(this._decode); |
| 520 | this.rowsRead = this._prefetched === null ? 0 : 1; |
| 521 | this._finalizerToken = null; |
| 522 | if (this._cursorId && __sqlCursorFinalizer) { |
| 523 | this._finalizerToken = {}; |
| 524 | __sqlCursorFinalizer.register( |
| 525 | this, this._cursorId, this._finalizerToken, |
| 526 | ); |
| 527 | } |
| 528 | } else { |
| 529 | this._native = false; |
| 530 | this._rows = res.rows.map((row) => row.map(this._decode)); |
| 531 | this._rowCount = this._rows.length; |
| 532 | this._index = 0; |
| 533 | this.rowsRead = Math.min(1, this._rowCount); |
| 534 | } |
| 535 | } |
| 536 | _obj(r) { const o = {}; for (let i = 0; i < this.columns.length; i++) o[this.columns[i]] = r[i]; return o; } |
| 537 | _finishNative() { |
| 538 | if (this._finalizerToken && __sqlCursorFinalizer) |
| 539 | __sqlCursorFinalizer.unregister(this._finalizerToken); |
| 540 | this._finalizerToken = null; |
| 541 | this._cursorId = 0; |
| 542 | } |
| 543 | _advanceNative() { |
| 544 | if (!this._cursorId) { |
| 545 | this._prefetched = null; |
| 546 | return; |
| 547 | } |
| 548 | const result = JSON.parse(__sql_cursor_next(this._cursorId)); |
| 549 | if (result.error) { |
| 550 | this._deferredError = new Error("SQL error: " + result.error); |
| 551 | this._prefetched = null; |
| 552 | this._finishNative(); |
| 553 | return; |
| 554 | } |
| 555 | this.rowsWritten = Number(result.rowsWritten || this.rowsWritten); |
| 556 | if (result.row === null) { |
| 557 | this._prefetched = null; |
| 558 | this._finishNative(); |
| 559 | } else { |
| 560 | this._prefetched = result.row.map(this._decode); |
| 561 | this.rowsRead++; |
| 562 | } |
| 563 | } |
| 564 | _nextRaw() { |
| 565 | if (this._native) { |
| 566 | if (this._deferredError) { |
| 567 | const error = this._deferredError; |
| 568 | this._deferredError = null; |
| 569 | throw error; |
| 570 | } |
| 571 | if (this._prefetched === null) return { done: true }; |
| 572 | const value = this._prefetched; |
| 573 | this._advanceNative(); |
| 574 | return { done: false, value }; |
| 575 | } |
| 576 | if (this._index >= this._rowCount) return { done: true }; |
| 577 | const index = this._index++; |
| 578 | const value = this._rows[index]; |
| 579 | // Release consumed rows even if the cursor itself remains reachable. |
| 580 | this._rows[index] = null; |
| 581 | this.rowsRead = Math.min(this._index + 1, this._rowCount); |
| 582 | return { done: false, value }; |
| 583 | } |
| 584 | toArray() { |
| 585 | const rows = []; |
| 586 | while (true) { |
| 587 | const result = this.next(); |
| 588 | if (result.done) return rows; |
| 589 | rows.push(result.value); |
| 590 | if (__heap_limit_excessively_exceeded()) |
| 591 | throw new Error("result set is too large to fit in memory"); |
| 592 | } |
| 593 | } |
| 594 | one() { |
| 595 | const first = this.next(); |
| 596 | if (first.done) |
| 597 | throw new Error("Expected exactly one result from SQL query, but got no results"); |
| 598 | if (!this.next().done) |
| 599 | throw new Error("Expected exactly one result from SQL query, but got multiple results"); |
| 600 | return first.value; |
| 601 | } |
| 602 | *raw() { |
| 603 | while (true) { |
| 604 | const result = this._nextRaw(); |
| 605 | if (result.done) return; |
| 606 | yield result.value; |
| 607 | } |
| 608 | } |
| 609 | get columnNames() { return this.columns; } |
| 610 | next() { |
| 611 | const result = this._nextRaw(); |
| 612 | return result.done ? result : { done: false, value: this._obj(result.value) }; |
| 613 | } |
| 614 | [Symbol.iterator]() { return this; } |
| 615 | } |
| 616 | class SqlStorage { |
| 617 | constructor(scope) { this._scope = scope; } |
| 618 | prepare(query) { |
| 619 | const storage = this; |
| 620 | const source = String(query); |
| 621 | return (...binds) => storage.exec(source, ...binds); |
| 622 | } |
| 623 | exec(query, ...binds) { |
| 624 | const encode = (value) => { |
| 625 | if (value instanceof ArrayBuffer) |
| 626 | return { __celld_bytes: Array.from(new Uint8Array(value)) }; |
| 627 | if (ArrayBuffer.isView(value)) |
| 628 | return { __celld_bytes: Array.from( |
| 629 | new Uint8Array(value.buffer, value.byteOffset, value.byteLength), |
| 630 | ) }; |
| 631 | return value; |
| 632 | }; |
| 633 | return new SqlCursor(JSON.parse(__sql_cursor_start( |
| 634 | this._scope, query, JSON.stringify(binds.map(encode)), |
| 635 | ))); |
| 636 | } |
| 637 | ingest(input) { |
| 638 | const result = JSON.parse(__sql_ingest(this._scope, String(input))); |
| 639 | if (result.error) throw new Error("SQL error: " + result.error); |
| 640 | return result; |
| 641 | } |
| 642 | get databaseSize() { return __sql_database_size(this._scope); } |
| 643 | setMaxPageCountForTest(pages) { |
| 644 | if (typeof __sql_set_max_page_count_for_test !== "function") |
| 645 | throw new Error("setMaxPageCountForTest is only available in tests"); |
| 646 | __sql_set_max_page_count_for_test(this._scope, Number(pages)); |
| 647 | } |
| 648 | setWriteFaultForTest(enabled) { |
| 649 | if (typeof __sql_set_write_fault_for_test !== "function") |
| 650 | throw new Error("setWriteFaultForTest is only available in tests"); |
| 651 | __sql_set_write_fault_for_test(!!enabled); |
| 652 | } |
| 653 | setCacheSizeForTest(pages) { |
| 654 | if (typeof __sql_set_cache_size_for_test !== "function") |
| 655 | throw new Error("setCacheSizeForTest is only available in tests"); |
| 656 | __sql_set_cache_size_for_test(this._scope, Number(pages)); |
| 657 | } |
| 658 | setInterruptFaultForTest(enabled) { |
| 659 | if (typeof __sql_set_interrupt_fault_for_test !== "function") |
| 660 | throw new Error( |
| 661 | "setInterruptFaultForTest is only available in tests"); |
| 662 | __sql_set_interrupt_fault_for_test(this._scope, !!enabled); |
| 663 | } |
| 664 | registerNomemFunctionForTest() { |
| 665 | if (typeof __sql_register_nomem_function_for_test !== "function") |
| 666 | throw new Error( |
| 667 | "registerNomemFunctionForTest is only available in tests"); |
| 668 | __sql_register_nomem_function_for_test(this._scope); |
| 669 | } |
| 670 | } |
| 671 | function __readStoredValue(scope, key, read) { |
| 672 | try { |
| 673 | return read(); |
| 674 | } catch (error) { |
| 675 | const message = String(error && error.message || error); |
| 676 | if (!message.toLowerCase().includes("deserialize cloned data")) |
| 677 | throw error; |
| 678 | const contextual = new Error( |
| 679 | "actor storage deserialization failed; actorId = " + |
| 680 | scope + "; key = " + key + "; " + message, |
| 681 | ); |
| 682 | contextual.cause = error; |
| 683 | throw contextual; |
| 684 | } |
| 685 | } |
| 686 | class SyncKvListIterator { |
| 687 | constructor(root, generation, cursor) { |
| 688 | this._root = root; |
| 689 | this._generation = generation; |
| 690 | this._cursor = cursor; |
| 691 | } |
| 692 | [Symbol.iterator]() { return this; } |
| 693 | next() { |
| 694 | if (this._generation !== this._root._syncKvListGeneration) { |
| 695 | throw new Error( |
| 696 | "kv.list() iterator was invalidated because a new call to kv.list() was started. " + |
| 697 | "Only one kv.list() iterator can exist at a time.", |
| 698 | ); |
| 699 | } |
| 700 | const value = |
| 701 | __storage_sync_list_next(this._cursor, __storedSentinel); |
| 702 | if (value === null) return { done: true, value: undefined }; |
| 703 | value[1] = __unwrapStored(value[1]); |
| 704 | return { done: false, value }; |
| 705 | } |
| 706 | } |
| 707 | class SyncKvStorage { |
| 708 | constructor(storage) { |
| 709 | this._storage = storage; |
| 710 | this._root = storage._transactionRoot; |
| 711 | } |
| 712 | get(key) { |
| 713 | key = String(key); |
| 714 | return __unwrapStored(__readStoredValue( |
| 715 | this._storage._scope, key, |
| 716 | () => __storage_get(this._storage._scope, key, |
| 717 | __storedSentinel), |
| 718 | )); |
| 719 | } |
| 720 | put(key, value) { |
| 721 | key = String(key); |
| 722 | try { |
| 723 | __storage_put(this._storage._scope, key, value); |
| 724 | } catch (error) { |
| 725 | __storage_put_serialized(this._storage._scope, key, |
| 726 | __storedBytes(value, error)); |
| 727 | } |
| 728 | } |
| 729 | delete(key) { |
| 730 | return __storage_delete(this._storage._scope, String(key)); |
| 731 | } |
| 732 | list(options = {}) { |
| 733 | const generation = ++this._root._syncKvListGeneration; |
| 734 | const cursor = __storage_sync_list_start( |
| 735 | this._storage._scope, JSON.stringify(options), |
| 736 | ); |
| 737 | return new SyncKvListIterator( |
| 738 | this._root, generation, cursor, |
| 739 | ); |
| 740 | } |
| 741 | } |
| 742 | class DurableObjectStorage { |
| 743 | constructor( |
| 744 | scope, |
| 745 | state = null, |
| 746 | transactionRoot = null, |
| 747 | transactionDepth = 0, |
| 748 | transactionControl = null, |
| 749 | ) { |
| 750 | this._scope = scope; |
| 751 | this._state = state; |
| 752 | this.sql = new SqlStorage(scope); |
| 753 | this._transactionRoot = transactionRoot || this; |
| 754 | this._transactionDepth = transactionDepth; |
| 755 | this._transactionControl = transactionControl; |
| 756 | if (!transactionRoot) { |
| 757 | this._transactionSerial = 0; |
| 758 | this._transactionTail = Promise.resolve(); |
| 759 | this._syncKvListGeneration = 0; |
| 760 | } |
| 761 | this._kv = new SyncKvStorage(this); |
| 762 | } |
| 763 | get kv() { return this._kv; } |
| 764 | _flushPendingPuts() { |
| 765 | if (this._state && this._state._aborted) return false; |
| 766 | __storage_flush_pending_puts(this._scope); |
| 767 | return true; |
| 768 | } |
| 769 | async get(k) { |
| 770 | await Promise.resolve(); |
| 771 | if (!this._flushPendingPuts()) return; |
| 772 | const key = Array.isArray(k) ? JSON.stringify(k) : String(k); |
| 773 | return __readStoredValue(this._scope, key, () => { |
| 774 | if (Array.isArray(k)) |
| 775 | return __unwrapStoredMap( |
| 776 | __storage_get_many(this._scope, k, __storedSentinel)); |
| 777 | return __unwrapStored( |
| 778 | __storage_get(this._scope, k, __storedSentinel)); |
| 779 | }); |
| 780 | } |
| 781 | async put(k, val) { |
| 782 | if (typeof k === "string") { |
| 783 | try { |
| 784 | __storage_queue_put(this._scope, k, val); |
| 785 | } catch (error) { |
| 786 | __storage_queue_put_serialized(this._scope, k, |
| 787 | __storedBytes(val, error)); |
| 788 | } |
| 789 | await Promise.resolve(); |
| 790 | this._flushPendingPuts(); |
| 791 | return; |
| 792 | } |
| 793 | const source = k instanceof Map ? Array.from(k) : Object.entries(k); |
| 794 | if (source.length === 0) return; |
| 795 | const entries = |
| 796 | source.map(([key, value]) => [String(key), value]); |
| 797 | try { |
| 798 | __storage_queue_put_many(this._scope, entries); |
| 799 | } catch (error) { |
| 800 | // A batch with a stub entry: encode every entry first (plain |
| 801 | // entries keep their native clone bytes, stub entries take |
| 802 | // the stored-stub envelope), then queue — so a genuinely |
| 803 | // uncloneable entry still queues nothing, like the batch op, |
| 804 | // which serializes fully before queueing. |
| 805 | const encoded = entries.map(([key, value]) => { |
| 806 | try { |
| 807 | return [key, __sc_encode(value)]; |
| 808 | } catch (error_) { |
| 809 | return [key, __storedBytes(value, error_)]; |
| 810 | } |
| 811 | }); |
| 812 | for (const [key, bytes] of encoded) |
| 813 | __storage_queue_put_serialized(this._scope, key, bytes); |
| 814 | } |
| 815 | await Promise.resolve(); |
| 816 | this._flushPendingPuts(); |
| 817 | } |
| 818 | async delete(k) { |
| 819 | await Promise.resolve(); |
| 820 | if (!this._flushPendingPuts()) return; |
| 821 | if (Array.isArray(k)) { |
| 822 | if (k.length === 0) return 0; |
| 823 | return __storage_delete_many(this._scope, k); |
| 824 | } |
| 825 | return __storage_delete(this._scope, k); |
| 826 | } |
| 827 | async list(options = {}) { |
| 828 | await Promise.resolve(); |
| 829 | if (!this._flushPendingPuts()) return new Map(); |
| 830 | return __unwrapStoredMap(__storage_list( |
| 831 | this._scope, JSON.stringify(options), __storedSentinel)); |
| 832 | } |
| 833 | async deleteAll() { |
| 834 | await Promise.resolve(); |
| 835 | if (!this._flushPendingPuts()) return; |
| 836 | __storage_delete_all(this._scope, __cell.deleteAllDeletesAlarm); |
| 837 | } |
| 838 | async sync() { |
| 839 | await Promise.resolve(); |
| 840 | this._flushPendingPuts(); |
| 841 | } |
| 842 | async setAlarm(t) { |
| 843 | await Promise.resolve(); |
| 844 | if (!this._flushPendingPuts()) return; |
| 845 | __alarm_set(this._scope, t instanceof Date ? t.getTime() : Number(t)); |
| 846 | } |
| 847 | async getAlarm() { |
| 848 | await Promise.resolve(); |
| 849 | if (!this._flushPendingPuts()) return null; |
| 850 | const v = __alarm_get(this._scope); |
| 851 | return v === null ? null : v; |
| 852 | } |
| 853 | async deleteAlarm() { |
| 854 | await Promise.resolve(); |
| 855 | if (!this._flushPendingPuts()) return; |
| 856 | __alarm_delete(this._scope); |
| 857 | } |
| 858 | _transactionStart() { |
| 859 | const root = this._transactionRoot; |
| 860 | const savepoint = "cells_tx_" + (++root._transactionSerial); |
| 861 | __storage_transaction_control( |
| 862 | this._scope, "start", this._transactionDepth > 0, savepoint, |
| 863 | ); |
| 864 | return savepoint; |
| 865 | } |
| 866 | _transactionCommit(savepoint) { |
| 867 | __storage_transaction_control( |
| 868 | this._scope, "commit", this._transactionDepth > 0, savepoint, |
| 869 | ); |
| 870 | } |
| 871 | _transactionRollback(savepoint, explicit = false) { |
| 872 | __storage_transaction_control( |
| 873 | this._scope, |
| 874 | explicit ? "rollback_explicit" : "rollback", |
| 875 | this._transactionDepth > 0, |
| 876 | savepoint, |
| 877 | ); |
| 878 | } |
| 879 | _transactionView(transactionControl) { |
| 880 | return new DurableObjectStorage( |
| 881 | this._scope, |
| 882 | this._state, |
| 883 | this._transactionRoot, |
| 884 | this._transactionDepth + 1, |
| 885 | transactionControl, |
| 886 | ); |
| 887 | } |
| 888 | rollback() { |
| 889 | const control = this._transactionControl; |
| 890 | if (!control) |
| 891 | throw new TypeError("rollback() must be called on a transaction"); |
| 892 | if (!control.rolledBack) { |
| 893 | control.rollback(); |
| 894 | control.rolledBack = true; |
| 895 | } |
| 896 | } |
| 897 | transactionSync(f) { |
| 898 | const savepoint = this._transactionStart(); |
| 899 | const control = { |
| 900 | rolledBack: false, |
| 901 | rollback: () => this._transactionRollback(savepoint, true), |
| 902 | }; |
| 903 | try { |
| 904 | const value = f(this._transactionView(control)); |
| 905 | if (!control.rolledBack) this._transactionCommit(savepoint); |
| 906 | return value; |
| 907 | } catch (error) { |
| 908 | if (!control.rolledBack) { |
| 909 | try { this._transactionRollback(savepoint); } catch {} |
| 910 | } |
| 911 | throw error; |
| 912 | } |
| 913 | } |
| 914 | async _runTransaction(f) { |
| 915 | const savepoint = this._transactionStart(); |
| 916 | const control = { |
| 917 | rolledBack: false, |
| 918 | rollback: () => this._transactionRollback(savepoint, true), |
| 919 | }; |
| 920 | try { |
| 921 | const value = await f(this._transactionView(control)); |
| 922 | if (!control.rolledBack) this._transactionCommit(savepoint); |
| 923 | return value; |
| 924 | } catch (error) { |
| 925 | if (!control.rolledBack) { |
| 926 | try { this._transactionRollback(savepoint); } catch {} |
| 927 | } |
| 928 | throw error; |
| 929 | } |
| 930 | } |
| 931 | async transaction(f) { |
| 932 | if (this._transactionDepth > 0) return this._runTransaction(f); |
| 933 | const root = this._transactionRoot; |
| 934 | const previous = root._transactionTail; |
| 935 | let release; |
| 936 | root._transactionTail = new Promise((resolve) => { release = resolve; }); |
| 937 | await previous; |
| 938 | try { |
| 939 | return await this._runTransaction(f); |
| 940 | } finally { |
| 941 | release(); |
| 942 | } |
| 943 | } |
| 944 | } |
| 945 | class DurableObjectId { |
| 946 | constructor(className, value, name = undefined) { |
| 947 | Object.defineProperties(this, { |
| 948 | _className: { value: className }, |
| 949 | _value: { value }, |
| 950 | }); |
| 951 | this.name = name; |
| 952 | this.jurisdiction = undefined; |
| 953 | } |
| 954 | toString() { return this._value; } |
| 955 | equals(other) { |
| 956 | return other instanceof DurableObjectId && other._value === this._value; |
| 957 | } |
| 958 | _scope() { return this._className + ":" + this._value; } |
| 959 | } |
| 960 | globalThis.DurableObjectRoutingError = class DurableObjectRoutingError |
| 961 | extends Error { |
| 962 | constructor(detail = {}) { |
| 963 | super("The Durable Object owner is currently unreachable"); |
| 964 | this.name = "DurableObjectRoutingError"; |
| 965 | this.code = "owner_unreachable"; |
| 966 | this.retryable = true; |
| 967 | if (typeof detail.scope === "string") this.scope = detail.scope; |
| 968 | if (typeof detail.owner === "string") this.owner = detail.owner; |
| 969 | } |
| 970 | }; |
| 971 | const __durableObjectRoutingError = (error) => { |
| 972 | const marker = "__CELLD_DO_ROUTING_ERROR__:"; |
| 973 | const message = String(error && error.message || error); |
| 974 | const offset = message.indexOf(marker); |
| 975 | if (offset < 0) return null; |
| 976 | try { |
| 977 | return new DurableObjectRoutingError( |
| 978 | JSON.parse(message.slice(offset + marker.length)), |
| 979 | ); |
| 980 | } catch { |
| 981 | return new DurableObjectRoutingError(); |
| 982 | } |
| 983 | }; |
| 984 | class DurableObjectState { |
| 985 | constructor(scope) { |
| 986 | this._scope = scope; |
| 987 | this._aborted = false; |
| 988 | this.storage = new DurableObjectStorage(scope, this); |
| 989 | this._gate = Promise.resolve(); |
| 990 | this._blockDepth = 0; |
| 991 | const separator = scope.indexOf(":"); |
| 992 | const className = separator < 0 ? scope : scope.slice(0, separator); |
| 993 | const value = separator < 0 ? scope : scope.slice(separator + 1); |
| 994 | this.id = new DurableObjectId( |
| 995 | className, value, __cell.idNames[scope], |
| 996 | ); |
| 997 | } |
| 998 | // Workerd's DurableObjectState.exports (actor-state.h): the same |
| 999 | // loopback surface as ctx.exports on stateless entrypoints. |
| 1000 | get exports() { return __ctxExports(); } |
| 1001 | blockConcurrencyWhile(f) { |
| 1002 | if (typeof f !== "function") |
| 1003 | throw new TypeError("blockConcurrencyWhile() requires a function"); |
| 1004 | if (this._blockDepth >= 64) |
| 1005 | throw new Error( |
| 1006 | "blockConcurrencyWhile() calls are nested too deeply.", |
| 1007 | ); |
| 1008 | if (this._blockDepth > 0) return this._runConcurrencyBlock(f); |
| 1009 | const next = this._gate.then(() => this._runConcurrencyBlock(f)); |
| 1010 | this._gate = next; |
| 1011 | return next; |
| 1012 | } |
| 1013 | _runConcurrencyBlock(f) { |
| 1014 | this._blockDepth++; |
| 1015 | let result; |
| 1016 | try { |
| 1017 | result = f(); |
| 1018 | } catch (error) { |
| 1019 | this._blockDepth--; |
| 1020 | this._resetAfterConcurrencyFailure(error); |
| 1021 | throw error; |
| 1022 | } |
| 1023 | const timerId = __timer_alloc(); |
| 1024 | let settled = false; |
| 1025 | const timeout = __op_timer( |
| 1026 | timerId, |
| 1027 | 30_000, |
| 1028 | ).then(() => { |
| 1029 | if (!settled) { |
| 1030 | throw new Error( |
| 1031 | "A call to blockConcurrencyWhile() in a Durable Object waited for " + |
| 1032 | "too long. The call was canceled and the Durable Object was reset.", |
| 1033 | ); |
| 1034 | } |
| 1035 | }); |
| 1036 | return Promise.race([Promise.resolve(result), timeout]).then( |
| 1037 | (value) => { |
| 1038 | settled = true; |
| 1039 | __timer_cancel(timerId); |
| 1040 | this._blockDepth--; |
| 1041 | return value; |
| 1042 | }, |
| 1043 | (error) => { |
| 1044 | settled = true; |
| 1045 | __timer_cancel(timerId); |
| 1046 | this._blockDepth--; |
| 1047 | this._resetAfterConcurrencyFailure(error); |
| 1048 | throw error; |
| 1049 | }, |
| 1050 | ); |
| 1051 | } |
| 1052 | _resetAfterConcurrencyFailure(error) { |
| 1053 | this._aborted = true; |
| 1054 | __storage_cancel_pending_puts(this._scope); |
| 1055 | const instance = __cell.instances[this._scope]; |
| 1056 | if (instance && instance.__celldState === this) |
| 1057 | delete __cell.instances[this._scope]; |
| 1058 | // Under a stub-mediated caller (this scope is not the current |
| 1059 | // event) the failure breaks the actor, as Workerd joins it |
| 1060 | // into the on-abort promise; a direct event keeps reset-only |
| 1061 | // semantics — its caller sees the rejection itself. |
| 1062 | if (__actorEventStack[__actorEventStack.length - 1] !== |
| 1063 | this._scope) |
| 1064 | __actorBreak(this._scope, error); |
| 1065 | } |
| 1066 | abort(reason) { |
| 1067 | this._aborted = true; |
| 1068 | __storage_cancel_pending_puts(this._scope); |
| 1069 | const instance = __cell.instances[this._scope]; |
| 1070 | if (instance && instance.__celldState === this) |
| 1071 | delete __cell.instances[this._scope]; |
| 1072 | const message = reason instanceof Error |
| 1073 | ? reason.message |
| 1074 | : String(reason); |
| 1075 | // Direct host-dispatched event on this actor: the uncatchable |
| 1076 | // terminate_execution path. Under a same-isolate stub caller, |
| 1077 | // termination would unwind the caller too, so break in JS. |
| 1078 | if (__actorEventStack[__actorEventStack.length - 1] === |
| 1079 | this._scope) { |
| 1080 | __actor_abort(this._scope, message); |
| 1081 | return; |
| 1082 | } |
| 1083 | __actorBreak(this._scope, |
| 1084 | reason instanceof Error ? reason : new Error(message)); |
| 1085 | } |
| 1086 | _ready() { return this._gate; } |
| 1087 | getWebSockets(tag) { |
| 1088 | return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row)); |
| 1089 | } |
| 1090 | acceptWebSocket(ws, tags = []) { |
| 1091 | ws._target = { id: ws._id, scope: this._scope }; |
| 1092 | if (ws._peer) ws._peer._target = ws._target; |
| 1093 | ws._hibernatable = true; |
| 1094 | if (ws._peer) ws._peer._hibernatable = true; |
| 1095 | ws._tags = Array.from(tags, String); |
| 1096 | __ws_accept(ws._id, this._scope, JSON.stringify(ws._tags)); |
| 1097 | __sockets.set(ws._id, ws); |
| 1098 | } |
| 1099 | _socket(id) { |
| 1100 | return __sockets.get(Number(id)) || |
| 1101 | this.getWebSockets().find((ws) => ws._id === id) || |
| 1102 | __wsStub(id); |
| 1103 | } |
| 1104 | waitUntil(promise) { |
| 1105 | globalThis.__registerWaitUntil(promise); |
| 1106 | } |
| 1107 | } |
| 1108 | function _instance(scope) { |
| 1109 | let inst = __cell.instances[scope]; |
| 1110 | if (!inst) { |
| 1111 | const className = scope.split(":")[0]; |
| 1112 | const cls = __cell.classes[className]; |
| 1113 | if (!cls) throw new Error("no DO class " + className); |
| 1114 | const state = new DurableObjectState(scope); |
| 1115 | inst = new cls(state, __cell.env); |
| 1116 | Object.defineProperty(inst, "__celldState", { value: state }); |
| 1117 | // Workerd worker-rpc.c++ getTargetInfo(): RPC needs `extends |
| 1118 | // DurableObject` unless the js_rpc compat flag is on. Decided |
| 1119 | // once here; dispatch reads a boolean. |
| 1120 | state._rpcOk = __cell.compat.jsRpc || |
| 1121 | __cell.doExports[className] === true; |
| 1122 | __cell.instances[scope] = inst; |
| 1123 | } |
| 1124 | return inst; |
| 1125 | } |
| 1126 | async function _readyInstance(scope) { |
| 1127 | const inst = _instance(scope); |
| 1128 | await inst.__celldState._ready(); |
| 1129 | return inst; |
| 1130 | } |
| 1131 | const __actorEventStack = []; |
| 1132 | const __incomingRequestSignals = new Map(); |
| 1133 | const __abortSignal = (signal, reason) => { |
| 1134 | if (signal.aborted) return; |
| 1135 | signal.aborted = true; |
| 1136 | signal.reason = reason; |
| 1137 | signal.dispatchEvent(new Event("abort")); |
| 1138 | }; |
| 1139 | globalThis.__abortIncomingRequest = (requestId) => { |
| 1140 | const signal = __incomingRequestSignals.get(String(requestId)); |
| 1141 | if (signal && !signal.aborted) { |
| 1142 | __abortSignal(signal, new Error("The client has disconnected")); |
| 1143 | return true; |
| 1144 | } |
| 1145 | return false; |
| 1146 | }; |
| 1147 | globalThis.__registerIncomingRequest = (requestId, request) => { |
| 1148 | __incomingRequestSignals.set(String(requestId), request.signal); |
| 1149 | }; |
| 1150 | globalThis.__finishIncomingRequest = (requestId) => { |
| 1151 | __incomingRequestSignals.delete(String(requestId)); |
| 1152 | }; |
| 1153 | globalThis.__endTerminatedActorEvent = (scope) => { |
| 1154 | for (let index = __actorEventStack.length - 1; index >= 0; index--) { |
| 1155 | if (__actorEventStack[index] === scope) { |
| 1156 | __actorEventStack.splice(index, 1); |
| 1157 | return; |
| 1158 | } |
| 1159 | } |
| 1160 | }; |
| 1161 | // Race a pending dispatch against the caller's abort signal: on abort, |
| 1162 | // run `abandon` (which reaches the target's side) and reject with the |
| 1163 | // caller's reason. The dispatch keeps its settle handlers, so a late |
| 1164 | // settlement after abandonment cannot trip the unhandled-rejection |
| 1165 | // signal. |
| 1166 | const __raceCallerAbort = (dispatch, signal, abandon) => |
| 1167 | new Promise((resolve, reject) => { |
| 1168 | let settled = false; |
| 1169 | const onAbort = () => { |
| 1170 | if (settled) return; |
| 1171 | settled = true; |
| 1172 | abandon(); |
| 1173 | reject(signal.reason); |
| 1174 | }; |
| 1175 | signal.addEventListener("abort", onAbort, { once: true }); |
| 1176 | dispatch.then( |
| 1177 | (value) => { |
| 1178 | if (settled) return; |
| 1179 | settled = true; |
| 1180 | signal.removeEventListener("abort", onAbort); |
| 1181 | resolve(value); |
| 1182 | }, |
| 1183 | (error) => { |
| 1184 | if (settled) return; |
| 1185 | settled = true; |
| 1186 | signal.removeEventListener("abort", onAbort); |
| 1187 | reject(error); |
| 1188 | }, |
| 1189 | ); |
| 1190 | }); |
| 1191 | const __awaitCancellableDoCall = (operation, signal) => { |
| 1192 | if (signal.aborted) { |
| 1193 | __do_call_cancel(operation.__celldCancelId); |
| 1194 | return Promise.reject(signal.reason); |
| 1195 | } |
| 1196 | return __raceCallerAbort(operation, signal, |
| 1197 | () => __do_call_cancel(operation.__celldCancelId)); |
| 1198 | }; |
| 1199 | // Workerd semantics: a Response crossing a service binding is a fresh |
| 1200 | // fetch-shaped Response — immutable headers, default reason phrase, |
| 1201 | // the request URL, and a real body stream — never the callee's own |
| 1202 | // mutable object. |
| 1203 | const __STATUS_TEXT = { |
| 1204 | 100: "Continue", 101: "Switching Protocols", 102: "Processing", |
| 1205 | 103: "Early Hints", 200: "OK", 201: "Created", 202: "Accepted", |
| 1206 | 203: "Non-Authoritative Information", 204: "No Content", |
| 1207 | 205: "Reset Content", 206: "Partial Content", 207: "Multi-Status", |
| 1208 | 208: "Already Reported", 226: "IM Used", 300: "Multiple Choices", |
| 1209 | 301: "Moved Permanently", 302: "Found", 303: "See Other", |
| 1210 | 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", |
| 1211 | 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", |
| 1212 | 402: "Payment Required", 403: "Forbidden", 404: "Not Found", |
| 1213 | 405: "Method Not Allowed", 406: "Not Acceptable", |
| 1214 | 407: "Proxy Authentication Required", 408: "Request Timeout", |
| 1215 | 409: "Conflict", 410: "Gone", 411: "Length Required", |
| 1216 | 412: "Precondition Failed", 413: "Payload Too Large", |
| 1217 | 414: "URI Too Long", 415: "Unsupported Media Type", |
| 1218 | 416: "Range Not Satisfiable", 417: "Expectation Failed", |
| 1219 | 418: "I'm a teapot", 421: "Misdirected Request", |
| 1220 | 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", |
| 1221 | 425: "Too Early", 426: "Upgrade Required", |
| 1222 | 428: "Precondition Required", 429: "Too Many Requests", |
| 1223 | 431: "Request Header Fields Too Large", |
| 1224 | 451: "Unavailable For Legal Reasons", 500: "Internal Server Error", |
| 1225 | 501: "Not Implemented", 502: "Bad Gateway", |
| 1226 | 503: "Service Unavailable", 504: "Gateway Timeout", |
| 1227 | 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", |
| 1228 | 507: "Insufficient Storage", 508: "Loop Detected", |
| 1229 | 510: "Not Extended", 511: "Network Authentication Required", |
| 1230 | }; |
| 1231 | const __wrapServiceResponse = (res, url) => { |
| 1232 | const wrapped = new Response( |
| 1233 | // Buffered bodies re-stream (an empty buffer still yields a |
| 1234 | // stream, as over real HTTP); a streaming body passes through. |
| 1235 | res._bodyBytes !== null ? res._bodyBytes : res.body, |
| 1236 | { |
| 1237 | status: res.status, |
| 1238 | statusText: |
| 1239 | res.statusText || __STATUS_TEXT[res.status] || "", |
| 1240 | headers: res.headers, |
| 1241 | webSocket: res.webSocket, |
| 1242 | __wsTarget: res._wsTarget, |
| 1243 | }, |
| 1244 | ); |
| 1245 | // The constructor copies headers, so mark the copy. |
| 1246 | Object.defineProperty(wrapped.headers, "_immutable", { value: true }); |
| 1247 | wrapped.url = url; |
| 1248 | // An upgraded pair whose both ends live in this isolate: link them |
| 1249 | // directly — the host connection seam only reaches external |
| 1250 | // clients. Frames the handler queued before linking flush first. |
| 1251 | const client = wrapped.webSocket; |
| 1252 | if (wrapped.status === 101 && client && client._peer) { |
| 1253 | const server = client._peer; |
| 1254 | client._loopback = server; |
| 1255 | server._loopback = client; |
| 1256 | for (const frame of server._pending.splice(0)) { |
| 1257 | // "send-binary" joined this queue with outbound sockets; without a case |
| 1258 | // of its own it fell through to the close branch and tore the pair down |
| 1259 | // instead of delivering the frame. |
| 1260 | if (frame[0] === "send") |
| 1261 | queueMicrotask(() => client._dispatchMessage(frame[1])); |
| 1262 | else if (frame[0] === "send-binary") |
| 1263 | queueMicrotask(() => { |
| 1264 | const data = frame[1]; |
| 1265 | client._dispatchMessage( |
| 1266 | data instanceof ArrayBuffer ? data : data.buffer.slice( |
| 1267 | data.byteOffset, |
| 1268 | data.byteOffset + data.byteLength, |
| 1269 | ), |
| 1270 | ); |
| 1271 | }); |
| 1272 | else |
| 1273 | queueMicrotask( |
| 1274 | () => client._dispatchClose(frame[1], frame[2], true)); |
| 1275 | } |
| 1276 | } |
| 1277 | return wrapped; |
| 1278 | }; |
| 1279 | // `[[services]]` binding: a Fetcher pointed at another Worker in this |
| 1280 | // process. No identity to resolve, so it goes straight to __svc_call. |
| 1281 | // Worker Loader (Code Mode): spawn a fresh isolate from supplied code and |
| 1282 | // invoke it. Walking skeleton — only `load(code)` and a default-entrypoint |
| 1283 | // `fetch()` are wired, mirroring the cross-isolate service-binding path below. |
| 1284 | globalThis.__makeLoader = () => { |
| 1285 | // `get(name, …)` is memoized by name to one isolate; `load()` is anonymous. |
| 1286 | // A stub holds a Promise<id> so `getCode` may be async and load lazily. |
| 1287 | const byName = new Map(); |
| 1288 | const makeEntrypoint = (idPromise, entrypoint) => { |
| 1289 | const target = { |
| 1290 | async fetch(input, init) { |
| 1291 | const id = await idPromise; |
| 1292 | const req = new Request(input, init); |
| 1293 | const headers = JSON.stringify(Array.from(req.headers)); |
| 1294 | const body_ = req._bodyBytes === null |
| 1295 | ? await req._consume() : req._bodyBytes; |
| 1296 | const r = JSON.parse( |
| 1297 | await __loader_fetch(id, req.url, req.method, body_, headers)); |
| 1298 | const body = r.streamId !== undefined |
| 1299 | ? new CelldHttpBodyStream(r.streamId) |
| 1300 | : r.body !== undefined ? r.body : Uint8Array.from(r.bodyBytes || []); |
| 1301 | return __wrapServiceResponse( |
| 1302 | new Response(body, { status: r.status, headers: r.headers }), |
| 1303 | req.url); |
| 1304 | }, |
| 1305 | }; |
| 1306 | // Both the default and named entrypoints expose RPC: property access is a |
| 1307 | // callable pipeline node dispatched via __loader_rpc to that entrypoint in |
| 1308 | // the loaded worker (default -> the "default" export, which |
| 1309 | // register_entrypoints registers like any other). fetch stays on the |
| 1310 | // target. Only single-method calls are supported for now. |
| 1311 | const session = { |
| 1312 | get: () => Promise.reject(new Error( |
| 1313 | "Awaitable properties on loaded workers are not supported yet.")), |
| 1314 | call: (path, args) => (async () => { |
| 1315 | if (path.length !== 1) |
| 1316 | throw new Error( |
| 1317 | "Pipelined property paths on loaded workers are not supported " + |
| 1318 | "yet."); |
| 1319 | const id = await idPromise; |
| 1320 | return __rpcDes( |
| 1321 | await __loader_rpc(id, entrypoint, path[0], __rpcOut(args, false))); |
| 1322 | })(), |
| 1323 | }; |
| 1324 | return new Proxy(target, { |
| 1325 | get: (base, prop) => { |
| 1326 | if (prop === "then") return undefined; |
| 1327 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 1328 | if (typeof prop !== "string") return undefined; |
| 1329 | return __makeNode(session, [prop], null); |
| 1330 | }, |
| 1331 | }); |
| 1332 | }; |
| 1333 | // Anonymous load() workers are evicted when their only stub is GC'd: the |
| 1334 | // finalizer drops the worker's isolate so it does not leak. Named get() |
| 1335 | // workers are retained by `byName` (memoized) and so are not registered. |
| 1336 | const finalizer = typeof FinalizationRegistry === "function" |
| 1337 | ? new FinalizationRegistry((id) => __loader_drop(id)) |
| 1338 | : null; |
| 1339 | const makeStub = (idPromise, evictable) => { |
| 1340 | // Explicit disposal evicts the worker deterministically; the finalizer is |
| 1341 | // a GC backstop for anonymous stubs that are dropped without disposing. |
| 1342 | // __loader_drop is idempotent, so the two paths cannot double-free. |
| 1343 | const drop = () => { idPromise.then((id) => __loader_drop(id), () => {}); }; |
| 1344 | const stub = { |
| 1345 | getEntrypoint(name = null, _options = {}) { |
| 1346 | return makeEntrypoint(idPromise, name === null ? "default" : name); |
| 1347 | }, |
| 1348 | dispose: drop, |
| 1349 | }; |
| 1350 | if (typeof Symbol.dispose === "symbol") stub[Symbol.dispose] = drop; |
| 1351 | if (evictable && finalizer) |
| 1352 | idPromise.then((id) => finalizer.register(stub, id), () => {}); |
| 1353 | return stub; |
| 1354 | }; |
| 1355 | // getCode is deferred into a microtask so a throw (or async getCode) |
| 1356 | // surfaces as a rejection when the worker is first used, not at get()/load(). |
| 1357 | const loadFrom = (getCode) => |
| 1358 | Promise.resolve().then(getCode).then((c) => __loader_load(JSON.stringify(c))); |
| 1359 | return { |
| 1360 | load(code) { return makeStub(loadFrom(() => code), true); }, |
| 1361 | get(name, getCode) { |
| 1362 | let idPromise = byName.get(name); |
| 1363 | if (idPromise === undefined) { |
| 1364 | idPromise = loadFrom(getCode); |
| 1365 | byName.set(name, idPromise); |
| 1366 | } |
| 1367 | return makeStub(idPromise, false); |
| 1368 | }, |
| 1369 | }; |
| 1370 | }; |
| 1371 | |
| 1372 | globalThis.__makeServiceBinding = (script, entrypoint = null) => { |
| 1373 | const target = { |
| 1374 | async fetch(input, init) { |
| 1375 | const req = new Request(input, init); |
| 1376 | const signal = req._signalForSubrequests; |
| 1377 | if (signal?.aborted) throw signal.reason; |
| 1378 | // A stream body advertises its length the way the HTTP layer |
| 1379 | // would: known length → Content-Length, unknown → chunked. |
| 1380 | if (req._bodyBytes === null && |
| 1381 | !req.headers.has("content-length") && |
| 1382 | !req.headers.has("transfer-encoding")) { |
| 1383 | const length = req.body._expectedLength; |
| 1384 | if (length === undefined) |
| 1385 | req.headers.set("transfer-encoding", "chunked"); |
| 1386 | else req.headers.set("content-length", String(length)); |
| 1387 | } |
| 1388 | // Fast path: the target is this same script, so its handler lives in |
| 1389 | // this isolate. Skip the op + pool-thread hop and call it directly, |
| 1390 | // inside its own event so the target's waitUntil does not attach to |
| 1391 | // the caller's. Cross-script targets still need their own isolate. |
| 1392 | if (script === __cell.script && entrypoint !== null) { |
| 1393 | // Mirror __dispatchTo: the target sees a fresh incoming signal, |
| 1394 | // aborted with "The client has disconnected" when the caller |
| 1395 | // abandons the call or cancels the response body; the caller's |
| 1396 | // own signal races the dispatch so an abandoned call rejects |
| 1397 | // immediately instead of pinning on a hung target. |
| 1398 | const requestController = new AbortController(); |
| 1399 | const dispatch = __dispatchEntrypointFetch( |
| 1400 | entrypoint, |
| 1401 | new Request(req, { |
| 1402 | signal: requestController.signal, |
| 1403 | __celldIncomingSignal: true, |
| 1404 | })); |
| 1405 | const response = signal |
| 1406 | ? await __raceCallerAbort(dispatch, signal, () => |
| 1407 | requestController.abort( |
| 1408 | new Error("The client has disconnected"))) |
| 1409 | : await dispatch; |
| 1410 | __attachResponseRequestCancellation( |
| 1411 | response, requestController, true); |
| 1412 | return __wrapServiceResponse(response, req.url); |
| 1413 | } |
| 1414 | if (entrypoint !== null) |
| 1415 | throw new Error( |
| 1416 | "Cross-script service bindings with an entrypoint do not " + |
| 1417 | "support fetch() yet; only same-script targets do."); |
| 1418 | if (script === __cell.script && typeof __cell.selfFetch === "function") { |
| 1419 | if (__cell.svcDepth >= 8) |
| 1420 | throw new Error( |
| 1421 | "Service binding recursion limit exceeded (8)"); |
| 1422 | __cell.svcDepth = (__cell.svcDepth || 0) + 1; |
| 1423 | const ctx = __beginEvent(); |
| 1424 | try { |
| 1425 | return __wrapServiceResponse( |
| 1426 | await __ctxRun(undefined, |
| 1427 | () => __cell.selfFetch(req, __cell.env, ctx)), |
| 1428 | req.url); |
| 1429 | } finally { |
| 1430 | __cell.svcDepth--; |
| 1431 | __endEvent(); |
| 1432 | } |
| 1433 | } |
| 1434 | const headers = JSON.stringify(Array.from(req.headers)); |
| 1435 | // Cross-isolate calls carry exact bytes; a stream body is drained |
| 1436 | // (and per spec disturbed) first. |
| 1437 | const body_ = req._bodyBytes === null |
| 1438 | ? await req._consume() : req._bodyBytes; |
| 1439 | const r = JSON.parse(await (signal |
| 1440 | ? __awaitCancellableDoCall( |
| 1441 | __svc_call_cancellable( |
| 1442 | script, req.url, req.method, body_, headers), |
| 1443 | signal) |
| 1444 | : __svc_call( |
| 1445 | script, req.url, req.method, body_, headers))); |
| 1446 | const body = r.streamId !== undefined |
| 1447 | ? new CelldHttpBodyStream(r.streamId) |
| 1448 | : r.body !== undefined |
| 1449 | ? r.body |
| 1450 | : Uint8Array.from(r.bodyBytes || []); |
| 1451 | return __wrapServiceResponse( |
| 1452 | new Response(body, { status: r.status, headers: r.headers }), |
| 1453 | req.url); |
| 1454 | }, |
| 1455 | // Workerd's test-visible Fetcher.scheduled(): invoke the target's |
| 1456 | // scheduled handler and report the outcome. |
| 1457 | async scheduled(options = {}) { |
| 1458 | if (script !== __cell.script || entrypoint !== null || |
| 1459 | typeof __cell.selfScheduled !== "function") |
| 1460 | throw new Error( |
| 1461 | "scheduled() is only implemented for same-script service " + |
| 1462 | "bindings whose target has a scheduled handler"); |
| 1463 | let noRetry = false; |
| 1464 | const ctrl = { |
| 1465 | scheduledTime: options.scheduledTime === undefined |
| 1466 | ? Date.now() : Number(options.scheduledTime), |
| 1467 | cron: options.cron === undefined ? "" : String(options.cron), |
| 1468 | noRetry() { noRetry = true; }, |
| 1469 | }; |
| 1470 | const ctx = __beginEvent(); |
| 1471 | try { |
| 1472 | await __cell.selfScheduled(ctrl, __cell.env, ctx); |
| 1473 | return { outcome: "ok", noRetry }; |
| 1474 | } finally { |
| 1475 | __endEvent(); |
| 1476 | } |
| 1477 | }, |
| 1478 | }; |
| 1479 | if (entrypoint === null) return target; |
| 1480 | // With `entrypoint = "Name"`, any property other than fetch is an |
| 1481 | // awaitable/callable pipeline node rooted at that class: awaiting |
| 1482 | // resolves the property remotely (a property-GET wire op), calling |
| 1483 | // invokes it, and deeper access extends the path, resolved on the |
| 1484 | // receiver side in one op. Same-script dispatch stays in this |
| 1485 | // isolate, so stub-able values may cross. A property path rooted |
| 1486 | // directly at the binding is context-free (ctx null): awaiting it |
| 1487 | // starts a fresh session, as in Workerd. |
| 1488 | const session = |
| 1489 | __entrypointSession(entrypoint, script === __cell.script, script); |
| 1490 | return new Proxy(target, { |
| 1491 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 1492 | get: (base, prop) => { |
| 1493 | if (prop === "then") return undefined; // a stub is not a thenable |
| 1494 | if (Reflect.has(base, prop)) return Reflect.get(base, prop); |
| 1495 | if (typeof prop !== "string") return undefined; |
| 1496 | // Workerd's test hook: the named method as a callable handle, |
| 1497 | // resolved — and refused — on the receiver side. |
| 1498 | if (prop === "getRpcMethodForTestOnly") |
| 1499 | return (name) => __makeNode(session, [String(name)], null); |
| 1500 | return __makeNode(session, [prop], null); |
| 1501 | }}); |
| 1502 | }; |
| 1503 | // RPC marshalling: V8 structured clone (Workerd js-rpc semantics), so |
| 1504 | // undefined, Date, Map, Set, BigInt, typed arrays, and cycles survive. |
| 1505 | // A value V8 cannot clone throws DataCloneError, as in Workerd. |
| 1506 | // |
| 1507 | // The envelope's first byte tags the payload. 0xff (the clone version |
| 1508 | // header) = plain clone, decoded as-is — the common case pays one |
| 1509 | // byte-compare and nothing else. 0x01 = clone of a lifted tree in |
| 1510 | // which RpcTarget instances, functions, and Durable Object stubs were |
| 1511 | // replaced by stub markers; the lift runs only after a plain clone |
| 1512 | // already threw, so plain-data calls never walk. 0x02 = a lifted |
| 1513 | // tree carrying only by-value host types (Blob/File, Headers, |
| 1514 | // Request/Response) and no capabilities — decoded like 0x01, but a |
| 1515 | // reply so tagged does not root its callee context. 0x00 = clone of |
| 1516 | // [error, ownProps] — a callee exception crossing as a real Error. |
| 1517 | const __dataCloneError = (error) => new DOMException( |
| 1518 | String(error && error.message || error), "DataCloneError"); |
| 1519 | const __tagged = (tag, sc) => { |
| 1520 | const out = new Uint8Array(sc.length + 1); |
| 1521 | out[0] = tag; |
| 1522 | out.set(sc, 1); |
| 1523 | return out; |
| 1524 | }; |
| 1525 | // ---- request-context confinement ------------------------------- |
| 1526 | // Workerd ties I/O objects to the IoContext of the event that made |
| 1527 | // them. Cells' equivalent: each dispatched event enters an |
| 1528 | // async-context frame (the same CPED the ALS rides, so it survives |
| 1529 | // awaits) carrying a context id. Stubs remember their owning |
| 1530 | // context and refuse to serialize elsewhere; pipeline nodes refuse |
| 1531 | // foreign awaits and calls — each with Workerd's exact error. |
| 1532 | let __nextCtxId = 1; |
| 1533 | const __ctxKey = Symbol("celld.ctx"); |
| 1534 | const __ctxNow = () => { |
| 1535 | const frame = __als_get(); |
| 1536 | return frame === undefined ? undefined : frame.get(__ctxKey); |
| 1537 | }; |
| 1538 | // Run `fn` under context `id` (undefined = a fresh one). An async |
| 1539 | // fn started inside keeps the frame across its awaits. The prior |
| 1540 | // frame is cloned so user AsyncLocalStorage stores still flow into |
| 1541 | // same-isolate callees, as they did before contexts existed. |
| 1542 | const __ctxRun = (id, fn) => { |
| 1543 | const prior = __als_get(); |
| 1544 | const frame = new Map(prior); |
| 1545 | frame.set(__ctxKey, id ?? __nextCtxId++); |
| 1546 | __als_set(frame); |
| 1547 | try { |
| 1548 | return fn(); |
| 1549 | } finally { |
| 1550 | __als_set(prior); |
| 1551 | } |
| 1552 | }; |
| 1553 | const __ctxError = (kind) => new Error( |
| 1554 | "Cannot perform I/O on behalf of a different request. I/O " + |
| 1555 | "objects (such as streams, request/response bodies, and others) " + |
| 1556 | "created in the context of one request handler cannot be " + |
| 1557 | "accessed from a different request's handler. This is a " + |
| 1558 | "limitation of Cloudflare Workers which allows us to improve " + |
| 1559 | "overall performance. (I/O type: " + kind + ")"); |
| 1560 | // ---- abortable request contexts -------------------------------- |
| 1561 | // Workerd's ctx.abort(reason) on an entrypoint aborts the request's |
| 1562 | // IoContext: the in-flight call rejects with the reason, and stubs |
| 1563 | // the context holds are disposed (their disposal callbacks fire). |
| 1564 | // State is allocated only when a context first holds a stub handle |
| 1565 | // or aborts, so plain-data dispatch pays nothing; call paths gate |
| 1566 | // every abort lookup on `__abortedCtxs.size` (one field read). |
| 1567 | // Aborted ids stay recorded: a stub rooted in a dead context must |
| 1568 | // keep rejecting with the reason. |
| 1569 | const __abortedCtxs = new Map(); |
| 1570 | // An actor-flavored abort reason: in-flight ops reject with the |
| 1571 | // wrapped reason, later ops with Workerd's post-abort message |
| 1572 | // (upstream TODO(bug): should propagate the reason, but doesn't). |
| 1573 | class __ActorAbort { constructor(reason) { this.reason = reason; } } |
| 1574 | const __postAbortError = (aborted) => aborted instanceof __ActorAbort |
| 1575 | ? new Error("The execution context which hosts this callback " + |
| 1576 | "is no longer running.") |
| 1577 | : aborted; |
| 1578 | // ctx id -> Set of live stub handles (metas) the context holds. |
| 1579 | const __ctxStubs = new Map(); |
| 1580 | // ctx id -> Set of reject callbacks for stub ops in flight against |
| 1581 | // that context. A hung callee never settles, so a context abort |
| 1582 | // must reject its pending callers directly. |
| 1583 | const __ctxPendingOps = new Map(); |
| 1584 | const __opTrack = (ctx, reject) => { |
| 1585 | let set = __ctxPendingOps.get(ctx); |
| 1586 | if (set === undefined) __ctxPendingOps.set(ctx, set = new Set()); |
| 1587 | set.add(reject); |
| 1588 | return () => { |
| 1589 | set.delete(reject); |
| 1590 | if (set.size === 0) __ctxPendingOps.delete(ctx); |
| 1591 | }; |
| 1592 | }; |
| 1593 | const __ctxRegister = (meta) => { |
| 1594 | if (meta.ctx === undefined) return; |
| 1595 | let set = __ctxStubs.get(meta.ctx); |
| 1596 | if (set === undefined) __ctxStubs.set(meta.ctx, set = new Set()); |
| 1597 | set.add(meta); |
| 1598 | }; |
| 1599 | const __ctxUnregister = (meta) => { |
| 1600 | const set = __ctxStubs.get(meta.ctx); |
| 1601 | if (set === undefined) return; |
| 1602 | set.delete(meta); |
| 1603 | if (set.size === 0) __ctxStubs.delete(meta.ctx); |
| 1604 | }; |
| 1605 | // Tear down a context: dispose every handle it still holds, so a |
| 1606 | // dup() leaked into it reaches the sender's disposal callback. |
| 1607 | const __ctxEnd = (id) => { |
| 1608 | const set = __ctxStubs.get(id); |
| 1609 | if (set === undefined) return; |
| 1610 | __ctxStubs.delete(id); |
| 1611 | for (const meta of set) __disposeStub(meta); |
| 1612 | }; |
| 1613 | const __ctxAbort = (id, reason) => { |
| 1614 | if (id === undefined || __abortedCtxs.has(id)) return; |
| 1615 | const stored = reason === undefined |
| 1616 | ? new Error("The execution context has been aborted.") |
| 1617 | : reason; |
| 1618 | __abortedCtxs.set(id, stored); |
| 1619 | __ctxEnd(id); |
| 1620 | const pending = __ctxPendingOps.get(id); |
| 1621 | if (pending === undefined) return; |
| 1622 | __ctxPendingOps.delete(id); |
| 1623 | const live = |
| 1624 | stored instanceof __ActorAbort ? stored.reason : stored; |
| 1625 | for (const reject of pending) reject(live); |
| 1626 | }; |
| 1627 | // The entrypoint ctx.abort. Instances are cached across calls, so |
| 1628 | // the construction-time ctx cannot pin a request id (Workerd |
| 1629 | // constructs per request); the current frame's id at abort() time |
| 1630 | // is the request being served, which matches Workerd observably. |
| 1631 | const __ctxAbortCurrent = |
| 1632 | (reason) => __ctxAbort(__ctxNow(), reason); |
| 1633 | // ---- same-process RPC stubs ------------------------------------ |
| 1634 | // A stub entry owns a local target; `refs` counts live handles |
| 1635 | // across dup()s. When the last handle is disposed the target's own |
| 1636 | // Symbol.dispose runs (async, matching Workerd's disposal callback). |
| 1637 | // Stubs cross same-isolate transports only (the DO owned fast path |
| 1638 | // and same-script entrypoint RPC); a marker revived elsewhere fails |
| 1639 | // loudly on use instead of aliasing an unrelated local entry. |
| 1640 | // `ctx` records the owning request context: the entry's for |
| 1641 | // running its target, the handle's for the serialize-elsewhere |
| 1642 | // check. |
| 1643 | const __stubEntries = new Map(); |
| 1644 | const __stubMeta = new WeakMap(); |
| 1645 | let __nextStubId = 1; |
| 1646 | const __stubIsolate = Math.random().toString(36).slice(2); |
| 1647 | const __newEntry = (target) => { |
| 1648 | // `scope` records the actor event that minted the entry (top of |
| 1649 | // the event stack at lift time), so an actor breakage can find |
| 1650 | // and abort the contexts hosting its exported stubs. |
| 1651 | const entry = { |
| 1652 | id: __nextStubId++, target, refs: 1, ctx: __ctxNow(), |
| 1653 | scope: __actorEventStack[__actorEventStack.length - 1], |
| 1654 | }; |
| 1655 | __stubEntries.set(entry.id, entry); |
| 1656 | return entry; |
| 1657 | }; |
| 1658 | // Actors broken in JS: scope -> reason. Workerd's DO ctx.abort |
| 1659 | // rejects in-flight and future calls; when the abort fires under a |
| 1660 | // same-isolate stub caller, terminate_execution would unwind that |
| 1661 | // caller too (the routed dispatch re-enters the isolate), so the |
| 1662 | // breakage is recorded here instead: contexts hosting the actor's |
| 1663 | // exported stubs abort (in-flight ops reject with the reason, |
| 1664 | // later ops with the post-abort message) and RPC dispatch to the |
| 1665 | // scope rejects with the reason. Direct host-dispatched DO events |
| 1666 | // keep the uncatchable terminate_execution path. |
| 1667 | const __brokenActors = new Map(); |
| 1668 | const __actorBreak = (scope, reason) => { |
| 1669 | if (__brokenActors.has(scope)) return; |
| 1670 | __brokenActors.set(scope, reason); |
| 1671 | for (const entry of __stubEntries.values()) |
| 1672 | if (entry.scope === scope) |
| 1673 | __ctxAbort(entry.ctx, new __ActorAbort(reason)); |
| 1674 | }; |
| 1675 | const __disposeStub = (meta) => { |
| 1676 | if (meta.disposed) return; |
| 1677 | meta.disposed = true; |
| 1678 | __ctxUnregister(meta); |
| 1679 | const entry = meta.entry; |
| 1680 | if (--entry.refs > 0) return; |
| 1681 | __stubEntries.delete(entry.id); |
| 1682 | const disposer = entry.target?.[Symbol.dispose]; |
| 1683 | if (typeof disposer === "function") |
| 1684 | Promise.resolve().then(() => disposer.call(entry.target)); |
| 1685 | }; |
| 1686 | const __stubDisposedError = () => |
| 1687 | new Error("RPC stub used after being disposed."); |
| 1688 | // Shared brand value for RpcTarget instances; see the RpcTarget |
| 1689 | // constructor. |
| 1690 | const __rpcNoClone = () => {}; |
| 1691 | // Workerd method-visibility rules by target kind: an RpcTarget |
| 1692 | // exposes inherited methods/accessors (never own instance state, |
| 1693 | // never Object.prototype); a plain object or function exposes own |
| 1694 | // properties only. Property reads go through normal [[Get]] so |
| 1695 | // Proxy handlers participate, as in Workerd. |
| 1696 | const __rpcNoSuchMethod = (prop) => new TypeError( |
| 1697 | 'The RPC receiver does not implement the method "' + prop + '".'); |
| 1698 | const __stubResolve = (target, prop) => { |
| 1699 | if (target instanceof __cf.RpcTarget) { |
| 1700 | if (Object.hasOwn(target, prop) || !(prop in target) || |
| 1701 | prop in Object.prototype) throw __rpcNoSuchMethod(prop); |
| 1702 | } else if (!Object.hasOwn(target, prop)) { |
| 1703 | throw __rpcNoSuchMethod(prop); |
| 1704 | } |
| 1705 | const value = target[prop]; |
| 1706 | // Bind plain methods to their receiver, but never touch `.bind` on |
| 1707 | // a stub or pipeline node — property access on those is remote. |
| 1708 | return typeof value === "function" && !__stubMeta.has(value) && |
| 1709 | !(value instanceof __cf.RpcPromise) && |
| 1710 | !(value instanceof __cf.RpcProperty) |
| 1711 | ? value.bind(target) : value; |
| 1712 | }; |
| 1713 | // ---- streams over RPC ------------------------------------------ |
| 1714 | // A live stream crosses as a handle in the caps table: the sender |
| 1715 | // locks the origin (reader/writer acquired at lift) behind a |
| 1716 | // bridge entry, and the receiver's endpoint is an ordinary |
| 1717 | // ReadableStream/WritableStream whose pulls and writes are stub |
| 1718 | // ops against the bridge — one bounded reverse call per chunk, |
| 1719 | // the clone being the one wire copy. Backpressure is the op in |
| 1720 | // flight: hwm 0 pulls only on demand, and the writable carries |
| 1721 | // one chunk per op. EOF, close, and errors cross as op results; |
| 1722 | // teardown (param disposal, context end, context abort) runs the |
| 1723 | // bridge disposer, which cancels or aborts an unfinished origin |
| 1724 | // with Workerd's generic disconnect errors — reasons do not |
| 1725 | // propagate, matching Workerd's own TODOs (and its verbatim |
| 1726 | // "endeded" typo). |
| 1727 | const __wsDisconnect = () => new Error( |
| 1728 | "WritableStream received over RPC was disconnected because " + |
| 1729 | "the remote execution context has endeded."); |
| 1730 | const __rsDisconnect = () => new Error( |
| 1731 | "ReadableStream received over RPC disconnected prematurely."); |
| 1732 | // Receiver wrapper stream -> its handle meta, for forwarding. |
| 1733 | const __rpcStreamMeta = new WeakMap(); |
| 1734 | const __readableBridge = (reader) => { |
| 1735 | const bridge = { |
| 1736 | done: false, |
| 1737 | async read() { |
| 1738 | let result; |
| 1739 | try { |
| 1740 | result = await reader.read(); |
| 1741 | } catch (error) { |
| 1742 | bridge.done = true; |
| 1743 | throw error; |
| 1744 | } |
| 1745 | if (result.done) bridge.done = true; |
| 1746 | return result; |
| 1747 | }, |
| 1748 | cancel() { |
| 1749 | if (bridge.done) return; |
| 1750 | bridge.done = true; |
| 1751 | reader.cancel(__rsDisconnect()).catch(() => {}); |
| 1752 | }, |
| 1753 | [Symbol.dispose]() { bridge.cancel(); }, |
| 1754 | }; |
| 1755 | return bridge; |
| 1756 | }; |
| 1757 | const __writableBridge = (writer) => { |
| 1758 | const bridge = { |
| 1759 | done: false, |
| 1760 | write: (chunk) => writer.write(chunk), |
| 1761 | close() { |
| 1762 | bridge.done = true; |
| 1763 | return writer.close(); |
| 1764 | }, |
| 1765 | abort() { |
| 1766 | bridge.done = true; |
| 1767 | return writer.abort(__wsDisconnect()); |
| 1768 | }, |
| 1769 | [Symbol.dispose]() { |
| 1770 | if (!bridge.done) bridge.abort().catch(() => {}); |
| 1771 | }, |
| 1772 | }; |
| 1773 | return bridge; |
| 1774 | }; |
| 1775 | const __liftStream = (v) => { |
| 1776 | const readable = v instanceof ReadableStream; |
| 1777 | const key = readable ? "__celld$rs" : "__celld$ws"; |
| 1778 | const meta = __rpcStreamMeta.get(v); |
| 1779 | if (meta !== undefined && !meta.disposed && !v.locked) { |
| 1780 | // Re-serializing a received, untouched stream forwards the |
| 1781 | // original handle: the reference moves (like a stub) and |
| 1782 | // the local wrapper is dead — a round trip stays one hop. |
| 1783 | meta.disposed = true; |
| 1784 | __ctxUnregister(meta); |
| 1785 | return { [key]: meta.entry.id, t: __stubIsolate }; |
| 1786 | } |
| 1787 | if (v.locked) |
| 1788 | throw new TypeError(readable |
| 1789 | ? "The ReadableStream has been locked to a reader." |
| 1790 | : "The WritableStream has been locked to a writer."); |
| 1791 | const bridge = readable |
| 1792 | ? __readableBridge(v.getReader()) |
| 1793 | : __writableBridge(v.getWriter()); |
| 1794 | return { [key]: __newEntry(bridge).id, t: __stubIsolate }; |
| 1795 | }; |
| 1796 | // Replace stub-able values with wire markers. Runs only after a |
| 1797 | // plain clone failed, so plain-data serialization never pays for |
| 1798 | // it. Passing an existing stub transfers its reference: the |
| 1799 | // sender's handle is disposed (dup() first to keep one) and the |
| 1800 | // receiver adopts it. Returns null when nothing was liftable. |
| 1801 | const __stubLift = (value) => { |
| 1802 | let lifted = false; |
| 1803 | // Capabilities (stubs, disposers) root the callee context; |
| 1804 | // by-value host types do not — they pick the 0x02 envelope. |
| 1805 | let caps = false; |
| 1806 | const seen = new Map(); |
| 1807 | const ctx = __ctxNow(); |
| 1808 | // A buffered body crosses as its bytes; a live-stream body |
| 1809 | // crosses as a stream handle (a capability, so the reply |
| 1810 | // roots its callee context and the pulls keep working). |
| 1811 | const liftBody = (v) => { |
| 1812 | if (v._bodyBytes !== null) return v._bodyBytes; |
| 1813 | caps = true; |
| 1814 | return __liftStream(v.body); |
| 1815 | }; |
| 1816 | const lift = (v) => { |
| 1817 | if (v === null || |
| 1818 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 1819 | const cached = seen.get(v); |
| 1820 | if (cached !== undefined) return cached; |
| 1821 | const meta = __stubMeta.get(v); |
| 1822 | if (meta) { |
| 1823 | lifted = true; |
| 1824 | caps = true; |
| 1825 | if (meta.disposed) throw __stubDisposedError(); |
| 1826 | // A stub belongs to the request that received it; another |
| 1827 | // request cannot serialize it (Workerd's IoContext rule). |
| 1828 | if (meta.ctx !== ctx) throw __ctxError("Client"); |
| 1829 | meta.disposed = true; // the ref moves to the receiver |
| 1830 | __ctxUnregister(meta); |
| 1831 | const marker = { "__celld$stub": meta.entry.id, |
| 1832 | t: __stubIsolate, c: meta.callable }; |
| 1833 | seen.set(v, marker); |
| 1834 | return marker; |
| 1835 | } |
| 1836 | const svc = __svcMeta.get(v); |
| 1837 | if (svc !== undefined) { |
| 1838 | // A loopback service stub (ctx.exports): name + props cross |
| 1839 | // as plain data and revive as a fresh loopback stub. Props |
| 1840 | // are lifted too — they may nest further stubs (Workerd's |
| 1841 | // nested channel tokens). |
| 1842 | lifted = true; |
| 1843 | caps = true; |
| 1844 | const marker = { "__celld$svc": svc.name, t: __stubIsolate }; |
| 1845 | seen.set(v, marker); |
| 1846 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 1847 | return marker; |
| 1848 | } |
| 1849 | // Workerd refuses to serialize its promise/property handles. |
| 1850 | if (v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty) |
| 1851 | throw new DOMException( |
| 1852 | 'Could not serialize object of type "' + |
| 1853 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 1854 | '". This type does not support serialization.', |
| 1855 | "DataCloneError"); |
| 1856 | if (typeof v === "function" || v instanceof __cf.RpcTarget) { |
| 1857 | lifted = true; |
| 1858 | caps = true; |
| 1859 | const marker = { "__celld$stub": __newEntry(v).id, |
| 1860 | t: __stubIsolate, |
| 1861 | c: typeof v === "function" }; |
| 1862 | seen.set(v, marker); |
| 1863 | return marker; |
| 1864 | } |
| 1865 | const doId = v.__celldDo; |
| 1866 | if (doId !== undefined) { |
| 1867 | lifted = true; |
| 1868 | caps = true; |
| 1869 | const marker = { "__celld$do": doId._className, |
| 1870 | v: doId._value, n: v.name ?? null }; |
| 1871 | seen.set(v, marker); |
| 1872 | return marker; |
| 1873 | } |
| 1874 | // HTTP host types cross by value, as in Workerd's RPC |
| 1875 | // serialization: entry lists for Headers, the buffered bytes |
| 1876 | // for bodies (the marker aliases the live buffer; the clone |
| 1877 | // is the one wire copy), and no signal — the receiver mints |
| 1878 | // a fresh one. A live stream body cannot cross yet. |
| 1879 | let marker; |
| 1880 | if (v instanceof Headers) { |
| 1881 | marker = { "__celld$hdr": [...v] }; |
| 1882 | } else if (v instanceof Blob) { |
| 1883 | marker = { "__celld$blob": v._bytes, y: v.type }; |
| 1884 | if (v instanceof File) { |
| 1885 | marker.n = v.name; |
| 1886 | marker.m = v.lastModified; |
| 1887 | } |
| 1888 | } else if (v instanceof Request) { |
| 1889 | marker = { "__celld$req": v.url, m: v.method, |
| 1890 | h: [...v.headers], r: v.redirect, c: v.cf, |
| 1891 | b: liftBody(v) }; |
| 1892 | } else if (v instanceof Response) { |
| 1893 | marker = { "__celld$res": v.status, |
| 1894 | t: v.statusText || |
| 1895 | __STATUS_TEXT[v.status] || "", |
| 1896 | h: [...v.headers], c: v.cf, |
| 1897 | b: v.body === null ? null : liftBody(v) }; |
| 1898 | } else if (v instanceof ReadableStream || |
| 1899 | v instanceof WritableStream) { |
| 1900 | caps = true; |
| 1901 | marker = __liftStream(v); |
| 1902 | } else if (v instanceof AbortSignal) { |
| 1903 | // A live signal handle: the receiver mints a fresh signal |
| 1904 | // wired to this one (same isolate); foreign bytes revive |
| 1905 | // a snapshot of the aborted flag. |
| 1906 | caps = true; |
| 1907 | marker = { "__celld$sig": __newEntry(v).id, |
| 1908 | t: __stubIsolate, a: v.aborted }; |
| 1909 | } |
| 1910 | if (marker !== undefined) { |
| 1911 | lifted = true; |
| 1912 | seen.set(v, marker); |
| 1913 | return marker; |
| 1914 | } |
| 1915 | const proto = Object.getPrototypeOf(v); |
| 1916 | if (!Array.isArray(v) && |
| 1917 | proto !== Object.prototype && proto !== null) { |
| 1918 | // A Proxy emulating neither a plain object nor an RpcTarget |
| 1919 | // is Workerd's canonical proxy serialization error. |
| 1920 | if (__util_proxy_details(v) !== undefined) |
| 1921 | throw new DOMException( |
| 1922 | "Proxy could not be serialized because it is not a " + |
| 1923 | "valid RPC receiver type. The Proxy must emulate either " + |
| 1924 | "a plain object or an RpcTarget, as indicated by the " + |
| 1925 | "Proxy's prototype chain.", "DataCloneError"); |
| 1926 | return v; // host/other: leave to the clone |
| 1927 | } |
| 1928 | const out = Array.isArray(v) ? [] : {}; |
| 1929 | seen.set(v, out); |
| 1930 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 1931 | const disposer = v[Symbol.dispose]; |
| 1932 | if (!Array.isArray(v) && typeof disposer === "function") { |
| 1933 | lifted = true; |
| 1934 | caps = true; |
| 1935 | out["__celld$disp"] = __newEntry(disposer.bind(v)).id; |
| 1936 | } |
| 1937 | return out; |
| 1938 | }; |
| 1939 | const tree = lift(value); |
| 1940 | return lifted ? { tree, caps } : null; |
| 1941 | }; |
| 1942 | // Revive host-type markers into real instances, adopting the wire |
| 1943 | // bytes directly — no copy beyond the clone's own. |
| 1944 | const __reviveBlob = (marker, bytes) => { |
| 1945 | const blob = marker.n !== undefined |
| 1946 | ? new File([], marker.n, |
| 1947 | { type: marker.y, lastModified: marker.m }) |
| 1948 | : new Blob([], { type: marker.y }); |
| 1949 | blob._bytes = bytes; |
| 1950 | blob.size = bytes.byteLength; |
| 1951 | return blob; |
| 1952 | }; |
| 1953 | const __adoptBody = (target, bytes) => { |
| 1954 | target._bodyBytes = bytes; |
| 1955 | target._body = new TextDecoder().decode(bytes); |
| 1956 | const body = target.body; |
| 1957 | if (body !== null) { |
| 1958 | body._st.bytes = bytes; |
| 1959 | body.__celldBodyBytes = bytes; |
| 1960 | body._expectedLength = bytes.byteLength; |
| 1961 | } |
| 1962 | }; |
| 1963 | // A non-bytes `b` is a live-stream body marker: revive it and |
| 1964 | // let the constructor adopt it as a streaming body. |
| 1965 | const __reviveRequest = (marker, url, revive) => { |
| 1966 | if (!(marker.b instanceof Uint8Array)) |
| 1967 | return new Request(url, { method: marker.m, |
| 1968 | headers: marker.h, redirect: marker.r, cf: marker.c, |
| 1969 | body: revive(marker.b) }); |
| 1970 | const req = new Request(url, { method: marker.m, |
| 1971 | headers: marker.h, redirect: marker.r, cf: marker.c }); |
| 1972 | __adoptBody(req, marker.b); |
| 1973 | return req; |
| 1974 | }; |
| 1975 | const __reviveResponse = (marker, revive) => { |
| 1976 | const bytes = marker.b instanceof Uint8Array; |
| 1977 | const res = new Response( |
| 1978 | marker.b === null ? null : bytes ? "" : revive(marker.b), { |
| 1979 | status: marker["__celld$res"], statusText: marker.t, |
| 1980 | headers: marker.h, cf: marker.c }); |
| 1981 | if (bytes) __adoptBody(res, marker.b); |
| 1982 | return res; |
| 1983 | }; |
| 1984 | // Wire a received stream handle to a local endpoint built with |
| 1985 | // the ordinary constructors — nothing new threads through the |
| 1986 | // stream hot paths. Read errors surface as Workerd's generic |
| 1987 | // premature-disconnect; write errors propagate (Workerd sends |
| 1988 | // real errors back through the write loop). |
| 1989 | const __foreignStreamOp = () => Promise.reject(new Error( |
| 1990 | "RPC streams cannot cross isolate boundaries yet.")); |
| 1991 | const __reviveStream = (marker, id, readable, handles) => { |
| 1992 | const entry = marker.t === __stubIsolate |
| 1993 | ? __stubEntries.get(id) : undefined; |
| 1994 | if (entry === undefined) |
| 1995 | return readable |
| 1996 | ? new ReadableStream({ pull: __foreignStreamOp }) |
| 1997 | : new WritableStream({ write: __foreignStreamOp, |
| 1998 | close: __foreignStreamOp, abort: __foreignStreamOp }); |
| 1999 | const meta = { entry, disposed: false, ctx: __ctxNow() }; |
| 2000 | __ctxRegister(meta); |
| 2001 | handles.push(meta); |
| 2002 | const stream = readable |
| 2003 | ? new ReadableStream({ |
| 2004 | async pull(controller) { |
| 2005 | let result; |
| 2006 | try { |
| 2007 | result = await __stubOp(meta, ["read"], []); |
| 2008 | } catch { |
| 2009 | throw __rsDisconnect(); |
| 2010 | } |
| 2011 | if (result.done) controller.close(); |
| 2012 | else controller.enqueue(result.value); |
| 2013 | }, |
| 2014 | cancel: () => |
| 2015 | __stubOp(meta, ["cancel"], []).catch(() => {}), |
| 2016 | }, { highWaterMark: 0 }) |
| 2017 | : new WritableStream({ |
| 2018 | write: (chunk) => __stubOp(meta, ["write"], [chunk]), |
| 2019 | close: () => __stubOp(meta, ["close"], []), |
| 2020 | abort: () => |
| 2021 | __stubOp(meta, ["abort"], []).catch(() => {}), |
| 2022 | }); |
| 2023 | __rpcStreamMeta.set(stream, meta); |
| 2024 | return stream; |
| 2025 | }; |
| 2026 | const __reviveSignal = (marker, id) => { |
| 2027 | const entry = marker.t === __stubIsolate |
| 2028 | ? __stubEntries.get(id) : undefined; |
| 2029 | const controller = new AbortController(); |
| 2030 | if (entry === undefined) { |
| 2031 | if (marker.a) controller.abort(); |
| 2032 | return controller.signal; |
| 2033 | } |
| 2034 | __stubEntries.delete(id); |
| 2035 | const signal = entry.target; |
| 2036 | if (signal.aborted) controller.abort(signal.reason); |
| 2037 | else signal.addEventListener("abort", |
| 2038 | () => controller.abort(signal.reason), { once: true }); |
| 2039 | return controller.signal; |
| 2040 | }; |
| 2041 | // The inverse: markers become live handles. `handles` collects the |
| 2042 | // revived stubs (for call-end param disposal or result-tree |
| 2043 | // disposal); `disposers` collects remote Symbol.dispose entries. |
| 2044 | const __stubRevive = (value) => { |
| 2045 | const handles = []; |
| 2046 | const disposers = []; |
| 2047 | const seen = new Set(); |
| 2048 | const revive = (v) => { |
| 2049 | if (v === null || typeof v !== "object") return v; |
| 2050 | const stubId = v["__celld$stub"]; |
| 2051 | if (stubId !== undefined) { |
| 2052 | const entry = v.t === __stubIsolate |
| 2053 | ? __stubEntries.get(stubId) : undefined; |
| 2054 | const stub = entry === undefined |
| 2055 | ? __foreignStub() |
| 2056 | : __makeStub(entry, v.c); |
| 2057 | const meta = __stubMeta.get(stub); |
| 2058 | if (meta) handles.push(meta); |
| 2059 | return stub; |
| 2060 | } |
| 2061 | const svcName = v["__celld$svc"]; |
| 2062 | if (svcName !== undefined) |
| 2063 | return v.t === __stubIsolate |
| 2064 | ? __entrypointStub(svcName, revive(v.p)) |
| 2065 | : __foreignStub(); |
| 2066 | const doClass = v["__celld$do"]; |
| 2067 | if (doClass !== undefined) { |
| 2068 | const namespace = __cell.makeNamespace(doClass); |
| 2069 | return namespace.get( |
| 2070 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 2071 | } |
| 2072 | const hdr = v["__celld$hdr"]; |
| 2073 | if (hdr !== undefined) return new Headers(hdr); |
| 2074 | const blobBytes = v["__celld$blob"]; |
| 2075 | if (blobBytes !== undefined) return __reviveBlob(v, blobBytes); |
| 2076 | const reqUrl = v["__celld$req"]; |
| 2077 | if (reqUrl !== undefined) |
| 2078 | return __reviveRequest(v, reqUrl, revive); |
| 2079 | if (v["__celld$res"] !== undefined) |
| 2080 | return __reviveResponse(v, revive); |
| 2081 | const rsId = v["__celld$rs"]; |
| 2082 | if (rsId !== undefined) |
| 2083 | return __reviveStream(v, rsId, true, handles); |
| 2084 | const wsId = v["__celld$ws"]; |
| 2085 | if (wsId !== undefined) |
| 2086 | return __reviveStream(v, wsId, false, handles); |
| 2087 | const sigId = v["__celld$sig"]; |
| 2088 | if (sigId !== undefined) return __reviveSignal(v, sigId); |
| 2089 | if (seen.has(v)) return v; |
| 2090 | seen.add(v); |
| 2091 | if (Array.isArray(v)) { |
| 2092 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 2093 | return v; |
| 2094 | } |
| 2095 | const proto = Object.getPrototypeOf(v); |
| 2096 | if (proto !== Object.prototype && proto !== null) return v; |
| 2097 | for (const key of Object.keys(v)) { |
| 2098 | if (key === "__celld$disp") { |
| 2099 | const entry = __stubEntries.get(v[key]); |
| 2100 | if (entry) disposers.push(entry); |
| 2101 | delete v[key]; |
| 2102 | continue; |
| 2103 | } |
| 2104 | v[key] = revive(v[key]); |
| 2105 | } |
| 2106 | return v; |
| 2107 | }; |
| 2108 | return { value: revive(value), handles, disposers }; |
| 2109 | }; |
| 2110 | // A marker that crossed an isolate boundary: fail on use, loudly. |
| 2111 | const __foreignStub = () => new Proxy(function () {}, { |
| 2112 | get: (_b, prop) => { |
| 2113 | if (prop === "then" || typeof prop !== "string") return undefined; |
| 2114 | return () => Promise.reject(new Error( |
| 2115 | "RPC stubs cannot cross isolate boundaries yet.")); |
| 2116 | }, |
| 2117 | apply: () => Promise.reject(new Error( |
| 2118 | "RPC stubs cannot cross isolate boundaries yet.")), |
| 2119 | }); |
| 2120 | // Workerd's entrypoint method-visibility rules (worker-rpc.c++): |
| 2121 | // reserved lifecycle names are refused outright; only prototype |
| 2122 | // methods and accessors are visible — never own instance state |
| 2123 | // (env/ctx live there) and never Object.prototype. |
| 2124 | const __entrypointReserved = new Set([ |
| 2125 | "constructor", "fetch", "connect", "alarm", "scheduled", |
| 2126 | "webSocketMessage", "webSocketClose", "webSocketError", "dup", |
| 2127 | ]); |
| 2128 | const __entrypointResolve = (inst, prop) => { |
| 2129 | if (__entrypointReserved.has(prop)) |
| 2130 | throw new TypeError("'" + prop + |
| 2131 | "' is a reserved method and cannot be called over RPC."); |
| 2132 | if (Object.hasOwn(inst, prop) || !(prop in inst) || |
| 2133 | prop in Object.prototype) |
| 2134 | throw __rpcNoSuchMethod(prop); |
| 2135 | const value = inst[prop]; |
| 2136 | return typeof value === "function" && !__stubMeta.has(value) && |
| 2137 | !(value instanceof __cf.RpcPromise) && |
| 2138 | !(value instanceof __cf.RpcProperty) |
| 2139 | ? value.bind(inst) : value; |
| 2140 | }; |
| 2141 | // A pipeline hop may continue only through plain data, functions, |
| 2142 | // RpcTargets, and stubs — never through an RPC promise/property |
| 2143 | // handle or a class instance (Workerd's receiver rules). |
| 2144 | const __walkable = (v) => |
| 2145 | v instanceof __cf.RpcPromise || v instanceof __cf.RpcProperty |
| 2146 | ? false |
| 2147 | : typeof v === "function" || v instanceof __cf.RpcTarget || |
| 2148 | (typeof v === "object" && v !== null && |
| 2149 | (Object.getPrototypeOf(v) === Object.prototype || |
| 2150 | Array.isArray(v))); |
| 2151 | // Receiver-side pipeline walk: resolve `path` from `root`, then |
| 2152 | // GET the final member (`args` null) or CALL it. Errors name the |
| 2153 | // path walked so far, as Workerd's do. A stub mid-walk continues |
| 2154 | // against its own target, in the stub's owning context. |
| 2155 | const __rpcWalk = async (root, path, args, entrypointRoot) => { |
| 2156 | let value = root; |
| 2157 | for (let i = 0; i < path.length; i++) { |
| 2158 | const meta = __stubMeta.get(value); |
| 2159 | if (meta) { |
| 2160 | if (meta.disposed) throw __stubDisposedError(); |
| 2161 | const rest = path.slice(i); |
| 2162 | return await __ctxRun(meta.entry.ctx, |
| 2163 | () => __rpcWalk(meta.entry.target, rest, args, false)); |
| 2164 | } |
| 2165 | if (i > 0 && !__walkable(value)) |
| 2166 | throw __rpcNoSuchMethod(path[i - 1]); |
| 2167 | const prop = path[i]; |
| 2168 | const next = entrypointRoot && i === 0 |
| 2169 | ? __entrypointResolve(value, prop) |
| 2170 | : __stubResolve(value, prop); |
| 2171 | if (i === path.length - 1) { |
| 2172 | if (args === null) return next; |
| 2173 | if (typeof next !== "function") |
| 2174 | throw new TypeError( |
| 2175 | '"' + path.join(".") + '" is not a function.'); |
| 2176 | return next(...args); |
| 2177 | } |
| 2178 | if (next instanceof __cf.RpcPromise || |
| 2179 | next instanceof __cf.RpcProperty) |
| 2180 | throw __rpcNoSuchMethod(prop); |
| 2181 | value = next; |
| 2182 | } |
| 2183 | // An empty path applies the root itself (a callable stub). |
| 2184 | if (args === null) return value; |
| 2185 | if (typeof value !== "function") |
| 2186 | throw new TypeError("The RPC stub is not callable."); |
| 2187 | return value(...args); |
| 2188 | }; |
| 2189 | // One stub-mediated op: clone through the RPC envelope both ways, |
| 2190 | // so nested stubs, errors, and uncloneables behave exactly as a |
| 2191 | // dispatched call. Args serialize in the caller's context (its |
| 2192 | // stubs must be its own to transfer); the decode, the walk, and |
| 2193 | // the reply serialization run in the stub's owning context, so |
| 2194 | // stubs minted by the target belong to the target's context. |
| 2195 | // Params received by the target are disposed when the op ends |
| 2196 | // (Workerd's param-disposal rule). |
| 2197 | const __stubOp = (meta, path, args) => { |
| 2198 | if (meta.disposed) return Promise.reject(__stubDisposedError()); |
| 2199 | const entry = meta.entry; |
| 2200 | // A stub rooted in an aborted context is broken: reject with the |
| 2201 | // abort reason, before and after the dispatch (the target may |
| 2202 | // abort its own context mid-call). Gated on one field read. |
| 2203 | if (__abortedCtxs.size !== 0) { |
| 2204 | const aborted = __abortedCtxs.get(entry.ctx); |
| 2205 | if (aborted !== undefined) |
| 2206 | return Promise.reject(__postAbortError(aborted)); |
| 2207 | } |
| 2208 | const argsSc = args === null ? null : __rpcOut(args, true); |
| 2209 | const dispatch = (async () => { |
| 2210 | // Workerd delivers RPC asynchronously: the callee must not run |
| 2211 | // before the caller's synchronous code. A call made just after |
| 2212 | // a not-yet-delivered ctx.abort counts as in flight (rejects |
| 2213 | // with the reason, not the post-abort message). Bodies queue |
| 2214 | // in call order, so e-order holds. |
| 2215 | await null; |
| 2216 | const reply = await __ctxRun(entry.ctx, |
| 2217 | () => __rpcRun(async () => { |
| 2218 | const decoded = |
| 2219 | argsSc === null ? null : __rpcDesArgs(argsSc); |
| 2220 | try { |
| 2221 | return await __rpcWalk(entry.target, path, |
| 2222 | decoded === null ? null : decoded.args, false); |
| 2223 | } finally { |
| 2224 | if (decoded !== null) |
| 2225 | for (const handle of decoded.received) |
| 2226 | __disposeStub(handle); |
| 2227 | } |
| 2228 | }, true)); |
| 2229 | if (__abortedCtxs.size !== 0) { |
| 2230 | const aborted = __abortedCtxs.get(entry.ctx); |
| 2231 | if (aborted !== undefined) |
| 2232 | throw aborted instanceof __ActorAbort |
| 2233 | ? aborted.reason : aborted; |
| 2234 | } |
| 2235 | return __rpcDes(reply); |
| 2236 | })(); |
| 2237 | if (entry.ctx === undefined) return dispatch; |
| 2238 | // Race the op against its hosting context's abort: a hung callee |
| 2239 | // never settles, so the settlement check above cannot reach it. |
| 2240 | // A late settlement lands on an already-settled promise (no-op). |
| 2241 | return new Promise((resolve, reject) => { |
| 2242 | const untrack = __opTrack(entry.ctx, reject); |
| 2243 | dispatch.then( |
| 2244 | (value) => { untrack(); resolve(value); }, |
| 2245 | (error) => { untrack(); reject(error); }); |
| 2246 | }); |
| 2247 | }; |
| 2248 | // Resolve a path against a local, already-revived value. A hop |
| 2249 | // landing on a same-isolate stub delegates the rest of the path |
| 2250 | // to the stub's target; everything else is a plain [[Get]] so |
| 2251 | // Durable Object stubs and Proxies participate. |
| 2252 | const __walkLocal = (parent, path, args) => { |
| 2253 | for (let i = 0; i < path.length; i++) { |
| 2254 | const meta = __stubMeta.get(parent); |
| 2255 | if (meta) return __stubOp(meta, path.slice(i), args); |
| 2256 | const prop = path[i]; |
| 2257 | const member = parent == null ? undefined : parent[prop]; |
| 2258 | if (i < path.length - 1) { |
| 2259 | parent = member; |
| 2260 | continue; |
| 2261 | } |
| 2262 | if (args === null) return member; |
| 2263 | if (typeof member !== "function") { |
| 2264 | if (member === undefined) throw __rpcNoSuchMethod(prop); |
| 2265 | throw new TypeError('"' + prop + '" is not a function.'); |
| 2266 | } |
| 2267 | // [[Call]] directly: `.apply` on a stub proxy would be a |
| 2268 | // remote property access, not an invocation. |
| 2269 | return Reflect.apply(member, parent, args); |
| 2270 | } |
| 2271 | if (args === null) return parent; |
| 2272 | const meta = __stubMeta.get(parent); |
| 2273 | if (meta) return __stubOp(meta, [], args); |
| 2274 | if (typeof parent !== "function") |
| 2275 | throw new TypeError("The RPC value is not callable."); |
| 2276 | return parent(...args); |
| 2277 | }; |
| 2278 | // A session is one place pipeline ops resolve: the local value a |
| 2279 | // call returned, a same-isolate stub's target, or a named |
| 2280 | // entrypoint (whose paths resolve receiver-side in one op). |
| 2281 | const __valueSession = (promise) => ({ |
| 2282 | root: () => promise, |
| 2283 | get: (path) => promise.then((v) => __walkLocal(v, path, null)), |
| 2284 | call: (path, args) => |
| 2285 | promise.then((v) => __walkLocal(v, path, args)), |
| 2286 | }); |
| 2287 | const __stubSession = (meta) => ({ |
| 2288 | get: (path) => __stubOp(meta, path, null), |
| 2289 | call: (path, args) => __stubOp(meta, path, args), |
| 2290 | }); |
| 2291 | const __entrypointSession = (name, local, script, makeInst) => ({ |
| 2292 | get: (path) => local |
| 2293 | ? (async () => __rpcDes( |
| 2294 | await __entrypointOp(name, path, null, true, makeInst)))() |
| 2295 | : Promise.reject(new Error( |
| 2296 | "Awaitable properties on cross-script service bindings " + |
| 2297 | "are not supported yet.")), |
| 2298 | call: (path, args) => (async () => { |
| 2299 | const argsSc = __rpcOut(args, local); |
| 2300 | if (local) |
| 2301 | return __rpcDes(await __entrypointOp( |
| 2302 | name, path, argsSc, true, makeInst)); |
| 2303 | if (path.length !== 1) |
| 2304 | throw new Error( |
| 2305 | "Pipelined property paths on cross-script service " + |
| 2306 | "bindings are not supported yet."); |
| 2307 | return __rpcDes( |
| 2308 | await __svc_rpc(script, name, path[0], argsSc)); |
| 2309 | })(), |
| 2310 | }); |
| 2311 | // Workerd's JsRpcPromise/JsRpcProperty: awaitable, callable, and |
| 2312 | // property access extends a path resolved at the far end, so |
| 2313 | // intermediates obey Workerd's receiver rules. `ctx` is the node's |
| 2314 | // owning request context — null marks a context-free node (a |
| 2315 | // property path rooted directly at a service binding, which |
| 2316 | // starts a fresh session per await); a foreign context awaiting a |
| 2317 | // property or calling through the node gets Workerd's |
| 2318 | // cross-context error. Depth is capped like Workerd's |
| 2319 | // MAX_PROPERTY_DEPTH. |
| 2320 | const __makeNode = (session, path, ctx) => { |
| 2321 | let promise; |
| 2322 | const value = () => promise ??= (() => { |
| 2323 | if (path.length === 0) return session.root(); |
| 2324 | if (ctx !== null && ctx !== __ctxNow()) |
| 2325 | return Promise.reject(__ctxError("Pipeline")); |
| 2326 | return session.get(path); |
| 2327 | })(); |
| 2328 | const brand = |
| 2329 | path.length === 0 ? __cf.RpcPromise : __cf.RpcProperty; |
| 2330 | return new Proxy(function () {}, { |
| 2331 | getPrototypeOf: () => brand.prototype, |
| 2332 | get: (_b, p) => { |
| 2333 | if (p === "then") |
| 2334 | return (onOk, onErr) => value().then(onOk, onErr); |
| 2335 | if (p === "catch") return (onErr) => value().catch(onErr); |
| 2336 | if (p === "finally") |
| 2337 | return (onDone) => value().finally(onDone); |
| 2338 | if (typeof p !== "string") return undefined; |
| 2339 | if (path.length >= 5120) |
| 2340 | throw new TypeError( |
| 2341 | "RPC pipelined property chain is too deep."); |
| 2342 | return __makeNode(session, [...path, p], ctx); |
| 2343 | }, |
| 2344 | apply: (_b, _this, args) => { |
| 2345 | let call; |
| 2346 | if (ctx !== null && ctx !== __ctxNow()) { |
| 2347 | call = Promise.reject(__ctxError("JsRpcPromise")); |
| 2348 | call.catch(() => {}); |
| 2349 | } else { |
| 2350 | // Eager, so concurrent calls keep e-order. |
| 2351 | call = session.call(path, args); |
| 2352 | } |
| 2353 | return __makeNode( |
| 2354 | __valueSession(call), [], ctx ?? __ctxNow()); |
| 2355 | }, |
| 2356 | }); |
| 2357 | }; |
| 2358 | const __makeStub = (entry, callable) => { |
| 2359 | const meta = |
| 2360 | { entry, callable, disposed: false, ctx: __ctxNow() }; |
| 2361 | __ctxRegister(meta); |
| 2362 | const stub = new Proxy(function () {}, { |
| 2363 | getPrototypeOf: () => __cf.RpcStub.prototype, |
| 2364 | get: (_b, prop) => { |
| 2365 | if (prop === "then") return undefined; |
| 2366 | if (prop === Symbol.dispose) return () => __disposeStub(meta); |
| 2367 | if (prop === "dup") return () => { |
| 2368 | if (meta.disposed) throw __stubDisposedError(); |
| 2369 | entry.refs++; |
| 2370 | return __makeStub(entry, callable); |
| 2371 | }; |
| 2372 | if (typeof prop !== "string") return undefined; |
| 2373 | return __makeNode(__stubSession(meta), [prop], __ctxNow()); |
| 2374 | }, |
| 2375 | apply: (_b, _this, args) => __makeNode( |
| 2376 | __valueSession(__stubOp(meta, [], args)), [], __ctxNow()), |
| 2377 | }); |
| 2378 | __stubMeta.set(stub, meta); |
| 2379 | return stub; |
| 2380 | }; |
| 2381 | // A loopback service stub for one of this worker's own |
| 2382 | // entrypoints — the ctx.exports surface. Calling the stub itself |
| 2383 | // returns a new stub carrying per-instance props, delivered to |
| 2384 | // the class constructor as ctx.props (Workerd's |
| 2385 | // ctx.exports.Name({ props })). |
| 2386 | const __svcMeta = new WeakMap(); |
| 2387 | const __entrypointStub = (name, props) => { |
| 2388 | let inst; |
| 2389 | const makeInst = props === undefined ? undefined : () => { |
| 2390 | if (inst !== undefined) return inst; |
| 2391 | const cls = __cell.entrypoints[name]; |
| 2392 | if (typeof cls !== "function") |
| 2393 | throw new TypeError( |
| 2394 | "The entrypoint " + name + " cannot carry props."); |
| 2395 | // Construction gets its own event, like __entrypointInstance. |
| 2396 | const ctx = __beginEvent(props); |
| 2397 | try { |
| 2398 | inst = new cls(ctx, __cell.env); |
| 2399 | } finally { |
| 2400 | __endEvent(); |
| 2401 | } |
| 2402 | return inst; |
| 2403 | }; |
| 2404 | const session = __entrypointSession(name, true, null, makeInst); |
| 2405 | const stub = new Proxy(function () {}, { |
| 2406 | getPrototypeOf: () => __cf.ServiceStub.prototype, |
| 2407 | get: (_b, prop) => { |
| 2408 | if (prop === "then") return undefined; |
| 2409 | if (typeof prop !== "string") return undefined; |
| 2410 | if (prop === "getRpcMethodForTestOnly") |
| 2411 | return (n) => __makeNode(session, [String(n)], null); |
| 2412 | return __makeNode(session, [prop], null); |
| 2413 | }, |
| 2414 | apply: (_b, _this, args) => |
| 2415 | __entrypointStub(name, args[0]?.props), |
| 2416 | }); |
| 2417 | __svcMeta.set(stub, { name, props }); |
| 2418 | return stub; |
| 2419 | }; |
| 2420 | // ---- stored stubs ---------------------------------------------- |
| 2421 | // Durable Object storage accepts only stubs with durable identity: |
| 2422 | // loopback service stubs (entrypoint name + props re-mint a fresh |
| 2423 | // stub on read) and Durable Object stubs (HMAC'd id + class revive |
| 2424 | // in any isolate). A transient handle — a received RPC stub, a |
| 2425 | // function, an RpcTarget — dies with its isolate; persisting its |
| 2426 | // entry id would revive garbage after a restart, so it is refused. |
| 2427 | // A stub-bearing row is written as 0x01 + clone(marker tree), off |
| 2428 | // the plain-clone fast path (the lift runs only after the plain |
| 2429 | // clone already threw, exactly like the RPC envelope). Reads hand |
| 2430 | // tagged rows to JS as [sentinel, tree]; the sentinel never leaves |
| 2431 | // this script and no user value can decode to it, so revival |
| 2432 | // cannot be spoofed by data shaped like a marker. |
| 2433 | const __storedSentinel = {}; |
| 2434 | const __storedLift = (value) => { |
| 2435 | let lifted = false; |
| 2436 | const seen = new Map(); |
| 2437 | const lift = (v) => { |
| 2438 | if (v === null || |
| 2439 | (typeof v !== "object" && typeof v !== "function")) return v; |
| 2440 | const cached = seen.get(v); |
| 2441 | if (cached !== undefined) return cached; |
| 2442 | // Ordering mirrors __stubLift: identify proxies by their |
| 2443 | // side tables and brands before touching any property — a |
| 2444 | // stub or pipeline proxy answers every property read with a |
| 2445 | // fresh RpcProperty node. |
| 2446 | if (__stubMeta.has(v) || v instanceof __cf.RpcTarget) |
| 2447 | throw new DOMException( |
| 2448 | "Durable Object storage can only store stubs with " + |
| 2449 | "durable identity: service stubs from ctx.exports and " + |
| 2450 | "Durable Object stubs. This value is a transient RPC " + |
| 2451 | "handle that would not survive a restart.", |
| 2452 | "DataCloneError"); |
| 2453 | const svc = __svcMeta.get(v); |
| 2454 | if (svc !== undefined) { |
| 2455 | lifted = true; |
| 2456 | const marker = { "__celld$svc": svc.name }; |
| 2457 | seen.set(v, marker); |
| 2458 | if (svc.props !== undefined) marker.p = lift(svc.props); |
| 2459 | return marker; |
| 2460 | } |
| 2461 | if (v instanceof __cf.RpcPromise || |
| 2462 | v instanceof __cf.RpcProperty) |
| 2463 | throw new DOMException( |
| 2464 | 'Could not serialize object of type "' + |
| 2465 | (v instanceof __cf.RpcPromise ? "RpcPromise" : "RpcProperty") + |
| 2466 | '". This type does not support serialization.', |
| 2467 | "DataCloneError"); |
| 2468 | if (typeof v === "function") return v; // leave to the clone |
| 2469 | const doId = v.__celldDo; |
| 2470 | if (doId !== undefined) { |
| 2471 | lifted = true; |
| 2472 | const marker = { "__celld$do": doId._className, |
| 2473 | v: doId._value, n: v.name ?? null }; |
| 2474 | seen.set(v, marker); |
| 2475 | return marker; |
| 2476 | } |
| 2477 | if (Array.isArray(v)) { |
| 2478 | const out = []; |
| 2479 | seen.set(v, out); |
| 2480 | for (let i = 0; i < v.length; i++) out[i] = lift(v[i]); |
| 2481 | return out; |
| 2482 | } |
| 2483 | const proto = Object.getPrototypeOf(v); |
| 2484 | if (proto !== Object.prototype && proto !== null) |
| 2485 | return v; // host/other: leave to the clone |
| 2486 | const out = {}; |
| 2487 | seen.set(v, out); |
| 2488 | for (const key of Object.keys(v)) out[key] = lift(v[key]); |
| 2489 | return out; |
| 2490 | }; |
| 2491 | const tree = lift(value); |
| 2492 | return lifted ? tree : null; |
| 2493 | }; |
| 2494 | // Encode one stub-bearing value for storage. Rethrows the original |
| 2495 | // clone error when nothing was liftable, so plain uncloneables |
| 2496 | // fail exactly as they always did. |
| 2497 | const __storedBytes = (value, error) => { |
| 2498 | const tree = __storedLift(value); |
| 2499 | if (tree === null) throw error; |
| 2500 | return __tagged(1, __sc_encode(tree)); |
| 2501 | }; |
| 2502 | const __storedRevive = (value) => { |
| 2503 | const seen = new Set(); |
| 2504 | const revive = (v) => { |
| 2505 | if (v === null || typeof v !== "object") return v; |
| 2506 | const svcName = v["__celld$svc"]; |
| 2507 | if (svcName !== undefined) |
| 2508 | return __entrypointStub(svcName, revive(v.p)); |
| 2509 | const doClass = v["__celld$do"]; |
| 2510 | if (doClass !== undefined) |
| 2511 | return __cell.makeNamespace(doClass).get( |
| 2512 | new DurableObjectId(doClass, v.v, v.n ?? undefined)); |
| 2513 | if (seen.has(v)) return v; |
| 2514 | seen.add(v); |
| 2515 | if (Array.isArray(v)) { |
| 2516 | for (let i = 0; i < v.length; i++) v[i] = revive(v[i]); |
| 2517 | return v; |
| 2518 | } |
| 2519 | const proto = Object.getPrototypeOf(v); |
| 2520 | if (proto !== Object.prototype && proto !== null) return v; |
| 2521 | for (const key of Object.keys(v)) v[key] = revive(v[key]); |
| 2522 | return v; |
| 2523 | }; |
| 2524 | return revive(value); |
| 2525 | }; |
| 2526 | const __unwrapStored = (v) => |
| 2527 | Array.isArray(v) && v[0] === __storedSentinel |
| 2528 | ? __storedRevive(v[1]) : v; |
| 2529 | // A map result is wrapped as a whole only when it holds at least |
| 2530 | // one tagged row, so the per-entry walk never runs on plain data. |
| 2531 | const __unwrapStoredMap = (v) => { |
| 2532 | if (!Array.isArray(v) || v[0] !== __storedSentinel) return v; |
| 2533 | const map = v[1]; |
| 2534 | for (const [key, value] of map) |
| 2535 | map.set(key, __unwrapStored(value)); |
| 2536 | return map; |
| 2537 | }; |
| 2538 | // ctx.exports: loopback stubs for every exported entrypoint plus |
| 2539 | // this worker's Durable Object namespaces. Built once, on first |
| 2540 | // access — ctx construction itself only carries the getter. |
| 2541 | let __ctxExportsCache; |
| 2542 | const __ctxExports = () => __ctxExportsCache ??= (() => { |
| 2543 | const out = {}; |
| 2544 | for (const name of Object.keys(__cell.entrypoints)) |
| 2545 | out[name] = __entrypointStub(name, undefined); |
| 2546 | for (const name of Object.keys(__cell.objectEntrypoints)) |
| 2547 | if (name !== "default") |
| 2548 | out[name] = __entrypointStub(name, undefined); |
| 2549 | for (const name of Object.keys(__cell.namespaceKeys)) |
| 2550 | out[name] = __cell.makeNamespace(name); |
| 2551 | return out; |
| 2552 | })(); |
| 2553 | // ---- RPC envelope ---------------------------------------------- |
| 2554 | // Serialize one payload. `lift` marks a same-isolate transport, |
| 2555 | // where stub-able values may cross as markers; elsewhere they stay |
| 2556 | // a DataCloneError, exactly as before stubs existed. |
| 2557 | const __rpcOut = (value, lift) => { |
| 2558 | try { |
| 2559 | return __sc_encode(value); |
| 2560 | } catch (error) { |
| 2561 | const lifted = lift ? __stubLift(value) : null; |
| 2562 | if (lifted === null) throw __dataCloneError(error); |
| 2563 | try { |
| 2564 | return __tagged( |
| 2565 | lifted.caps ? 1 : 2, __sc_encode(lifted.tree)); |
| 2566 | } catch (error_) { |
| 2567 | throw __dataCloneError(error_); |
| 2568 | } |
| 2569 | } |
| 2570 | }; |
| 2571 | // A callee exception as tagged bytes: the Error crosses by value |
| 2572 | // (V8 serializes Error natively), custom own properties beside it. |
| 2573 | const __rpcErrOut = (error) => { |
| 2574 | // `name` rides in the props: V8 only round-trips the standard |
| 2575 | // Error subclass names, and e.g. DataCloneError must survive. |
| 2576 | const props = error instanceof Error |
| 2577 | ? { ...error, name: error.name } : {}; |
| 2578 | let sc; |
| 2579 | try { |
| 2580 | sc = __sc_encode([error, props]); |
| 2581 | } catch { |
| 2582 | const error_ = new Error(String(error?.message ?? error)); |
| 2583 | sc = __sc_encode([error_, { name: String(error?.name ?? "Error") }]); |
| 2584 | } |
| 2585 | return __tagged(0, sc); |
| 2586 | }; |
| 2587 | // The callee half of one RPC: run `body`, answer tagged bytes. |
| 2588 | const __rpcRun = async (body, lift) => { |
| 2589 | try { |
| 2590 | return __rpcOut(await body(), lift); |
| 2591 | } catch (error) { |
| 2592 | return __rpcErrOut(error); |
| 2593 | } |
| 2594 | }; |
| 2595 | const __rpcDesArgs = (bytes) => { |
| 2596 | if (bytes[0] === 0xff) |
| 2597 | return { args: __sc_decode(bytes), received: [] }; |
| 2598 | const revived = __stubRevive(__sc_decode(bytes.subarray(1))); |
| 2599 | return { args: revived.value, received: revived.handles }; |
| 2600 | }; |
| 2601 | // The caller half: decode a reply, rebuilding stubs and rethrowing |
| 2602 | // callee exceptions as real Errors with the callee's own |
| 2603 | // properties, `.remote`, and a local (caller-side) stack. |
| 2604 | const __rpcDes = (bytes) => { |
| 2605 | if (bytes[0] === 0xff) return __sc_decode(bytes); |
| 2606 | if (bytes[0] === 1 || bytes[0] === 2) { |
| 2607 | const { value, handles, disposers } = |
| 2608 | __stubRevive(__sc_decode(bytes.subarray(1))); |
| 2609 | if (value !== null && typeof value === "object" && |
| 2610 | !__stubMeta.has(value) && |
| 2611 | (handles.length > 0 || disposers.length > 0)) { |
| 2612 | Object.defineProperty(value, Symbol.dispose, { |
| 2613 | configurable: true, |
| 2614 | value: () => { |
| 2615 | for (const handle of handles) __disposeStub(handle); |
| 2616 | for (const entry of disposers) { |
| 2617 | __stubEntries.delete(entry.id); |
| 2618 | Promise.resolve().then(() => entry.target()); |
| 2619 | } |
| 2620 | }, |
| 2621 | }); |
| 2622 | } |
| 2623 | return value; |
| 2624 | } |
| 2625 | const [error, props] = __sc_decode(bytes.subarray(1)); |
| 2626 | if (error instanceof Error) { |
| 2627 | Object.assign(error, props); |
| 2628 | error.remote = true; |
| 2629 | const local = new Error().stack; |
| 2630 | error.stack = error.name + ": " + error.message + |
| 2631 | local.slice(local.indexOf("\n")); |
| 2632 | } |
| 2633 | throw error; |
| 2634 | }; |
| 2635 | // Deprecated Fetcher `get()`/`put()`/`delete()` HTTP helpers, kept by |
| 2636 | // the fetcher_has_get_put_delete compat flag (Workerd http.c++): |
| 2637 | // shortcuts for fetch() with the corresponding method. |
| 2638 | const __fetcherStatus = (res, method) => { |
| 2639 | if (res.status >= 200 && res.status < 300) return; |
| 2640 | throw new Error("HTTP " + method + " request failed: " + res.status + |
| 2641 | " " + (res.statusText || __STATUS_TEXT[res.status] || "")); |
| 2642 | }; |
| 2643 | const __fetcherHelper = (fetch, prop) => { |
| 2644 | if (prop === "get") return async (url, type) => { |
| 2645 | const res = await fetch(url, { method: "GET" }); |
| 2646 | if (res.status === 404 || res.status === 410) return null; |
| 2647 | __fetcherStatus(res, "GET"); |
| 2648 | if (type === "stream") |
| 2649 | return res.body ?? new ReadableStream({ start(c) { c.close(); } }); |
| 2650 | if (type === "arrayBuffer") return res.arrayBuffer(); |
| 2651 | if (type === "json") return res.json(); |
| 2652 | return res.text(); |
| 2653 | }; |
| 2654 | if (prop === "put") return async (url, body, options) => { |
| 2655 | const { expiration, expirationTtl } = options ?? {}; |
| 2656 | if (expiration !== undefined || expirationTtl !== undefined) { |
| 2657 | const url_ = new URL(url); |
| 2658 | if (expiration !== undefined) |
| 2659 | url_.searchParams.append("expiration", expiration); |
| 2660 | if (expirationTtl !== undefined) |
| 2661 | url_.searchParams.append("expiration_ttl", expirationTtl); |
| 2662 | url = url_.toString(); |
| 2663 | } |
| 2664 | __fetcherStatus(await fetch(url, { method: "PUT", body }), "PUT"); |
| 2665 | }; |
| 2666 | return async (url) => { |
| 2667 | __fetcherStatus(await fetch(url, { method: "DELETE" }), "DELETE"); |
| 2668 | }; |
| 2669 | }; |
| 2670 | function makeNamespace(className) { |
| 2671 | const namespaceKey = __cell.namespaceKeys[className]; |
| 2672 | if (typeof namespaceKey !== "string") |
| 2673 | throw new Error("no Durable Object namespace key for " + className); |
| 2674 | const namespace = { |
| 2675 | idFromName(name) { |
| 2676 | name = String(name); |
| 2677 | return new DurableObjectId( |
| 2678 | className, __do_id(namespaceKey, "name", name), name, |
| 2679 | ); |
| 2680 | }, |
| 2681 | idFromString(value) { |
| 2682 | return new DurableObjectId( |
| 2683 | className, __do_id(namespaceKey, "validate", String(value)), |
| 2684 | ); |
| 2685 | }, |
| 2686 | newUniqueId(options = {}) { |
| 2687 | const jurisdiction = options == null ? undefined : options.jurisdiction; |
| 2688 | if (jurisdiction != null) |
| 2689 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 2690 | return new DurableObjectId( |
| 2691 | className, __do_id(namespaceKey, "unique", ""), |
| 2692 | ); |
| 2693 | }, |
| 2694 | jurisdiction(value) { |
| 2695 | if (value == null) return namespace; |
| 2696 | throw new Error("Jurisdiction restrictions are not implemented"); |
| 2697 | }, |
| 2698 | getByName(name, options) { |
| 2699 | return namespace.get(namespace.idFromName(name), options); |
| 2700 | }, |
| 2701 | get(id) { |
| 2702 | if (!(id instanceof DurableObjectId) || id._className !== className) |
| 2703 | throw new TypeError("Durable Object ID is not valid for this namespace"); |
| 2704 | const scope = id._scope(); |
| 2705 | // Emulate production: the actor recovers its name only when it is |
| 2706 | // <= 1024 UTF-8 bytes; longer names are dropped so ctx.id.name is |
| 2707 | // undefined. The full name still seeds the routing hash, so |
| 2708 | // dispatch is unchanged. Short names skip the byte count (< 256 |
| 2709 | // chars is always <= 1020 bytes) to keep the hot path alloc-free. |
| 2710 | const nm = id.name; |
| 2711 | const dispatchName = nm === undefined ? undefined |
| 2712 | : nm.length < 256 || new TextEncoder().encode(nm).length <= 1024 |
| 2713 | ? nm : undefined; |
| 2714 | if (dispatchName !== undefined) __cell.idNames[scope] = dispatchName; |
| 2715 | // Fetch and native RPC use the same host routing/activation seam. |
| 2716 | // Never expose `.then`: a DO stub is not itself a promise. |
| 2717 | // `__celldDo` brands the stub so the RPC lift can send it as a |
| 2718 | // revivable marker rather than failing the clone; non-enumerable |
| 2719 | // so Object.keys(stub) stays Workerd's [id, name]. |
| 2720 | const target = { id, name: dispatchName }; |
| 2721 | Object.defineProperty(target, "__celldDo", { value: id }); |
| 2722 | const abortMarker = "__CELLD_ACTOR_ABORT__:"; |
| 2723 | const processExitMarker = "__CELLD_PROCESS_EXIT__:"; |
| 2724 | let brokenReason = null; |
| 2725 | const invoke = async (operation) => { |
| 2726 | if (brokenReason !== null) throw new Error(brokenReason); |
| 2727 | try { |
| 2728 | return await operation(); |
| 2729 | } catch (error) { |
| 2730 | const routingError = __durableObjectRoutingError(error); |
| 2731 | if (routingError !== null) throw routingError; |
| 2732 | const message = String(error && error.message || error); |
| 2733 | const marker = [abortMarker, processExitMarker] |
| 2734 | .find((candidate) => message.includes(candidate)); |
| 2735 | if (!marker) throw error; |
| 2736 | brokenReason = message.slice(message.indexOf(marker) + marker.length); |
| 2737 | throw new Error(brokenReason); |
| 2738 | } |
| 2739 | }; |
| 2740 | const doFetch = async (input, init) => { |
| 2741 | const req = new Request(input, init); |
| 2742 | const signal = req._signalForSubrequests; |
| 2743 | if (signal?.aborted) throw signal.reason; |
| 2744 | // The DO seam carries exact bytes; a stream body is drained |
| 2745 | // (and per spec disturbed) first. |
| 2746 | const body_ = req._bodyBytes === null |
| 2747 | ? await req._consume() : req._bodyBytes; |
| 2748 | // Fast path: this isolate owns the target cell — run the DO |
| 2749 | // in-isolate, avoiding the __do_call host round trip. |
| 2750 | if (__cell.owned[scope]) { |
| 2751 | return await invoke(() => __dispatchTo( |
| 2752 | scope, req.url, req.method, body_, |
| 2753 | JSON.stringify(Array.from(req.headers)), |
| 2754 | null, |
| 2755 | true, |
| 2756 | signal, |
| 2757 | )); |
| 2758 | } |
| 2759 | const r = JSON.parse(await invoke(() => { |
| 2760 | if (!signal) return __do_call( |
| 2761 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 2762 | JSON.stringify(Array.from(req.headers)), |
| 2763 | ); |
| 2764 | return __awaitCancellableDoCall( |
| 2765 | __do_call_cancellable( |
| 2766 | scope, dispatchName ?? null, req.url, req.method, body_, |
| 2767 | JSON.stringify(Array.from(req.headers)), |
| 2768 | ), |
| 2769 | signal, |
| 2770 | ); |
| 2771 | })); |
| 2772 | const body = r.streamId !== undefined |
| 2773 | ? new CelldHttpBodyStream(r.streamId) |
| 2774 | : r.body !== undefined |
| 2775 | ? r.body |
| 2776 | : Uint8Array.from(r.bodyBytes || []); |
| 2777 | return new Response(body, { |
| 2778 | status: r.status, headers: r.headers, __wsTarget: r.wsTarget, |
| 2779 | }); |
| 2780 | }; |
| 2781 | const stub = new Proxy(target, { get: (_target, prop) => { |
| 2782 | if (prop === "then") return undefined; |
| 2783 | if (Reflect.has(_target, prop)) return Reflect.get(_target, prop); |
| 2784 | if (prop === "fetch") return doFetch; |
| 2785 | if (typeof prop !== "string") return undefined; |
| 2786 | if (__cell.compat.fetcherGetPutDelete && |
| 2787 | (prop === "get" || prop === "put" || prop === "delete")) |
| 2788 | return __fetcherHelper(doFetch, prop); |
| 2789 | // Fast path: this isolate owns the target cell — run the DO RPC |
| 2790 | // in-isolate, avoiding the __rpc_call host round trip. Still a |
| 2791 | // structured clone each way: Workerd extracts a copy even for a |
| 2792 | // same-isolate call, and JSON round-tripped here before. The |
| 2793 | // reply decodes inside invoke() so abort/exit markers rethrown |
| 2794 | // from the envelope still trip the broken-stub sniffing. |
| 2795 | if (__cell.owned[scope]) |
| 2796 | return async (...args) => invoke( |
| 2797 | async () => __rpcDes(await __dispatchRpc( |
| 2798 | scope, prop, __rpcOut(args, true))), |
| 2799 | ); |
| 2800 | // The routed channel also lifts: same-process dispatch |
| 2801 | // re-enters this isolate, where the markers revive; bytes |
| 2802 | // that land elsewhere revive as loud foreign stubs. |
| 2803 | return async (...args) => invoke( |
| 2804 | async () => __rpcDes(await __rpc_call( |
| 2805 | scope, dispatchName ?? null, prop, __rpcOut(args, true), |
| 2806 | )), |
| 2807 | ); |
| 2808 | }}); |
| 2809 | return stub; |
| 2810 | } |
| 2811 | }; |
| 2812 | return namespace; |
| 2813 | } |
| 2814 | const __attachResponseRequestCancellation = ( |
| 2815 | response, |
| 2816 | requestController, |
| 2817 | wrapBody, |
| 2818 | ) => { |
| 2819 | if (!(response instanceof Response) || |
| 2820 | response._bodyBytes !== null || |
| 2821 | response.body === null) { |
| 2822 | return; |
| 2823 | } |
| 2824 | const requestControllers = Array.isArray( |
| 2825 | response.__celldRequestControllers, |
| 2826 | ) |
| 2827 | ? response.__celldRequestControllers |
| 2828 | : [requestController]; |
| 2829 | if (requestControllers !== response.__celldRequestControllers) { |
| 2830 | Object.defineProperty(response, "__celldRequestControllers", { |
| 2831 | value: requestControllers, |
| 2832 | }); |
| 2833 | } else { |
| 2834 | requestControllers.push(requestController); |
| 2835 | } |
| 2836 | if (!wrapBody || response.__celldCancellationWrapped) return; |
| 2837 | const reader = response.body.getReader(); |
| 2838 | response.body = new ReadableStream({ |
| 2839 | async pull(controller) { |
| 2840 | const result = await reader.read(); |
| 2841 | if (result.done) controller.close(); |
| 2842 | else controller.enqueue(result.value); |
| 2843 | }, |
| 2844 | async cancel() { |
| 2845 | const reason = new Error("The client has disconnected"); |
| 2846 | for (const controller of requestControllers) { |
| 2847 | if (!controller.signal.aborted) controller.abort(reason); |
| 2848 | } |
| 2849 | try { |
| 2850 | await reader.cancel(reason); |
| 2851 | } catch {} |
| 2852 | }, |
| 2853 | }, { highWaterMark: 0 }); |
| 2854 | Object.defineProperty(response, "__celldCancellationWrapped", { |
| 2855 | value: true, |
| 2856 | }); |
| 2857 | }; |
| 2858 | // called on the owner node by the /__do/<scope> endpoint: run one object. |
| 2859 | // Returns the Response; Rust's read_response unwraps it (don't double-wrap). |
| 2860 | // A top-level (non-actor) request whose signal can be aborted by id, so a |
| 2861 | // disconnected HTTP or service-binding caller reaches the target's |
| 2862 | // `request.signal`. |
| 2863 | globalThis.__makeIncomingRequest = ( |
| 2864 | url, method, body, headersJson, |
| 2865 | ) => __makeRequest( |
| 2866 | url, method, body, headersJson, undefined, true); |
| 2867 | globalThis.__dispatchTo = async ( |
| 2868 | scope, url, method, body, headersJson, requestId = null, inline = false, |
| 2869 | callerSignal = null, |
| 2870 | ) => { |
| 2871 | // Request already allocates a default controller for an absent signal. |
| 2872 | // Retain that same allocation so a streamed response can report reader |
| 2873 | // cancellation after the handler has returned. |
| 2874 | const requestController = new AbortController(); |
| 2875 | if (requestId !== null) |
| 2876 | __incomingRequestSignals.set( |
| 2877 | String(requestId), requestController.signal); |
| 2878 | __actorEventStack.push(scope); |
| 2879 | try { |
| 2880 | // Output gate for the co-hosted fast path: the routed path is gated in the |
| 2881 | // host, but an owned in-isolate dispatch bypasses it, so sample the cell's |
| 2882 | // committed-write position here and hold the response below until durable. |
| 2883 | const gateBefore = inline ? __writePosition(scope) : null; |
| 2884 | const dispatch = (async () => { |
| 2885 | const inst = await _readyInstance(scope); |
| 2886 | return await __ctxRun(undefined, () => inst.fetch( |
| 2887 | __makeRequest( |
| 2888 | url, |
| 2889 | method, |
| 2890 | body, |
| 2891 | headersJson, |
| 2892 | requestController.signal, |
| 2893 | true, |
| 2894 | ))); |
| 2895 | })(); |
| 2896 | // The owned in-isolate fast path carries the caller's signal here |
| 2897 | // directly (the routed channel reaches this signal through |
| 2898 | // __do_call_cancel/__abortIncomingRequest instead). Mirror those |
| 2899 | // semantics: abandonment aborts the target's fresh incoming signal |
| 2900 | // with the canonical disconnect reason and rejects the caller with |
| 2901 | // its own reason; the abandoned dispatch keeps its settle handlers |
| 2902 | // and drains its waitUntil work. |
| 2903 | const response = callerSignal === null |
| 2904 | ? await dispatch |
| 2905 | : await __raceCallerAbort(dispatch, callerSignal, () => |
| 2906 | requestController.abort( |
| 2907 | new Error("The client has disconnected"))); |
| 2908 | __attachResponseRequestCancellation( |
| 2909 | response, |
| 2910 | requestController, |
| 2911 | inline, |
| 2912 | ); |
| 2913 | if (response instanceof Response && response.status === 101 && |
| 2914 | response.webSocket && !response.webSocket._target) { |
| 2915 | const socket = response.webSocket._peer; |
| 2916 | const target = { id: response.webSocket._id, scope }; |
| 2917 | response.webSocket._target = target; |
| 2918 | if (socket) { |
| 2919 | socket._target = target; |
| 2920 | if (!socket._hibernatable) |
| 2921 | __ws_accept_regular(socket._id, scope); |
| 2922 | __sockets.set(socket._id, socket); |
| 2923 | socket._flushPending(); |
| 2924 | } |
| 2925 | } |
| 2926 | // Hold the inline response until the write is durable (rejects if it can |
| 2927 | // not be proved, breaking the call as a routed gate failure would). A null |
| 2928 | // `before` means this thread opened the cell's connection during the |
| 2929 | // handler; a fresh connection's change counter starts at zero, so treat it |
| 2930 | // as zero — a write advances past it, a read leaves it there. |
| 2931 | if (inline) { |
| 2932 | const after = __writePosition(scope); |
| 2933 | if (after !== null && after > (gateBefore ?? 0)) await __gateWrite(scope, after); |
| 2934 | } |
| 2935 | return response; |
| 2936 | } finally { |
| 2937 | if (requestId !== null) |
| 2938 | __incomingRequestSignals.delete(String(requestId)); |
| 2939 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 2940 | __actorEventStack.pop(); |
| 2941 | } |
| 2942 | }; |
| 2943 | const __rpcTargetMethod = async (scope, method) => { |
| 2944 | const inst = await _readyInstance(scope); |
| 2945 | if (!inst.__celldState._rpcOk) |
| 2946 | throw new TypeError( |
| 2947 | "The receiving Durable Object does not support RPC, because " + |
| 2948 | "its class was not declared with `extends DurableObject`. In " + |
| 2949 | "order to enable RPC, make sure your class extends the " + |
| 2950 | "special class `DurableObject`, which can be imported from " + |
| 2951 | "the module \"cloudflare:workers\"."); |
| 2952 | const fn = inst[method]; |
| 2953 | if (typeof fn !== "function") |
| 2954 | throw new TypeError(method + " is not a function"); |
| 2955 | return [inst, fn]; |
| 2956 | }; |
| 2957 | // The byte path always lifts stub-able values into the reply: the |
| 2958 | // markers carry the isolate token, so they revive only back in this |
| 2959 | // isolate (the owned fast path and same-process routed dispatch) |
| 2960 | // and fail loudly on use anywhere else. Callee exceptions cross in |
| 2961 | // the error envelope on every flavor. |
| 2962 | globalThis.__dispatchRpc = async (scope, method, args) => { |
| 2963 | __actorEventStack.push(scope); |
| 2964 | try { |
| 2965 | // A string is the legacy JSON flavor (test harness, old cross-node |
| 2966 | // envelope); bytes are V8 structured clone. Answer in kind. |
| 2967 | if (typeof args === "string") { |
| 2968 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 2969 | const result = await fn.apply(inst, JSON.parse(args)); |
| 2970 | return JSON.stringify(result) ?? "null"; |
| 2971 | } |
| 2972 | return await __ctxRun(undefined, () => (async () => { |
| 2973 | const decoded = __rpcDesArgs(args); |
| 2974 | try { |
| 2975 | return await __rpcRun(async () => { |
| 2976 | // A broken actor (JS-flavored ctx.abort) rejects every |
| 2977 | // later call with the reason. One gated field read. |
| 2978 | if (__brokenActors.size !== 0) { |
| 2979 | const broken = __brokenActors.get(scope); |
| 2980 | if (broken !== undefined) throw broken; |
| 2981 | } |
| 2982 | const [inst, fn] = await __rpcTargetMethod(scope, method); |
| 2983 | return fn.apply(inst, decoded.args); |
| 2984 | }, true); |
| 2985 | } finally { |
| 2986 | for (const handle of decoded.received) __disposeStub(handle); |
| 2987 | } |
| 2988 | })()); |
| 2989 | } finally { |
| 2990 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 2991 | __actorEventStack.pop(); |
| 2992 | } |
| 2993 | }; |
| 2994 | // Invoke a method on a named WorkerEntrypoint. Instances are cached per |
| 2995 | // entrypoint: the class is stateless across calls the way a Worker is, |
| 2996 | // so re-constructing per call would only add allocation. |
| 2997 | const __entrypointInstances = new Map(); |
| 2998 | const __entrypointInstance = (name) => { |
| 2999 | const cls = __cell.entrypoints[name]; |
| 3000 | if (typeof cls !== "function") { |
| 3001 | // Workerd getExportedHandler(): distinguish a Durable Object class |
| 3002 | // misused as a stateless entrypoint from a name that resolves to |
| 3003 | // nothing. Error path only; both lookups are O(1). |
| 3004 | if (__cell.classes[name] !== undefined || __cell.doExports[name]) |
| 3005 | throw new TypeError( |
| 3006 | `The entrypoint name ${name} refers to a Durable Object ` + |
| 3007 | "class, but the incoming request is trying to invoke it as " + |
| 3008 | "a stateless worker."); |
| 3009 | throw new TypeError( |
| 3010 | `The entrypoint name ${name} was not found in this worker. ` + |
| 3011 | "Ensure the worker exports an entrypoint with that name."); |
| 3012 | } |
| 3013 | let inst = __entrypointInstances.get(name); |
| 3014 | if (inst === undefined) { |
| 3015 | // End the construction event immediately: ctx.waitUntil registers |
| 3016 | // into whichever event is current at call time, so leaving this |
| 3017 | // event on the stack would swallow every later registration in the |
| 3018 | // isolate. |
| 3019 | const ctx = __beginEvent(); |
| 3020 | try { |
| 3021 | inst = new cls(ctx, __cell.env); |
| 3022 | } finally { |
| 3023 | __endEvent(); |
| 3024 | } |
| 3025 | __entrypointInstances.set(name, inst); |
| 3026 | } |
| 3027 | return inst; |
| 3028 | }; |
| 3029 | // `env.NAME.fetch()` where NAME is bound with `entrypoint = "..."` goes |
| 3030 | // to that class's fetch, not the module's default export. A plain |
| 3031 | // object export (Workerd's non-class entrypoint) dispatches its |
| 3032 | // handler functions as fn(arg, env, ctx). |
| 3033 | globalThis.__dispatchEntrypointFetch = async (name, request) => { |
| 3034 | const handler = __cell.objectEntrypoints[name]; |
| 3035 | if (handler !== undefined) { |
| 3036 | if (typeof handler.fetch !== "function") |
| 3037 | throw new TypeError( |
| 3038 | `Entrypoint ${JSON.stringify(name)} has no fetch handler`); |
| 3039 | const ctx = __beginEvent(); |
| 3040 | try { |
| 3041 | return await __ctxRun(undefined, |
| 3042 | () => handler.fetch(request, __cell.env, ctx)); |
| 3043 | } finally { |
| 3044 | __endEvent(); |
| 3045 | } |
| 3046 | } |
| 3047 | const inst = __entrypointInstance(name); |
| 3048 | if (typeof inst.fetch !== "function") |
| 3049 | throw new TypeError( |
| 3050 | `Entrypoint ${JSON.stringify(name)} has no fetch handler`); |
| 3051 | return await __ctxRun(undefined, () => inst.fetch(request)); |
| 3052 | }; |
| 3053 | // Workerd's simple-handler RPC rules (worker-rpc.c++): a non-class |
| 3054 | // handler method is called as fn(arg, env, ctx), the client must send |
| 3055 | // exactly one argument, and the handler must not declare more than |
| 3056 | // (arg, env, ctx). The messages are Workerd's, verbatim. |
| 3057 | const __callObjectEntrypoint = (handler, method, args) => { |
| 3058 | const fn = handler[method]; |
| 3059 | if (typeof fn !== "function") |
| 3060 | throw new TypeError( |
| 3061 | 'The RPC receiver does not implement the method "' + method + |
| 3062 | '".'); |
| 3063 | if (fn.length > 3) |
| 3064 | throw new TypeError( |
| 3065 | 'Cannot call handler function "' + method + '" over RPC ' + |
| 3066 | "because it has the wrong number of arguments. A simple " + |
| 3067 | "function handler can only be called over RPC if it has " + |
| 3068 | "exactly the arguments (arg, env, ctx), where only the first " + |
| 3069 | "argument comes from the client. To support multi-argument " + |
| 3070 | "RPC functions, use class-based syntax (extending " + |
| 3071 | "WorkerEntrypoint) instead."); |
| 3072 | if (args.length !== 1) |
| 3073 | throw new TypeError( |
| 3074 | 'Attempted to call RPC function "' + method + '" with the ' + |
| 3075 | "wrong number of arguments. When calling a top-level handler " + |
| 3076 | "function that is not declared as part of a class, you must " + |
| 3077 | "always send exactly one argument. In order to support " + |
| 3078 | "variable numbers of arguments, the server must use " + |
| 3079 | "class-based syntax (extending WorkerEntrypoint) instead."); |
| 3080 | const ctx = { |
| 3081 | waitUntil: globalThis.__registerWaitUntil, |
| 3082 | passThroughOnException() {}, |
| 3083 | abort: __ctxAbortCurrent, |
| 3084 | props: __defaultProps, |
| 3085 | get exports() { return __ctxExports(); }, |
| 3086 | }; |
| 3087 | return fn.call(handler, args[0], __cell.env, ctx); |
| 3088 | }; |
| 3089 | // One entrypoint op (a call, or a property GET when argsSc is |
| 3090 | // null), inside a fresh request context — the callee owns stubs |
| 3091 | // revived from its params, and stubs it mints belong to it. |
| 3092 | const __entrypointOp = (name, path, argsSc, local, makeInst) => { |
| 3093 | const id = __nextCtxId++; |
| 3094 | return __ctxRun(id, () => (async () => { |
| 3095 | const decoded = argsSc === null ? null : __rpcDesArgs(argsSc); |
| 3096 | let drain = null; |
| 3097 | try { |
| 3098 | const reply = await __rpcRun(async () => { |
| 3099 | // The handler's synchronous part runs inside its own event so |
| 3100 | // ctx.waitUntil and the imported waitUntil have a target. The |
| 3101 | // event pops before the first await — the event stack is |
| 3102 | // strictly LIFO and an event held across an await would be |
| 3103 | // popped by whichever event settles next — and its registered |
| 3104 | // work drains before a plain reply (below). |
| 3105 | __beginEvent(); |
| 3106 | let result; |
| 3107 | try { |
| 3108 | const handler = __cell.objectEntrypoints[name]; |
| 3109 | if (handler !== undefined && makeInst === undefined) { |
| 3110 | // Simple-handler entrypoints expose single-method calls |
| 3111 | // only; property GETs and deeper paths are refused. |
| 3112 | if (argsSc === null || path.length !== 1) |
| 3113 | throw __rpcNoSuchMethod(path[0]); |
| 3114 | result = __callObjectEntrypoint( |
| 3115 | handler, path[0], decoded.args); |
| 3116 | } else { |
| 3117 | const inst = makeInst === undefined |
| 3118 | ? __entrypointInstance(name) : makeInst(); |
| 3119 | result = __rpcWalk(inst, path, |
| 3120 | decoded === null ? null : decoded.args, true); |
| 3121 | } |
| 3122 | } finally { |
| 3123 | drain = __endEvent(); |
| 3124 | } |
| 3125 | return await result; |
| 3126 | }, local); |
| 3127 | // Registered work drains before a plain reply. A |
| 3128 | // capability-bearing reply (tag 1) must not wait: a returned |
| 3129 | // stream's chunks may be produced by that very work, which |
| 3130 | // cannot finish until the caller pulls (returnReadableStream's |
| 3131 | // waitUntil writer would deadlock behind its own reply). |
| 3132 | if (reply[0] !== 1 && drain !== null) await drain; |
| 3133 | // ctx.abort() during the call supersedes its result; the raw |
| 3134 | // reason rejects the caller (same isolate — identity holds). |
| 3135 | if (__abortedCtxs.size !== 0) { |
| 3136 | const reason = __abortedCtxs.get(id); |
| 3137 | if (reason !== undefined) throw reason; |
| 3138 | } |
| 3139 | // A reply that exports no stubs (tag 0xff plain, tag 0 error) |
| 3140 | // leaves nothing rooting this context: tear it down now, so a |
| 3141 | // dup() the callee leaked reaches its disposal callback |
| 3142 | // promptly (Workerd tears the IoContext down at call end |
| 3143 | // unless returned capabilities hold it open). |
| 3144 | if (reply[0] !== 1) __ctxEnd(id); |
| 3145 | return reply; |
| 3146 | } finally { |
| 3147 | if (decoded !== null) |
| 3148 | for (const handle of decoded.received) __disposeStub(handle); |
| 3149 | } |
| 3150 | })()); |
| 3151 | }; |
| 3152 | // Cross-isolate and host callers still pass a single method name. |
| 3153 | globalThis.__dispatchEntrypointRpc = |
| 3154 | (name, path, argsSc, local = false) => __entrypointOp( |
| 3155 | name, typeof path === "string" ? [path] : path, argsSc, local, |
| 3156 | undefined); |
| 3157 | // WebSocket: the host holds the socket; these deliver events into the DO. |
| 3158 | // `ws` is a lightweight stub whose send/close route back to the host task |
| 3159 | // by wsId — so the isolate can be hibernated between messages. |
| 3160 | globalThis.__wsStub = (wsId) => ({ |
| 3161 | _hibernatable: true, |
| 3162 | send: (data) => { |
| 3163 | if (data instanceof ArrayBuffer) |
| 3164 | __ws_send_binary(wsId, new Uint8Array(data)); |
| 3165 | else if (ArrayBuffer.isView(data)) |
| 3166 | __ws_send_binary(wsId, |
| 3167 | new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); |
| 3168 | else |
| 3169 | __ws_send(wsId, String(data)); |
| 3170 | }, |
| 3171 | close: (code = 1000, reason = "") => __ws_close(wsId, code, reason), |
| 3172 | }); |
| 3173 | globalThis.__wsOpen = async (scope, wsId, protocol) => { |
| 3174 | __actorEventStack.push(scope); |
| 3175 | try { |
| 3176 | const inst = await _readyInstance(scope); |
| 3177 | const socket = inst.__celldState._socket(wsId); |
| 3178 | if (socket.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 3179 | socket.protocol = protocol; |
| 3180 | socket.readyState = WebSocket.READY_STATE_OPEN; |
| 3181 | socket.dispatchEvent(new Event("open")); |
| 3182 | } finally { |
| 3183 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 3184 | __actorEventStack.pop(); |
| 3185 | } |
| 3186 | }; |
| 3187 | globalThis.__wsMessage = async (scope, wsId, msg) => { |
| 3188 | __actorEventStack.push(scope); |
| 3189 | try { |
| 3190 | const inst = await _readyInstance(scope); |
| 3191 | const socket = inst.__celldState._socket(wsId); |
| 3192 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 3193 | socket._dispatchMessage(msg); |
| 3194 | else if (typeof inst.webSocketMessage === "function") |
| 3195 | await inst.webSocketMessage(socket, msg); |
| 3196 | } finally { |
| 3197 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 3198 | __actorEventStack.pop(); |
| 3199 | } |
| 3200 | }; |
| 3201 | globalThis.__wsBinary = async (scope, wsId, data) => { |
| 3202 | __actorEventStack.push(scope); |
| 3203 | try { |
| 3204 | const inst = await _readyInstance(scope); |
| 3205 | const socket = inst.__celldState._socket(wsId); |
| 3206 | const bytes = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 3207 | if (!socket._hibernatable && typeof socket._dispatchMessage === "function") |
| 3208 | socket._dispatchMessage(bytes); |
| 3209 | else if (typeof inst.webSocketMessage === "function") |
| 3210 | await inst.webSocketMessage(socket, bytes); |
| 3211 | } finally { |
| 3212 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 3213 | __actorEventStack.pop(); |
| 3214 | } |
| 3215 | }; |
| 3216 | globalThis.__wsClosed = async (scope, wsId, code, reason, wasClean) => { |
| 3217 | __actorEventStack.push(scope); |
| 3218 | try { |
| 3219 | const inst = await _readyInstance(scope); |
| 3220 | const socket = inst.__celldState._socket(wsId); |
| 3221 | if (!socket._hibernatable && typeof socket._dispatchClose === "function") |
| 3222 | socket._dispatchClose(code, reason, wasClean); |
| 3223 | else if (!wasClean && typeof inst.webSocketError === "function") |
| 3224 | // A hibernatable socket reports an abnormal closure through |
| 3225 | // webSocketError, which celld listed as a handler name and never |
| 3226 | // called. |
| 3227 | await inst.webSocketError( |
| 3228 | socket, |
| 3229 | new Error(reason ? `WebSocket closed abnormally: ${reason}` : "WebSocket closed abnormally"), |
| 3230 | ); |
| 3231 | else if (typeof inst.webSocketClose === "function") |
| 3232 | await inst.webSocketClose(socket, code, reason, wasClean); |
| 3233 | } finally { |
| 3234 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 3235 | __actorEventStack.pop(); |
| 3236 | } |
| 3237 | }; |
| 3238 | // called by celld's scheduler when an alarm is due. Returns a promise. |
| 3239 | globalThis.__fireAlarm = async (scope, scheduledTime, retryCount) => { |
| 3240 | __actorEventStack.push(scope); |
| 3241 | try { |
| 3242 | const inst = await _readyInstance(scope); |
| 3243 | if (typeof inst.alarm !== "function") return; |
| 3244 | await inst.alarm({ scheduledTime, retryCount, isRetry: retryCount > 0 }); |
| 3245 | } finally { |
| 3246 | if (__actorEventStack[__actorEventStack.length - 1] === scope) |
| 3247 | __actorEventStack.pop(); |
| 3248 | } |
| 3249 | }; |
| 3250 | globalThis.__cell = { |
| 3251 | entrypoints: {}, |
| 3252 | objectEntrypoints: {}, |
| 3253 | doExports: {}, |
| 3254 | classes: {}, |
| 3255 | instances: {}, |
| 3256 | env: {}, |
| 3257 | owned: {}, |
| 3258 | idNames: {}, |
| 3259 | namespaceKeys: {}, |
| 3260 | node: "", |
| 3261 | deleteAllDeletesAlarm: false, |
| 3262 | compat: { jsRpc: false, fetcherGetPutDelete: false }, |
| 3263 | makeNamespace, |
| 3264 | }; |
| 3265 | // `cloudflare:workers` module surface. The DO base class sets ctx/env the |
| 3266 | // way `class X extends DurableObject` expects; env aliases the cell env. |
| 3267 | globalThis.__cf = { |
| 3268 | DurableObject: class DurableObject { |
| 3269 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 3270 | }, |
| 3271 | // The enumerable function-valued brand makes V8's structured clone |
| 3272 | // fail on every RpcTarget instance, forcing it off the silent |
| 3273 | // plain-clone path and into the stub lift (Workerd rejects these |
| 3274 | // from plain serialization outright). |
| 3275 | RpcTarget: class RpcTarget { |
| 3276 | constructor() { |
| 3277 | Object.defineProperty(this, "__celldRpcTarget", { |
| 3278 | value: __rpcNoClone, enumerable: true, |
| 3279 | }); |
| 3280 | } |
| 3281 | }, |
| 3282 | // Named entrypoint for `[[services]]` with `entrypoint = "Name"`. |
| 3283 | WorkerEntrypoint: class WorkerEntrypoint { |
| 3284 | constructor(ctx, env) { this.ctx = ctx; this.env = env; } |
| 3285 | }, |
| 3286 | // `new RpcStub(target)` wraps any local object or function in a |
| 3287 | // loopback stub; the constructor returns the proxy, so instanceof |
| 3288 | // works through __makeStub's getPrototypeOf trap. |
| 3289 | RpcStub: class RpcStub { |
| 3290 | constructor(target) { |
| 3291 | if (target === null || |
| 3292 | (typeof target !== "object" && typeof target !== "function")) |
| 3293 | throw new TypeError( |
| 3294 | "RpcStub requires an object or function."); |
| 3295 | return __makeStub( |
| 3296 | __newEntry(target), typeof target === "function"); |
| 3297 | } |
| 3298 | }, |
| 3299 | RpcPromise: class RpcPromise extends Promise {}, |
| 3300 | RpcProperty: class RpcProperty {}, |
| 3301 | ServiceStub: class ServiceStub {}, |
| 3302 | // `import { waitUntil } from "cloudflare:workers"`: register into |
| 3303 | // the current event; outside any event this is Workerd's |
| 3304 | // global-scope error. |
| 3305 | waitUntil(promise) { |
| 3306 | if (__eventStack.length === 0) |
| 3307 | throw new Error( |
| 3308 | "Disallowed operation called within global scope."); |
| 3309 | globalThis.__registerWaitUntil(promise); |
| 3310 | }, |
| 3311 | exports: {}, |
| 3312 | get env() { return globalThis.__cell.env; }, |
| 3313 | }; |
| 3314 | // Pass-through proxy standing in for unsupported node:* builtins: callable, |
| 3315 | // constructable, and every property returns itself — so bundle evaluation |
| 3316 | // never crashes on a builtin the fetch path doesn't actually exercise. |
| 3317 | globalThis.__nodeStub = new Proxy(function () {}, { |
| 3318 | get: (_t, p) => { |
| 3319 | // Never masquerade as a thenable. `await` probes `.then`; returning |
| 3320 | // the callable proxy here creates a promise that can never settle. |
| 3321 | if (p === "then") return undefined; |
| 3322 | // coerce cleanly in string/number contexts so evaluation never throws |
| 3323 | if (p === Symbol.toPrimitive || p === "toString" || p === "valueOf") return () => ""; |
| 3324 | if (p === Symbol.toStringTag) return "NodeStub"; |
| 3325 | if (p === Symbol.iterator) return function* () {}; |
| 3326 | return globalThis.__nodeStub; |
| 3327 | }, |
| 3328 | apply: () => globalThis.__nodeStub, |
| 3329 | construct: () => globalThis.__nodeStub, |
| 3330 | }); |
| 3331 | if (!globalThis.Event) { |
| 3332 | globalThis.Event = class Event { |
| 3333 | // Private fields: stored in the object itself, so an Event costs no |
| 3334 | // side allocation and no defineProperty call at construction. The |
| 3335 | // public members are accessors because the DOM standard makes them |
| 3336 | // read-only; EventTarget drives them through _begin/_end. |
| 3337 | #type; #bubbles; #cancelable; #composed; |
| 3338 | #defaultPrevented = false; |
| 3339 | #eventPhase = 0; |
| 3340 | #target; #currentTarget; #path; |
| 3341 | #stop = false; #stopImmediate = false; #dispatching = false; |
| 3342 | // Workerd: events the runtime delivers are trusted; events a |
| 3343 | // script constructs and dispatches itself are not. |
| 3344 | #trusted = false; |
| 3345 | constructor(type, init = {}) { |
| 3346 | if (arguments.length === 0) |
| 3347 | throw new TypeError( |
| 3348 | "Failed to construct 'Event': 1 argument required, but only " + |
| 3349 | "0 present."); |
| 3350 | if (init !== undefined && init !== null && |
| 3351 | typeof init !== "object") |
| 3352 | throw new TypeError( |
| 3353 | "Failed to construct 'Event': The provided value is not of " + |
| 3354 | "type 'EventInit'."); |
| 3355 | const options = init || {}; |
| 3356 | // Template interpolation, not String(): it must throw for a |
| 3357 | // Symbol, which String() would happily format. |
| 3358 | this.#type = `${type}`; |
| 3359 | this.#bubbles = !!options.bubbles; |
| 3360 | this.#cancelable = !!options.cancelable; |
| 3361 | this.#composed = !!options.composed; |
| 3362 | } |
| 3363 | get type() { return this.#type; } |
| 3364 | get bubbles() { return this.#bubbles; } |
| 3365 | get cancelable() { return this.#cancelable; } |
| 3366 | get composed() { return this.#composed; } |
| 3367 | get defaultPrevented() { return this.#defaultPrevented; } |
| 3368 | get eventPhase() { return this.#eventPhase; } |
| 3369 | get target() { return this.#target; } |
| 3370 | get currentTarget() { return this.#currentTarget; } |
| 3371 | get isTrusted() { return this.#trusted; } |
| 3372 | get timeStamp() { return 0; } |
| 3373 | get returnValue() { return !this.#defaultPrevented; } |
| 3374 | // The one writable member, per the DOM standard. |
| 3375 | get cancelBubble() { return this.#stop; } |
| 3376 | set cancelBubble(value) { if (value) this.#stop = true; } |
| 3377 | composedPath() { return this.#path ? this.#path.slice() : []; } |
| 3378 | preventDefault() { |
| 3379 | if (this.#cancelable) this.#defaultPrevented = true; |
| 3380 | } |
| 3381 | stopPropagation() { this.#stop = true; } |
| 3382 | stopImmediatePropagation() { |
| 3383 | this.#stop = true; |
| 3384 | this.#stopImmediate = true; |
| 3385 | } |
| 3386 | // Internal dispatch hooks used by EventTarget. |
| 3387 | get _dispatching() { return this.#dispatching; } |
| 3388 | get _stopImmediate() { return this.#stopImmediate; } |
| 3389 | _trust() { this.#trusted = true; } |
| 3390 | _begin(target) { |
| 3391 | this.#dispatching = true; |
| 3392 | this.#target = target; |
| 3393 | this.#currentTarget = target; |
| 3394 | this.#eventPhase = 2; // AT_TARGET |
| 3395 | this.#path = [target]; |
| 3396 | this.#stop = false; |
| 3397 | this.#stopImmediate = false; |
| 3398 | } |
| 3399 | // Workerd leaves currentTarget set after dispatch (the DOM standard |
| 3400 | // nulls it); only the phase is reset. |
| 3401 | _end() { |
| 3402 | this.#eventPhase = 0; |
| 3403 | this.#dispatching = false; |
| 3404 | } |
| 3405 | }; |
| 3406 | { |
| 3407 | const phases = { |
| 3408 | NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3, |
| 3409 | }; |
| 3410 | for (const [name, value] of Object.entries(phases)) { |
| 3411 | const d = { value, writable: false, enumerable: true, |
| 3412 | configurable: false }; |
| 3413 | Object.defineProperty(globalThis.Event, name, d); |
| 3414 | Object.defineProperty(globalThis.Event.prototype, name, d); |
| 3415 | } |
| 3416 | } |
| 3417 | } |
| 3418 | if (!globalThis.CustomEvent) { |
| 3419 | globalThis.CustomEvent = class CustomEvent extends Event { |
| 3420 | constructor(type, init = {}) { |
| 3421 | super(type, init); |
| 3422 | this.detail = init.detail === undefined ? null : init.detail; |
| 3423 | } |
| 3424 | }; |
| 3425 | } |
| 3426 | if (!globalThis.ExtendableEvent) { |
| 3427 | // Exists as a type but is not constructable from user code. |
| 3428 | globalThis.ExtendableEvent = class ExtendableEvent extends Event { |
| 3429 | constructor() { |
| 3430 | throw new TypeError("Illegal constructor"); |
| 3431 | } |
| 3432 | }; |
| 3433 | } |
| 3434 | if (!globalThis.EventTarget) { |
| 3435 | globalThis.EventTarget = class EventTarget { |
| 3436 | constructor() { this._listeners = new Map(); } |
| 3437 | addEventListener(type, callback, options = {}) { |
| 3438 | if (callback === null || callback === undefined) return; |
| 3439 | if (typeof callback !== "function" && |
| 3440 | typeof callback.handleEvent !== "function") |
| 3441 | throw new TypeError( |
| 3442 | "Failed to execute 'addEventListener' on 'EventTarget': " + |
| 3443 | "parameter 2 is not of type 'EventListener'."); |
| 3444 | const object = typeof options === "object" && options !== null; |
| 3445 | // Capture and passive are accepted for portability but must be |
| 3446 | // false: Cells dispatches only at the target, so honouring them |
| 3447 | // would silently change ordering. |
| 3448 | if (object ? options.capture || options.passive : !!options) |
| 3449 | throw new TypeError( |
| 3450 | "Cells does not support the 'capture' or 'passive' options " + |
| 3451 | "on addEventListener()."); |
| 3452 | const signal = object ? options.signal : undefined; |
| 3453 | if (signal && signal.aborted) return; |
| 3454 | const key = String(type); |
| 3455 | const list = this._listeners.get(key) || []; |
| 3456 | if (list.some((e) => e.callback === callback)) return; |
| 3457 | list.push({ callback, once: object && !!options.once }); |
| 3458 | this._listeners.set(key, list); |
| 3459 | if (signal) |
| 3460 | signal.addEventListener("abort", () => |
| 3461 | this.removeEventListener(key, callback), { once: true }); |
| 3462 | } |
| 3463 | removeEventListener(type, callback, options = {}) { |
| 3464 | const object = typeof options === "object" && options !== null; |
| 3465 | if (object ? options.capture : !!options) |
| 3466 | throw new TypeError( |
| 3467 | "Cells does not support the 'capture' option on " + |
| 3468 | "removeEventListener()."); |
| 3469 | const list = this._listeners.get(String(type)); |
| 3470 | if (!list) return; |
| 3471 | const index = list.findIndex((e) => e.callback === callback); |
| 3472 | if (index >= 0) list.splice(index, 1); |
| 3473 | } |
| 3474 | dispatchEvent(event) { |
| 3475 | if (!(event instanceof Event)) |
| 3476 | throw new TypeError("argument is not an Event"); |
| 3477 | if (event._dispatching) |
| 3478 | throw new DOMException( |
| 3479 | "The event is already being dispatched.", |
| 3480 | "InvalidStateError"); |
| 3481 | event._begin(this); |
| 3482 | // Copy: a listener may add or remove listeners mid-dispatch. |
| 3483 | for (const item of (this._listeners.get(event.type) || []).slice()) { |
| 3484 | if (event._stopImmediate) break; |
| 3485 | if (item.once) |
| 3486 | this.removeEventListener(event.type, item.callback); |
| 3487 | if (typeof item.callback === "function") |
| 3488 | item.callback.call(this, event); |
| 3489 | else item.callback.handleEvent(event); |
| 3490 | } |
| 3491 | const handler = this["on" + event.type]; |
| 3492 | if (!event._stopImmediate && typeof handler === "function") |
| 3493 | handler.call(this, event); |
| 3494 | event._end(); |
| 3495 | return !event.defaultPrevented; |
| 3496 | } |
| 3497 | }; |
| 3498 | } |
| 3499 | // The global scope is itself an EventTarget. |
| 3500 | if (typeof globalThis.addEventListener !== "function") { |
| 3501 | const globalTarget = new EventTarget(); |
| 3502 | for (const name of |
| 3503 | ["addEventListener", "removeEventListener", "dispatchEvent"]) |
| 3504 | globalThis[name] = globalTarget[name].bind(globalTarget); |
| 3505 | } |
| 3506 | if (!globalThis.MessageEvent) { |
| 3507 | globalThis.MessageEvent = class MessageEvent extends Event { |
| 3508 | constructor(type, init = {}) { |
| 3509 | super(type, init); |
| 3510 | this.data = init.data; |
| 3511 | this.origin = String(init.origin || ""); |
| 3512 | this.lastEventId = String(init.lastEventId || ""); |
| 3513 | } |
| 3514 | }; |
| 3515 | } |
| 3516 | if (!globalThis.CloseEvent) { |
| 3517 | globalThis.CloseEvent = class CloseEvent extends Event { |
| 3518 | constructor(type, init = {}) { |
| 3519 | super(type, init); |
| 3520 | this.code = Number(init.code || 0); |
| 3521 | // `reason` is a USVString: a lone surrogate becomes U+FFFD rather than |
| 3522 | // travelling as an unpaired code unit. |
| 3523 | this.reason = String(init.reason || "").toWellFormed |
| 3524 | ? String(init.reason || "").toWellFormed() |
| 3525 | : String(init.reason || "").replace( |
| 3526 | /[\uD800-\uDFFF]/g, |
| 3527 | (unit, index, whole) => { |
| 3528 | const code = unit.charCodeAt(0); |
| 3529 | const next = whole.charCodeAt(index + 1); |
| 3530 | const prev = whole.charCodeAt(index - 1); |
| 3531 | const paired = code <= 0xDBFF |
| 3532 | ? next >= 0xDC00 && next <= 0xDFFF |
| 3533 | : prev >= 0xD800 && prev <= 0xDBFF; |
| 3534 | return paired ? unit : "\uFFFD"; |
| 3535 | }, |
| 3536 | ); |
| 3537 | this.wasClean = !!init.wasClean; |
| 3538 | } |
| 3539 | }; |
| 3540 | } |
| 3541 | if (!globalThis.DOMException) { |
| 3542 | globalThis.DOMException = class DOMException extends Error { |
| 3543 | constructor(message = "", name = "Error") { super(message); this.name = name; } |
| 3544 | }; |
| 3545 | // WebIDL legacy code constants, enumerable on both the interface |
| 3546 | // object and its prototype, in spec order. |
| 3547 | { |
| 3548 | const codes = [ |
| 3549 | ["INDEX_SIZE_ERR", 1], ["DOMSTRING_SIZE_ERR", 2], |
| 3550 | ["HIERARCHY_REQUEST_ERR", 3], ["WRONG_DOCUMENT_ERR", 4], |
| 3551 | ["INVALID_CHARACTER_ERR", 5], ["NO_DATA_ALLOWED_ERR", 6], |
| 3552 | ["NO_MODIFICATION_ALLOWED_ERR", 7], ["NOT_FOUND_ERR", 8], |
| 3553 | ["NOT_SUPPORTED_ERR", 9], ["INUSE_ATTRIBUTE_ERR", 10], |
| 3554 | ["INVALID_STATE_ERR", 11], ["SYNTAX_ERR", 12], |
| 3555 | ["INVALID_MODIFICATION_ERR", 13], ["NAMESPACE_ERR", 14], |
| 3556 | ["INVALID_ACCESS_ERR", 15], ["VALIDATION_ERR", 16], |
| 3557 | ["TYPE_MISMATCH_ERR", 17], ["SECURITY_ERR", 18], |
| 3558 | ["NETWORK_ERR", 19], ["ABORT_ERR", 20], |
| 3559 | ["URL_MISMATCH_ERR", 21], ["QUOTA_EXCEEDED_ERR", 22], |
| 3560 | ["TIMEOUT_ERR", 23], ["INVALID_NODE_TYPE_ERR", 24], |
| 3561 | ["DATA_CLONE_ERR", 25], |
| 3562 | ]; |
| 3563 | for (const [name, value] of codes) { |
| 3564 | const d = { value, writable: false, enumerable: true, |
| 3565 | configurable: false }; |
| 3566 | Object.defineProperty(globalThis.DOMException, name, d); |
| 3567 | Object.defineProperty(globalThis.DOMException.prototype, name, d); |
| 3568 | } |
| 3569 | } |
| 3570 | } |
| 3571 | if (!globalThis.AbortSignal) { |
| 3572 | globalThis.AbortSignal = class AbortSignal extends EventTarget { |
| 3573 | // The Headers/Blob clone-poisoning brand: V8's structured |
| 3574 | // clone throws on functions, so a live signal reaches the |
| 3575 | // RPC lift instead of silently flattening to plain data. |
| 3576 | constructor() { |
| 3577 | super(); |
| 3578 | this.aborted = false; |
| 3579 | this.reason = undefined; |
| 3580 | this.__celldHost = __rpcNoClone; |
| 3581 | } |
| 3582 | throwIfAborted() { if (this.aborted) throw this.reason; } |
| 3583 | static abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 3584 | const c = new AbortController(); c.abort(reason); return c.signal; |
| 3585 | } |
| 3586 | static timeout(ms) { |
| 3587 | const c = new AbortController(); |
| 3588 | setTimeout(() => c.abort(new DOMException( |
| 3589 | "The operation was aborted due to timeout", "TimeoutError", |
| 3590 | )), ms); |
| 3591 | return c.signal; |
| 3592 | } |
| 3593 | static any(signals) { |
| 3594 | const c = new AbortController(); |
| 3595 | for (const signal of signals) { |
| 3596 | if (signal.aborted) { c.abort(signal.reason); break; } |
| 3597 | signal.addEventListener("abort", () => c.abort(signal.reason), { once: true }); |
| 3598 | } |
| 3599 | return c.signal; |
| 3600 | } |
| 3601 | }; |
| 3602 | globalThis.AbortController = class AbortController { |
| 3603 | constructor() { this.signal = new AbortSignal(); } |
| 3604 | abort(reason = new DOMException("This operation was aborted", "AbortError")) { |
| 3605 | __abortSignal(this.signal, reason); |
| 3606 | } |
| 3607 | }; |
| 3608 | } |
| 3609 | if (!globalThis.Blob) { |
| 3610 | // Same clone-poisoning brand as Headers: an enumerable |
| 3611 | // function-valued property makes V8's structured clone throw, so |
| 3612 | // a Blob reaches the RPC lift instead of silently flattening. |
| 3613 | const __blobNoClone = () => {}; |
| 3614 | globalThis.Blob = class Blob { |
| 3615 | constructor(parts = [], options = {}) { |
| 3616 | // size is assigned before type so both land in the order the |
| 3617 | // inspect output below reports them. |
| 3618 | if (options && options.endings !== undefined) |
| 3619 | throw new Error( |
| 3620 | "The 'endings' field on 'Options' is not implemented."); |
| 3621 | this.size = 0; |
| 3622 | // A type outside U+0020..U+007E is not a valid MIME type and is |
| 3623 | // dropped rather than stored. |
| 3624 | const rawType = String(options.type || ""); |
| 3625 | this.type = /^[\u0020-\u007e]*$/.test(rawType) |
| 3626 | ? rawType.toLowerCase() : ""; |
| 3627 | this.__celldHost = __blobNoClone; |
| 3628 | // Two passes. First convert every part in order — string |
| 3629 | // conversion runs user code (Symbol.toPrimitive), which may |
| 3630 | // resize a backing buffer. Buffers and views are carried through |
| 3631 | // as-is so a length-tracking view is measured *after* those side |
| 3632 | // effects, matching Workerd. Then allocate once and copy. |
| 3633 | // |
| 3634 | // The previous shape pushed every byte into a plain array with a |
| 3635 | // spread, costing roughly 8x the memory and exceeding the |
| 3636 | // argument limit on multi-megabyte parts. |
| 3637 | const sources = []; |
| 3638 | for (const part of parts) { |
| 3639 | if (part instanceof Blob) sources.push(part._bytes); |
| 3640 | else if (part instanceof ArrayBuffer || |
| 3641 | ArrayBuffer.isView(part)) sources.push(part); |
| 3642 | else sources.push(new TextEncoder().encode(String(part))); |
| 3643 | } |
| 3644 | const chunks = sources.map((source) => |
| 3645 | source instanceof Uint8Array ? source |
| 3646 | : source instanceof ArrayBuffer ? new Uint8Array(source) |
| 3647 | : new Uint8Array( |
| 3648 | source.buffer, source.byteOffset, source.byteLength)); |
| 3649 | let total = 0; |
| 3650 | for (const chunk of chunks) total += chunk.byteLength; |
| 3651 | const LIMIT = 134217728; |
| 3652 | if (total > LIMIT) |
| 3653 | throw new RangeError( |
| 3654 | `Blob size ${total} exceeds limit ${LIMIT}`); |
| 3655 | const bytes = new Uint8Array(total); |
| 3656 | let offset = 0; |
| 3657 | for (const chunk of chunks) { |
| 3658 | bytes.set(chunk, offset); |
| 3659 | offset += chunk.byteLength; |
| 3660 | } |
| 3661 | // Non-enumerable: the backing store is not part of the object's |
| 3662 | // observable shape (inspect, JSON, spread). |
| 3663 | Object.defineProperty(this, "_bytes", { |
| 3664 | value: bytes, writable: true, configurable: true, |
| 3665 | }); |
| 3666 | this.size = total; |
| 3667 | } |
| 3668 | async arrayBuffer() { return this._bytes.slice().buffer; } |
| 3669 | async bytes() { return this._bytes.slice(); } |
| 3670 | async text() { return new TextDecoder().decode(this._bytes); } |
| 3671 | stream() { |
| 3672 | const bytes = this._bytes; |
| 3673 | return new ReadableStream({ |
| 3674 | start(controller) { |
| 3675 | if (bytes.byteLength) controller.enqueue(bytes.slice()); |
| 3676 | controller.close(); |
| 3677 | }, |
| 3678 | }); |
| 3679 | } |
| 3680 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 3681 | return `Blob { size: ${this.size}, type: '${this.type}' }`; |
| 3682 | } |
| 3683 | slice(start = 0, end = this.size, type = "") { |
| 3684 | const norm = (n, fallback) => { |
| 3685 | n = n === undefined ? fallback : Number(n); |
| 3686 | return n < 0 ? Math.max(this.size + n, 0) : Math.min(n, this.size); |
| 3687 | }; |
| 3688 | const a = norm(start, 0), b = norm(end, this.size); |
| 3689 | return new Blob( |
| 3690 | [this._bytes.subarray(a, Math.max(a, b))], { type }); |
| 3691 | } |
| 3692 | get [Symbol.toStringTag]() { return "Blob"; } |
| 3693 | }; |
| 3694 | } |
| 3695 | if (!globalThis.File) { |
| 3696 | // WebIDL-ish per Workerd: name is required, name/lastModified are |
| 3697 | // brand-checked prototype getters (enumerable, matching the |
| 3698 | // workers_api_getters_setters_on_prototype flag), and lastModified |
| 3699 | // coerces via ToNumber (throws for BigInt), NaN becoming 0. |
| 3700 | globalThis.File = class File extends Blob { |
| 3701 | #name; |
| 3702 | #lastModified; |
| 3703 | constructor(parts, name, options = {}) { |
| 3704 | if (arguments.length < 2) |
| 3705 | throw new TypeError( |
| 3706 | "Failed to construct 'File': 2 arguments required, but " + |
| 3707 | `only ${arguments.length} present.`); |
| 3708 | super(parts, options); |
| 3709 | this.#name = String(name); |
| 3710 | const lm = options == null ? undefined : options.lastModified; |
| 3711 | if (lm === undefined) this.#lastModified = Date.now(); |
| 3712 | else { |
| 3713 | const n = +lm; // ToNumber: throws for BigInt, like WebIDL |
| 3714 | this.#lastModified = Number.isFinite(n) ? Math.trunc(n) : 0; |
| 3715 | } |
| 3716 | } |
| 3717 | get name() { return this.#name; } |
| 3718 | get lastModified() { return this.#lastModified; } |
| 3719 | get [Symbol.toStringTag]() { return "File"; } |
| 3720 | [Symbol.for("nodejs.util.inspect.custom")]() { |
| 3721 | return `File { name: '${this.name}', ` + |
| 3722 | `lastModified: ${this.lastModified}, size: ${this.size}, ` + |
| 3723 | `type: '${this.type}' }`; |
| 3724 | } |
| 3725 | }; |
| 3726 | for (const key of ["name", "lastModified"]) { |
| 3727 | const desc = |
| 3728 | Object.getOwnPropertyDescriptor(File.prototype, key); |
| 3729 | desc.enumerable = true; |
| 3730 | Object.defineProperty(File.prototype, key, desc); |
| 3731 | } |
| 3732 | } |
| 3733 | if (!globalThis.FormData) { |
| 3734 | // Body -> FormData for multipart/form-data and |
| 3735 | // application/x-www-form-urlencoded. Kept out of the class so V8 only |
| 3736 | // pre-parses it; the body is compiled on first actual formData() call. |
| 3737 | globalThis.__parseFormData = (text, contentType) => { |
| 3738 | const ct = String(contentType || ""); |
| 3739 | if (/^\s*application\/x-www-form-urlencoded/i.test(ct)) { |
| 3740 | const form = new FormData(); |
| 3741 | for (const [key, value] of new URLSearchParams(text)) |
| 3742 | form.append(key, value); |
| 3743 | return form; |
| 3744 | } |
| 3745 | if (!/^\s*multipart\/form-data/i.test(ct)) |
| 3746 | throw new TypeError( |
| 3747 | "Unrecognized Content-Type header value. FormData can only " + |
| 3748 | "parse the following MIME types: multipart/form-data, " + |
| 3749 | "application/x-www-form-urlencoded"); |
| 3750 | const found = /boundary\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(ct); |
| 3751 | if (!found) |
| 3752 | throw new TypeError( |
| 3753 | "No boundary was found in the multipart/form-data " + |
| 3754 | "Content-Type header."); |
| 3755 | const boundary = (found[1] !== undefined ? found[1] : found[2]).trim(); |
| 3756 | const form = new FormData(); |
| 3757 | const delimiter = "--" + boundary; |
| 3758 | // Parts are delimited by the boundary; the preamble before the first |
| 3759 | // delimiter and the epilogue after the closing one are ignored. |
| 3760 | const chunks = text.split(delimiter); |
| 3761 | for (let i = 1; i < chunks.length; i++) { |
| 3762 | let chunk = chunks[i]; |
| 3763 | if (chunk.startsWith("--")) break; // closing delimiter |
| 3764 | chunk = chunk.replace(/^\r?\n/, ""); |
| 3765 | const split = /\r?\n\r?\n/.exec(chunk); |
| 3766 | if (!split) continue; |
| 3767 | const rawHeaders = chunk.slice(0, split.index); |
| 3768 | // Trim the CRLF that belongs to the following delimiter. |
| 3769 | const body = chunk |
| 3770 | .slice(split.index + split[0].length) |
| 3771 | .replace(/\r?\n$/, ""); |
| 3772 | let disposition = null; |
| 3773 | let type = ""; |
| 3774 | for (const line of rawHeaders.split(/\r?\n/)) { |
| 3775 | const colon = line.indexOf(":"); |
| 3776 | if (colon < 0) continue; |
| 3777 | const name = line.slice(0, colon).trim().toLowerCase(); |
| 3778 | const value = line.slice(colon + 1).trim(); |
| 3779 | if (name === "content-disposition") disposition = value; |
| 3780 | else if (name === "content-type") type = value; |
| 3781 | } |
| 3782 | if (disposition === null) |
| 3783 | throw new TypeError( |
| 3784 | "Content-Disposition header is required for each FormData " + |
| 3785 | "part."); |
| 3786 | const kind = disposition.split(";")[0].trim(); |
| 3787 | if (kind.toLowerCase() !== "form-data") |
| 3788 | throw new TypeError( |
| 3789 | "Content-Disposition header for FormData part must have the " + |
| 3790 | "value \"form-data\", possibly followed by parameters. Got: " + |
| 3791 | "\"" + kind + "\""); |
| 3792 | const param = (key) => { |
| 3793 | const m = new RegExp( |
| 3794 | key + "\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^;]*))", "i", |
| 3795 | ).exec(disposition); |
| 3796 | if (!m) return undefined; |
| 3797 | const raw = m[1] !== undefined ? m[1] : (m[2] || "").trim(); |
| 3798 | if (/\\$/.test(raw.replace(/\\\\/g, ""))) |
| 3799 | throw new TypeError( |
| 3800 | "Name or filename can't end with backslash"); |
| 3801 | return raw.replace(/\\(.)/g, "$1"); |
| 3802 | }; |
| 3803 | const name = param("name"); |
| 3804 | if (name === undefined) |
| 3805 | throw new TypeError( |
| 3806 | "Content-Disposition header for FormData part must have a " + |
| 3807 | "name parameter."); |
| 3808 | const filename = param("filename"); |
| 3809 | if (filename === undefined) form.append(name, body); |
| 3810 | else |
| 3811 | form.append( |
| 3812 | name, new File([body], filename, { type: type || "" })); |
| 3813 | } |
| 3814 | return form; |
| 3815 | }; |
| 3816 | // Spec entry conversion: strings stay strings; a Blob becomes a |
| 3817 | // File named "blob" (or `filename`); a File is renamed only when a |
| 3818 | // filename is supplied. |
| 3819 | const __formDataValue = (value, filename) => { |
| 3820 | if (!(value instanceof Blob)) return String(value); |
| 3821 | if (value instanceof File && filename === undefined) return value; |
| 3822 | return new File( |
| 3823 | [value], |
| 3824 | filename === undefined ? "blob" : String(filename), |
| 3825 | { |
| 3826 | type: value.type, |
| 3827 | lastModified: |
| 3828 | value instanceof File ? value.lastModified : undefined, |
| 3829 | }, |
| 3830 | ); |
| 3831 | }; |
| 3832 | globalThis.FormData = class FormData { |
| 3833 | constructor() { this._entries = []; } |
| 3834 | append(name, value, filename) { |
| 3835 | this._entries.push( |
| 3836 | [String(name), __formDataValue(value, filename)]); |
| 3837 | } |
| 3838 | set(name, value, filename) { |
| 3839 | value = __formDataValue(value, filename); |
| 3840 | const key = String(name); |
| 3841 | // Spec: replace the first match in place, keeping its position, |
| 3842 | // and drop any later matches. |
| 3843 | const first = this._entries.findIndex(([k]) => k === key); |
| 3844 | if (first < 0) { this._entries.push([key, value]); return; } |
| 3845 | this._entries[first] = [key, value]; |
| 3846 | for (let i = this._entries.length - 1; i > first; i--) |
| 3847 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 3848 | } |
| 3849 | get(name) { |
| 3850 | const row = this._entries.find(([key]) => key === String(name)); |
| 3851 | return row ? row[1] : null; |
| 3852 | } |
| 3853 | getAll(name) { |
| 3854 | return this._entries.filter(([key]) => key === String(name)).map(([, value]) => value); |
| 3855 | } |
| 3856 | has(name) { return this._entries.some(([key]) => key === String(name)); } |
| 3857 | delete(name) { |
| 3858 | const key = String(name); |
| 3859 | // Splice in place: the iterators below read the live list, so the |
| 3860 | // array identity must survive a delete during iteration. |
| 3861 | for (let i = this._entries.length - 1; i >= 0; i--) |
| 3862 | if (this._entries[i][0] === key) this._entries.splice(i, 1); |
| 3863 | } |
| 3864 | // Iteration is live: the iterator holds an index and re-reads the |
| 3865 | // entry list, so entries appended during iteration are visited and |
| 3866 | // an exhausted iterator resumes if entries are added later. A |
| 3867 | // generator cannot do this — once it returns it is done forever. |
| 3868 | _iterate(pick) { |
| 3869 | const self = this; |
| 3870 | let index = 0; |
| 3871 | const iterator = { |
| 3872 | next() { |
| 3873 | if (index >= self._entries.length) |
| 3874 | return { value: undefined, done: true }; |
| 3875 | return { value: pick(self._entries[index++]), done: false }; |
| 3876 | }, |
| 3877 | [Symbol.iterator]() { return iterator; }, |
| 3878 | }; |
| 3879 | return iterator; |
| 3880 | } |
| 3881 | entries() { return this._iterate((e) => [e[0], e[1]]); } |
| 3882 | keys() { return this._iterate((e) => e[0]); } |
| 3883 | values() { return this._iterate((e) => e[1]); } |
| 3884 | [Symbol.iterator]() { return this.entries(); } |
| 3885 | forEach(callback, thisArg) { |
| 3886 | if (typeof callback !== "function") |
| 3887 | throw new TypeError( |
| 3888 | "Failed to execute 'forEach' on 'FormData': parameter 1 is " + |
| 3889 | "not of type 'Function'."); |
| 3890 | for (const [key, value] of this.entries()) |
| 3891 | callback.call(thisArg, value, key, this); |
| 3892 | } |
| 3893 | }; |
| 3894 | } |
| 3895 | // Node's Buffer lives in src/js/node_buffer.js, compiled |
| 3896 | // lazily (LAZY_GLOBALS / LAZY_MODULES) on first use. |
| 3897 | if (!globalThis.ErrorEvent) { |
| 3898 | globalThis.ErrorEvent = class ErrorEvent extends Event { |
| 3899 | constructor(type, init = {}) { |
| 3900 | super(type, init); |
| 3901 | this.message = String(init.message ?? ""); |
| 3902 | this.filename = String(init.filename ?? ""); |
| 3903 | this.lineno = Number(init.lineno ?? 0); |
| 3904 | this.colno = Number(init.colno ?? 0); |
| 3905 | this.error = init.error; |
| 3906 | } |
| 3907 | }; |
| 3908 | } |
| 3909 | // Web API globals a real bundle references at module scope but that the |
| 3910 | // prelude doesn't provide. Stub as empty classes (guarded so we never |
| 3911 | // clobber a real prelude implementation). Enough to LOAD; runtime use of |
| 3912 | // an unimplemented one is a separate gap. |
| 3913 | for (const n of ["WebSocket", "EventTarget", "Event", "MessageEvent", |
| 3914 | "CloseEvent", "ErrorEvent", "EventSource", "MessageChannel", |
| 3915 | "MessagePort", "BroadcastChannel", "SubtleCrypto", "TransformStream", |
| 3916 | "ReadableStream", "WritableStream", "ReadableStreamDefaultReader", |
| 3917 | "WritableStreamDefaultWriter", |
| 3918 | "ByteLengthQueuingStrategy", "CountQueuingStrategy", |
| 3919 | "TextEncoderStream", "TextDecoderStream", "FileReader"]) { |
| 3920 | if (!globalThis[n]) globalThis[n] = class {}; |
| 3921 | } |
| 3922 | globalThis.__sockets = new Map(); |
| 3923 | globalThis.WebSocket = class WebSocket extends EventTarget { |
| 3924 | // The spec names, which workerd exposes and real bundles use. celld only |
| 3925 | // had the READY_STATE_* aliases, which no other runtime defines. |
| 3926 | static CONNECTING = 0; |
| 3927 | static OPEN = 1; |
| 3928 | static CLOSING = 2; |
| 3929 | static CLOSED = 3; |
| 3930 | static READY_STATE_CONNECTING = 0; |
| 3931 | static READY_STATE_OPEN = 1; |
| 3932 | static READY_STATE_CLOSING = 2; |
| 3933 | static READY_STATE_CLOSED = 3; |
| 3934 | constructor(id, protocols = []) { |
| 3935 | super(); |
| 3936 | const outbound = typeof id === "string"; |
| 3937 | this._outbound = outbound; |
| 3938 | this._pendingClose = null; |
| 3939 | this._id = outbound ? __ws_alloc() : Number(id); |
| 3940 | this._attachment = undefined; |
| 3941 | this._target = null; |
| 3942 | this._accepted = false; |
| 3943 | this._hibernatable = false; |
| 3944 | this._pending = []; |
| 3945 | // The other end of an in-isolate upgrade (a WebSocketPair served |
| 3946 | // over a same-script service binding); frames route to it |
| 3947 | // directly instead of through the host connection. |
| 3948 | this._loopback = null; |
| 3949 | this.readyState = outbound ? 0 : 1; |
| 3950 | this._binaryType = __cell.compat?.websocketStandardBinaryType |
| 3951 | ? "blob" |
| 3952 | : "arraybuffer"; |
| 3953 | // A server-side socket has no URL, and reports null rather than an empty |
| 3954 | // string -- workerd's inspect output pins this. |
| 3955 | this.url = outbound ? id : null; |
| 3956 | this.protocol = ""; |
| 3957 | this.extensions = ""; |
| 3958 | if (outbound) { |
| 3959 | // workerd validates the URL in the constructor and throws |
| 3960 | // synchronously; letting the connector reject later would surface a |
| 3961 | // scheme mistake as a network failure instead of a TypeError. |
| 3962 | let parsed; |
| 3963 | try { |
| 3964 | parsed = new URL(id); |
| 3965 | } catch { |
| 3966 | throw new DOMException( |
| 3967 | "WebSocket Constructor: The url is invalid.", |
| 3968 | "SyntaxError"); |
| 3969 | } |
| 3970 | if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { |
| 3971 | throw new DOMException( |
| 3972 | "WebSocket Constructor: The url scheme must be ws or wss.", |
| 3973 | "SyntaxError"); |
| 3974 | } |
| 3975 | // A Durable Object socket is pushed events by the host so it can revive |
| 3976 | // a hibernated cell. A Worker socket has no cell: the isolate polls it, |
| 3977 | // and it lives and dies with the request, which is the lifetime |
| 3978 | // Cloudflare gives one too. |
| 3979 | const scope = __actorEventStack[__actorEventStack.length - 1] || ""; |
| 3980 | this._polled = !scope; |
| 3981 | const requested = typeof protocols === "string" |
| 3982 | ? [protocols] |
| 3983 | : Array.from(protocols, String); |
| 3984 | for (const value of requested) { |
| 3985 | // RFC 6455 subprotocols are HTTP tokens; a space or separator would |
| 3986 | // otherwise be smuggled into the Sec-WebSocket-Protocol header. |
| 3987 | if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) { |
| 3988 | throw new DOMException( |
| 3989 | `WebSocket Constructor: The subprotocol '${value}' is invalid.`, |
| 3990 | "SyntaxError"); |
| 3991 | } |
| 3992 | } |
| 3993 | if (new Set(requested).size !== requested.length) { |
| 3994 | throw new DOMException( |
| 3995 | "WebSocket Constructor: The subprotocols must be unique.", |
| 3996 | "SyntaxError"); |
| 3997 | } |
| 3998 | __sockets.set(this._id, this); |
| 3999 | const connection = __ws_connect(this._id, scope, id, JSON.stringify(requested)); |
| 4000 | __registerWaitUntil(connection); |
| 4001 | if (this._polled) this._startPump(); |
| 4002 | connection.then((protocol) => { |
| 4003 | if (this.readyState === WebSocket.READY_STATE_CLOSING) { |
| 4004 | if (this._pendingClose) { |
| 4005 | const [code, reason] = this._pendingClose; |
| 4006 | __ws_close(this._id, code, reason); |
| 4007 | } |
| 4008 | return; |
| 4009 | } |
| 4010 | if (this.readyState !== WebSocket.READY_STATE_CONNECTING) return; |
| 4011 | this.protocol = protocol; |
| 4012 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 4013 | this.dispatchEvent(new Event("open")); |
| 4014 | }, (error) => { |
| 4015 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 4016 | __sockets.delete(this._id); |
| 4017 | this.dispatchEvent(new ErrorEvent("error", { message: String(error?.message || error), error })); |
| 4018 | this._dispatchClose(1006, "", false); |
| 4019 | }); |
| 4020 | } |
| 4021 | } |
| 4022 | // The pump ends only when the socket closes, so it must NOT be registered |
| 4023 | // as waitUntil work: that would hold the request open for as long as the |
| 4024 | // socket lives, and the region can only reclaim an abandoned socket by |
| 4025 | // exiting. Its `__ws_next` ops still belong to the region and are driven |
| 4026 | // while the request runs, then aborted with it. |
| 4027 | _startPump() { |
| 4028 | if (this._pumping) return; |
| 4029 | this._pumping = true; |
| 4030 | this._pump().catch(() => {}); |
| 4031 | } |
| 4032 | // Drain the host queue for an isolate-polled socket. Each `__ws_next` is an |
| 4033 | // ordinary async op, so the request's region owns it and aborts it if the |
| 4034 | // request ends first — the socket is closed by the region on the way out. |
| 4035 | async _pump() { |
| 4036 | for (;;) { |
| 4037 | const frame = await __ws_next(this._id); |
| 4038 | const tag = frame[0]; |
| 4039 | const body = frame.subarray(1); |
| 4040 | if (tag === 0) { |
| 4041 | this._dispatchMessage(new TextDecoder().decode(body)); |
| 4042 | } else if (tag === 1) { |
| 4043 | this._dispatchMessage( |
| 4044 | body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength), |
| 4045 | ); |
| 4046 | } else if (tag === 2) { |
| 4047 | if (this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 4048 | this.protocol = new TextDecoder().decode(body); |
| 4049 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 4050 | this.dispatchEvent(new Event("open")); |
| 4051 | } |
| 4052 | } else { |
| 4053 | const info = JSON.parse(new TextDecoder().decode(body)); |
| 4054 | this._dispatchClose(info.code, info.reason, info.wasClean); |
| 4055 | return; |
| 4056 | } |
| 4057 | } |
| 4058 | } |
| 4059 | // Deliver whatever this end queued before it had somewhere to send. |
| 4060 | _flushToPeer() { |
| 4061 | const peer = this._loopback; |
| 4062 | if (!peer) return; |
| 4063 | for (const frame of this._pending.splice(0)) { |
| 4064 | if (frame[0] === "send") { |
| 4065 | queueMicrotask(() => peer._dispatchMessage(frame[1])); |
| 4066 | } else if (frame[0] === "send-binary") { |
| 4067 | const data = frame[1]; |
| 4068 | const bytes = data instanceof ArrayBuffer |
| 4069 | ? data |
| 4070 | : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); |
| 4071 | queueMicrotask(() => peer._dispatchMessage(bytes)); |
| 4072 | } else { |
| 4073 | queueMicrotask(() => peer._dispatchClose(frame[1], frame[2], true)); |
| 4074 | } |
| 4075 | } |
| 4076 | } |
| 4077 | get binaryType() { return this._binaryType; } |
| 4078 | // The spec ignores an unrecognised value rather than throwing. |
| 4079 | set binaryType(value) { |
| 4080 | if (value === "blob" || value === "arraybuffer") this._binaryType = value; |
| 4081 | } |
| 4082 | accept() { |
| 4083 | this._accepted = true; |
| 4084 | // A pair used directly, without being returned through a 101 response, |
| 4085 | // still has to carry frames once both ends are accepted. celld only |
| 4086 | // linked a pair on the upgrade path, so such a pair queued forever. |
| 4087 | if (this._peer && this._peer._accepted && !this._loopback) { |
| 4088 | this._loopback = this._peer; |
| 4089 | this._peer._loopback = this; |
| 4090 | this._flushToPeer(); |
| 4091 | this._peer._flushToPeer(); |
| 4092 | } |
| 4093 | // A socket obtained from a `fetch()` upgrade is already connected and |
| 4094 | // delivers nothing until it is accepted; this is where it starts. |
| 4095 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) { |
| 4096 | this.readyState = WebSocket.READY_STATE_OPEN; |
| 4097 | if (this._polled) this._startPump(); |
| 4098 | } |
| 4099 | } |
| 4100 | send(data) { |
| 4101 | if (this.readyState !== WebSocket.READY_STATE_OPEN) |
| 4102 | throw new DOMException("WebSocket is not open", "InvalidStateError"); |
| 4103 | const binary = data instanceof ArrayBuffer || ArrayBuffer.isView(data); |
| 4104 | const text = binary ? null : String(data); |
| 4105 | if (this._loopback) { |
| 4106 | const peer = this._loopback; |
| 4107 | const message = binary |
| 4108 | ? (data instanceof ArrayBuffer ? data.slice(0) : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)) |
| 4109 | : text; |
| 4110 | queueMicrotask(() => peer._dispatchMessage(message)); |
| 4111 | return; |
| 4112 | } |
| 4113 | // The pending queue belongs to an inbound pair socket that has been |
| 4114 | // accepted but not yet bound to a host transport. An outbound socket is |
| 4115 | // already bound -- queueing here would silently swallow its frames. |
| 4116 | if (!this._outbound && this._accepted && !this._target) { |
| 4117 | this._pending.push([binary ? "send-binary" : "send", binary ? data : text]); |
| 4118 | return; |
| 4119 | } |
| 4120 | if (binary) { |
| 4121 | const bytes = data instanceof ArrayBuffer |
| 4122 | ? new Uint8Array(data) |
| 4123 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 4124 | __ws_send_binary(this._id, bytes); |
| 4125 | } else { |
| 4126 | __ws_send(this._id, text); |
| 4127 | } |
| 4128 | } |
| 4129 | close(code = 1000, reason = "") { |
| 4130 | // WHATWG: an application may send 1000 or 3000-4999. Everything else is |
| 4131 | // reserved for the protocol itself. |
| 4132 | const wanted = Number(code); |
| 4133 | if (wanted !== 1000 && !(wanted >= 3000 && wanted <= 4999)) { |
| 4134 | throw new DOMException( |
| 4135 | `WebSocket close code ${code} is not permitted`, |
| 4136 | "InvalidAccessError"); |
| 4137 | } |
| 4138 | // RFC 6455 5.5: the close frame body is at most 125 bytes, two of which |
| 4139 | // are the code. Measured in UTF-8, so a multibyte reason can exceed the |
| 4140 | // cap at well under 123 characters. |
| 4141 | if (new TextEncoder().encode(String(reason)).length > 123) { |
| 4142 | throw new DOMException( |
| 4143 | "WebSocket close reason must not exceed 123 bytes", |
| 4144 | "SyntaxError"); |
| 4145 | } |
| 4146 | // Outbound sockets follow the WebSocket spec: closing a closed socket is a |
| 4147 | // no-op. Inbound sockets must NOT take that shortcut -- a Durable Object |
| 4148 | // answers a peer-initiated close from inside `webSocketClose`, by which |
| 4149 | // point `_dispatchClose` has already marked this side closed, and its |
| 4150 | // reply carries the reason the client is entitled to see. |
| 4151 | if (this._outbound && this.readyState === WebSocket.READY_STATE_CLOSED) { |
| 4152 | return; |
| 4153 | } |
| 4154 | const connecting = this.readyState === WebSocket.READY_STATE_CONNECTING; |
| 4155 | this.readyState = WebSocket.READY_STATE_CLOSING; |
| 4156 | if (this._outbound && connecting) { |
| 4157 | this._pendingClose = [code, reason]; |
| 4158 | return; |
| 4159 | } |
| 4160 | if (this._outbound) { |
| 4161 | __ws_close(this._id, code, reason); |
| 4162 | return; |
| 4163 | } |
| 4164 | this.readyState = 3; |
| 4165 | if (this._loopback) { |
| 4166 | const peer = this._loopback; |
| 4167 | queueMicrotask(() => peer._dispatchClose(code, reason, true)); |
| 4168 | return; |
| 4169 | } |
| 4170 | if (this._accepted && !this._target) { |
| 4171 | this._pending.push(["close", code, reason]); |
| 4172 | return; |
| 4173 | } |
| 4174 | __ws_close(this._id, code, reason); |
| 4175 | } |
| 4176 | _flushPending() { |
| 4177 | const pending = this._pending.splice(0); |
| 4178 | for (const frame of pending) { |
| 4179 | if (frame[0] === "send") __ws_send(this._id, frame[1]); |
| 4180 | else if (frame[0] === "send-binary") { |
| 4181 | const data = frame[1]; |
| 4182 | const bytes = data instanceof ArrayBuffer |
| 4183 | ? new Uint8Array(data) |
| 4184 | : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); |
| 4185 | __ws_send_binary(this._id, bytes); |
| 4186 | } |
| 4187 | else __ws_close(this._id, frame[1], frame[2]); |
| 4188 | } |
| 4189 | } |
| 4190 | serializeAttachment(value) { |
| 4191 | this._attachment = value; |
| 4192 | __ws_attachment_set(this._id, JSON.stringify(value)); |
| 4193 | } |
| 4194 | deserializeAttachment() { return this._attachment; } |
| 4195 | _dispatchMessage(data) { |
| 4196 | if (this._binaryType === "blob" && data instanceof ArrayBuffer) { |
| 4197 | data = new Blob([data]); |
| 4198 | } |
| 4199 | const event = new MessageEvent("message", { data }); |
| 4200 | event._trust(); |
| 4201 | this.dispatchEvent(event); |
| 4202 | } |
| 4203 | _dispatchClose(code, reason, wasClean) { |
| 4204 | if (this.readyState === WebSocket.READY_STATE_CLOSED) return; |
| 4205 | this.readyState = WebSocket.READY_STATE_CLOSED; |
| 4206 | __sockets.delete(this._id); |
| 4207 | // An abnormal closure fires `error` before `close`. Code written against |
| 4208 | // the standard onerror never ran otherwise, which matters most for an |
| 4209 | // outbound socket: its peer is a remote server that can simply vanish. |
| 4210 | // An abnormal closure fires `error` before `close`. Code written against |
| 4211 | // the standard onerror never ran otherwise, which matters most for an |
| 4212 | // outbound socket: its peer is a remote server that can simply vanish. |
| 4213 | // An abnormal closure fires `error` before `close`. Code written against |
| 4214 | // the standard onerror never ran otherwise, which matters most for an |
| 4215 | // outbound socket: its peer is a remote server that can simply vanish. |
| 4216 | if (!wasClean) { |
| 4217 | this.dispatchEvent(new ErrorEvent("error", { |
| 4218 | message: reason |
| 4219 | ? `WebSocket closed abnormally: ${reason}` |
| 4220 | : "WebSocket closed abnormally", |
| 4221 | })); |
| 4222 | } |
| 4223 | const event = new CloseEvent("close", { code, reason, wasClean }); |
| 4224 | event._trust(); |
| 4225 | this.dispatchEvent(event); |
| 4226 | } |
| 4227 | }; |
| 4228 | globalThis.__makeSocket = (id) => new WebSocket(id); |
| 4229 | globalThis.__socketFromRow = (row) => { |
| 4230 | let ws = __sockets.get(Number(row.id)); |
| 4231 | if (!ws) { |
| 4232 | ws = __makeSocket(row.id); |
| 4233 | __sockets.set(Number(row.id), ws); |
| 4234 | } |
| 4235 | ws._tags = row.tags || []; |
| 4236 | ws._hibernatable = true; |
| 4237 | if (row.attachment != null) { |
| 4238 | try { ws._attachment = JSON.parse(row.attachment); } catch { ws._attachment = undefined; } |
| 4239 | } |
| 4240 | return ws; |
| 4241 | }; |
| 4242 | globalThis.WebSocketPair = function WebSocketPair() { |
| 4243 | const id = __ws_alloc(); |
| 4244 | const client = __makeSocket(id); |
| 4245 | const server = __makeSocket(id); |
| 4246 | client._peer = server; |
| 4247 | server._peer = client; |
| 4248 | // Indexed AND iterable: `const [client, server] = new WebSocketPair()` is |
| 4249 | // the form most Cloudflare code uses. |
| 4250 | return { |
| 4251 | 0: client, |
| 4252 | 1: server, |
| 4253 | length: 2, |
| 4254 | [Symbol.iterator]() { |
| 4255 | return [client, server][Symbol.iterator](); |
| 4256 | }, |
| 4257 | }; |
| 4258 | }; |
| 4259 | if (!globalThis.performance) |
| 4260 | globalThis.performance = { now: () => Date.now(), timeOrigin: 0, mark() {}, measure() {} }; |
| 4261 | if (!globalThis.navigator) globalThis.navigator = { |
| 4262 | userAgent: "Cloudflare-Workers", hardwareConcurrency: 1, |
| 4263 | language: "en", languages: ["en"], |
| 4264 | }; |
| 4265 | if (!globalThis.queueMicrotask) |
| 4266 | globalThis.queueMicrotask = (f) => Promise.resolve().then(f); |
| 4267 | if (!globalThis.scheduler) |
| 4268 | globalThis.scheduler = { |
| 4269 | wait: (ms) => new Promise((resolve) => setTimeout(resolve, Number(ms) || 0)), |
| 4270 | }; |
| 4271 | if (!globalThis.structuredClone) { |
| 4272 | globalThis.structuredClone = (value, options) => { |
| 4273 | const seen = new Map(); |
| 4274 | const clone = (input) => { |
| 4275 | if (input === null || typeof input !== "object") return input; |
| 4276 | if (seen.has(input)) return seen.get(input); |
| 4277 | if (input instanceof Date) return new Date(input.getTime()); |
| 4278 | if (input instanceof ArrayBuffer) return input.slice(0); |
| 4279 | if (ArrayBuffer.isView(input)) |
| 4280 | return new input.constructor(input.buffer.slice( |
| 4281 | input.byteOffset, input.byteOffset + input.byteLength, |
| 4282 | )); |
| 4283 | if (input instanceof Map) { |
| 4284 | const out = new Map(); seen.set(input, out); |
| 4285 | for (const [k, v] of input) out.set(clone(k), clone(v)); |
| 4286 | return out; |
| 4287 | } |
| 4288 | if (input instanceof Set) { |
| 4289 | const out = new Set(); seen.set(input, out); |
| 4290 | for (const v of input) out.add(clone(v)); |
| 4291 | return out; |
| 4292 | } |
| 4293 | const out = Array.isArray(input) ? [] : Object.create(Object.getPrototypeOf(input)); |
| 4294 | seen.set(input, out); |
| 4295 | for (const key of Reflect.ownKeys(input)) out[key] = clone(input[key]); |
| 4296 | return out; |
| 4297 | }; |
| 4298 | const result = clone(value); |
| 4299 | // Transfer semantics: the source buffer is detached. The clone |
| 4300 | // above already copied its bytes, which is what the spec's |
| 4301 | // "transferred" clone observes. |
| 4302 | for (const item of (options && options.transfer) || []) { |
| 4303 | if (item instanceof ArrayBuffer) item.transfer(); |
| 4304 | } |
| 4305 | return result; |
| 4306 | }; |
| 4307 | } |
| 4308 | // Web Crypto is installed after the rest of the harness so it can use |
| 4309 | // DOMException, structuredClone, and Buffer. |
| 4310 | // `Buffer` is read at call time, which materializes the lazy global. |
| 4311 | const __zlibSync = (mode, data) => Buffer.from(JSON.parse(__zlib( |
| 4312 | mode, |
| 4313 | JSON.stringify(Array.from(Buffer.from(data))), |
| 4314 | ))); |
| 4315 | globalThis.__zlibModule = { |
| 4316 | constants: { |
| 4317 | Z_NO_FLUSH: 0, |
| 4318 | Z_PARTIAL_FLUSH: 1, |
| 4319 | Z_SYNC_FLUSH: 2, |
| 4320 | Z_FULL_FLUSH: 3, |
| 4321 | Z_FINISH: 4, |
| 4322 | Z_BLOCK: 5, |
| 4323 | }, |
| 4324 | gzipSync: (data, _options) => __zlibSync("gzip", data), |
| 4325 | gunzipSync: (data, _options) => __zlibSync("gunzip", data), |
| 4326 | deflateSync: (data, _options) => __zlibSync("deflate", data), |
| 4327 | inflateSync: (data, _options) => __zlibSync("inflate", data), |
| 4328 | deflateRawSync: (data, _options) => __zlibSync("deflateRaw", data), |
| 4329 | inflateRawSync: (data, _options) => __zlibSync("inflateRaw", data), |
| 4330 | }; |
| 4331 | if (!globalThis.process) globalThis.process = { |
| 4332 | env: {}, platform: "linux", arch: "x64", version: "v20.0.0", |
| 4333 | versions: { node: "20.0.0" }, argv: [], cwd: () => "/", |
| 4334 | stdin: { fd: 0, isTTY: false }, |
| 4335 | stdout: { fd: 1, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 4336 | stderr: { fd: 2, isTTY: false, write: (s) => { __log(String(s)); return true; } }, |
| 4337 | nextTick: (f, ...a) => queueMicrotask(() => f(...a)), |
| 4338 | on() {}, once() {}, off() {}, emit() {}, hrtime: () => [0, 0], |
| 4339 | }; |
| 4340 | globalThis.process.exit = (code = 0) => { |
| 4341 | const actorScope = __actorEventStack[__actorEventStack.length - 1] || ""; |
| 4342 | if (actorScope) { |
| 4343 | const instance = __cell.instances[actorScope]; |
| 4344 | if (instance?.__celldState) |
| 4345 | instance.__celldState._resetAfterConcurrencyFailure(); |
| 4346 | } |
| 4347 | __process_exit(Number(code) || 0, actorScope); |
| 4348 | }; |
| 4349 | globalThis.process.getBuiltinModule = |
| 4350 | (id) => __builtin_module(String(id)); |
| 4351 | if (!globalThis.global) globalThis.global = globalThis; |
| 4352 | const __eventStack = []; |
| 4353 | globalThis.__registerWaitUntil = (promise) => { |
| 4354 | const event = __eventStack[__eventStack.length - 1]; |
| 4355 | const tracked = Promise.resolve(promise).catch((error) => { |
| 4356 | console.error("waitUntil rejected", error); |
| 4357 | }); |
| 4358 | if (event) event.waitUntil.push(tracked); |
| 4359 | }; |
| 4360 | // `props` are the per-stub props a loopback service stub carries |
| 4361 | // (ctx.props); `exports` is built once, on first access. |
| 4362 | const __defaultProps = {}; |
| 4363 | globalThis.__beginEvent = (props = __defaultProps) => { |
| 4364 | const event = { waitUntil: [] }; |
| 4365 | __eventStack.push(event); |
| 4366 | return { |
| 4367 | waitUntil: globalThis.__registerWaitUntil, |
| 4368 | passThroughOnException() {}, |
| 4369 | abort: __ctxAbortCurrent, |
| 4370 | props, |
| 4371 | get exports() { return __ctxExports(); }, |
| 4372 | }; |
| 4373 | }; |
| 4374 | globalThis.__endEvent = () => { |
| 4375 | const event = __eventStack.pop(); |
| 4376 | if (!event || event.waitUntil.length === 0) return null; |
| 4377 | return Promise.allSettled(event.waitUntil); |
| 4378 | }; |
| 4379 | // fs stub that behaves like a no-filesystem env: reads throw ENOENT and |
| 4380 | // existsSync is false, so the common `try { readFileSync } catch (ENOENT)` |
| 4381 | // fallbacks in real deps (e.g. pi-agent config) take their default path. |
| 4382 | const __enoent = () => { const e = new Error("ENOENT: no filesystem"); e.code = "ENOENT"; throw e; }; |
| 4383 | globalThis.__fs = new Proxy({}, { get: (_t, p) => { |
| 4384 | if (p === "existsSync") return () => false; |
| 4385 | if (["readFileSync", "readdirSync", "statSync", "lstatSync", "realpathSync", "readlinkSync"].includes(p)) return __enoent; |
| 4386 | return globalThis.__nodeStub; |
| 4387 | }}); |
| 4388 | const __bridgeResponseStream = (body, requestControllers) => { |
| 4389 | const streamId = __response_stream_create(); |
| 4390 | const pump = (async () => { |
| 4391 | const reader = body.getReader(); |
| 4392 | const consumerClosed = __response_stream_closed(streamId) |
| 4393 | .then((status) => status === "cancelled" |
| 4394 | ? { consumerClosed: true } |
| 4395 | : new Promise(() => {})); |
| 4396 | const cancelProducer = async () => { |
| 4397 | const reason = new Error("The client has disconnected"); |
| 4398 | for (const controller of requestControllers || []) { |
| 4399 | if (!controller.signal.aborted) controller.abort(reason); |
| 4400 | } |
| 4401 | try { |
| 4402 | await reader.cancel(reason); |
| 4403 | } catch {} |
| 4404 | await __response_stream_close(streamId, ""); |
| 4405 | }; |
| 4406 | try { |
| 4407 | for (;;) { |
| 4408 | const result = await Promise.race([ |
| 4409 | reader.read().then((read) => ({ read })), |
| 4410 | consumerClosed, |
| 4411 | ]); |
| 4412 | if (result.consumerClosed) { |
| 4413 | await cancelProducer(); |
| 4414 | return; |
| 4415 | } |
| 4416 | if (result.read.done) { |
| 4417 | await __response_stream_close(streamId, ""); |
| 4418 | return; |
| 4419 | } |
| 4420 | const bytes = __bodyBytes(result.read.value); |
| 4421 | for (let offset = 0; offset < bytes.byteLength; offset += 64 * 1024) { |
| 4422 | await __response_stream_write( |
| 4423 | streamId, |
| 4424 | bytes.subarray(offset, offset + 64 * 1024), |
| 4425 | ); |
| 4426 | } |
| 4427 | } |
| 4428 | } catch (error) { |
| 4429 | if (String(error).includes("response stream consumer canceled")) { |
| 4430 | await cancelProducer(); |
| 4431 | return; |
| 4432 | } |
| 4433 | await __response_stream_close(streamId, String(error)); |
| 4434 | } |
| 4435 | })(); |
| 4436 | globalThis.__registerWaitUntil(pump); |
| 4437 | return streamId; |
| 4438 | }; |
| 4439 | globalThis.__readResponse = (r) => { |
| 4440 | if (!(r instanceof Response)) { |
| 4441 | return { |
| 4442 | status: 200, |
| 4443 | bodyBytes: new TextEncoder().encode(String(r)), |
| 4444 | bodyStreamId: 0, |
| 4445 | headersJson: "[]", |
| 4446 | wsTargetJson: "null", |
| 4447 | }; |
| 4448 | } |
| 4449 | const bodyStreamId = r._bodyBytes === null |
| 4450 | ? typeof r.body?.__celldStreamId === "number" && |
| 4451 | !r.__celldRequestControllers |
| 4452 | ? r.body.__celldStreamId |
| 4453 | : __bridgeResponseStream( |
| 4454 | r.body, |
| 4455 | r.__celldRequestControllers, |
| 4456 | ) |
| 4457 | : 0; |
| 4458 | if (bodyStreamId) { |
| 4459 | return { |
| 4460 | status: r.status, |
| 4461 | bodyBytes: new Uint8Array(), |
| 4462 | bodyStreamId, |
| 4463 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 4464 | wsTargetJson: JSON.stringify( |
| 4465 | r._wsTarget || (r.webSocket && r.webSocket._target) || null, |
| 4466 | ), |
| 4467 | }; |
| 4468 | } |
| 4469 | const bytes = r._bodyBytes; |
| 4470 | return { |
| 4471 | status: r.status, |
| 4472 | bodyBytes: bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), |
| 4473 | bodyStreamId: 0, |
| 4474 | headersJson: JSON.stringify(Array.from(r.headers)), |
| 4475 | wsTargetJson: JSON.stringify( |
| 4476 | r._wsTarget || (r.webSocket && r.webSocket._target) || null, |
| 4477 | ), |
| 4478 | }; |
| 4479 | }; |