exoagent 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "capnweb",
3
+ "version": "0.4.0",
4
+ "description": "JavaScript/TypeScript-native RPC library with Promise Pipelining",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "author": "Kenton Varda <kenton@cloudflare.com>",
8
+ "license": "MIT",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": {
16
+ "workerd": "./dist/index-workers.js",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "workerd": "./dist/index-workers.cjs",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ }
24
+ },
25
+ "type": "module",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup --format esm,cjs",
31
+ "build:watch": "tsup --watch --format esm,cjs",
32
+ "test": "vitest run",
33
+ "test:watch": "vitest",
34
+ "prepublishOnly": "npm run build"
35
+ },
36
+ "devDependencies": {
37
+ "@changesets/changelog-github": "^0.5.2",
38
+ "@changesets/cli": "^2.29.8",
39
+ "@cloudflare/vitest-pool-workers": "^0.10.15",
40
+ "@cloudflare/workers-types": "^4.20251216.0",
41
+ "@types/ws": "^8.18.1",
42
+ "@vitest/browser": "^3.2.4",
43
+ "pkg-pr-new": "^0.0.60",
44
+ "playwright": "^1.56.1",
45
+ "tsup": "^8.5.1",
46
+ "tsx": "^4.21.0",
47
+ "typescript": "^5.9.3",
48
+ "vitest": "^3.2.4",
49
+ "ws": "^8.18.3"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/cloudflare/capnweb"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/cloudflare/capnweb/issues"
57
+ },
58
+ "homepage": "https://github.com/cloudflare/capnweb#readme"
59
+ }
@@ -1,4 +1,4 @@
1
- import { RpcSessionOptions, RpcStub, RpcTarget, RpcTransport, RpcSession } from '../dist/capnweb';
1
+ import { RpcSessionOptions, RpcStub, RpcTarget, RpcTransport, RpcSession } from '../packages/capnweb/dist';
2
2
  declare class TestTransport implements RpcTransport {
3
3
  name: string;
4
4
  private partner?;
@@ -1,5 +1,5 @@
1
1
  import { Tool, ToolExecutionOptions } from 'ai';
2
- import { RpcTarget } from '../dist/capnweb';
2
+ import { RpcTarget } from '../packages/capnweb/dist';
3
3
  import { RpcToolset } from './rpc-toolset';
4
4
  import { z } from 'zod';
5
5
  export type SafeEvalResult = {
package/dist/index.mjs CHANGED
@@ -49,7 +49,7 @@ function createDenoSandbox(options = {}) {
49
49
  })`
50
50
  };
51
51
  }
52
- const runtimeCode = '// src/code-mode-runtime.ts\nimport { RpcSession, setGlobalRpcSessionOptions } from "capnweb";\n\n// src/stream-transport.ts\nfunction concatBuffers(a, b) {\n const result = new Uint8Array(a.length + b.length);\n result.set(a, 0);\n result.set(b, a.length);\n return result;\n}\nvar BufferedReader = class {\n buffer;\n reader;\n constructor(input) {\n this.buffer = new Uint8Array(0);\n this.reader = input.getReader();\n }\n async read(numberOfBytes) {\n if (numberOfBytes <= 0) {\n throw new Error("numberOfBytes must be positive");\n }\n while (this.buffer.length < numberOfBytes) {\n const result2 = await this.reader.read();\n if (result2.done || result2.value == null) {\n throw new Error("Stream closed");\n }\n this.buffer = concatBuffers(this.buffer, result2.value);\n }\n const result = this.buffer.slice(0, numberOfBytes);\n this.buffer = this.buffer.slice(numberOfBytes);\n return result;\n }\n};\nvar StreamTransport = class {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n this.bufferReader = new BufferedReader(input);\n this.writer = output.getWriter();\n }\n bufferReader;\n writer;\n async send(message) {\n const encoder = new TextEncoder();\n const messageBytes = encoder.encode(message);\n const length = messageBytes.length;\n if (length > 4294967295) {\n throw new Error("Message length exceeds maximum allowed size (4GB)");\n }\n const lengthBytes = new Uint8Array(4);\n const view = new DataView(lengthBytes.buffer);\n view.setUint32(0, length, true);\n const combined = new Uint8Array(4 + length);\n combined.set(lengthBytes, 0);\n combined.set(messageBytes, 4);\n await this.writer.write(combined);\n }\n async receive() {\n const lengthBytes = await this.bufferReader.read(4);\n const lengthBuffer = new Uint8Array(lengthBytes).buffer;\n const length = new DataView(lengthBuffer).getUint32(0, true);\n if (length > 100 * 1024 * 1024) {\n throw new Error("Message length exceeds maximum allowed size");\n }\n if (length === 0) {\n return "";\n }\n const messageBytes = await this.bufferReader.read(length);\n const decoder = new TextDecoder();\n return decoder.decode(messageBytes);\n }\n abort(reason) {\n this.input.cancel(reason).catch(() => {\n });\n this.writer.close().catch(() => {\n });\n }\n};\n\n// src/code-mode-runtime.ts\nsetGlobalRpcSessionOptions(() => ({ recordReplayMode: "all" }));\nasync function run(context) {\n const transport = new StreamTransport(context.input, context.output);\n try {\n const session = new RpcSession(transport);\n const api = session.getRemoteMain();\n const code = await api.__code__();\n const fn = new Function("api", `return (${code})(api)`);\n const result = await fn(api);\n await api.__return__(result);\n } finally {\n transport.abort("done");\n }\n}\nasync function main() {\n if (!__SANDBOX_CONTEXT_PROMISE__) {\n throw new TypeError("__SANDBOX_CONTEXT_PROMISE__ was not replaced prior to execution.");\n }\n const ctx = await __SANDBOX_CONTEXT_PROMISE__;\n const { input, output, onSuccess, onFailure } = ctx;\n return run({ input, output }).then(() => {\n onSuccess();\n }).catch((err) => {\n console.error("runtime error", err);\n onFailure();\n });\n}\nmain();\n';
52
+ const runtimeCode = '// packages/capnweb/dist/index.js\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");\nif (!Symbol.dispose) {\n Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose");\n}\nif (!Symbol.asyncDispose) {\n Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose");\n}\nif (!Promise.withResolvers) {\n Promise.withResolvers = function() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n };\n}\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nvar getGlobalRpcSessionOptions = () => ({});\nvar setGlobalRpcSessionOptions = (options) => {\n getGlobalRpcSessionOptions = options;\n};\nvar CALLBACK_CLEANUP = /* @__PURE__ */ Symbol("callback-cleanup");\nfunction typeForRpc(value) {\n switch (typeof value) {\n case "boolean":\n case "number":\n case "string":\n return "primitive";\n case "undefined":\n return "undefined";\n case "object":\n case "function":\n break;\n case "bigint":\n return "bigint";\n default:\n return "unsupported";\n }\n if (value === null) {\n return "primitive";\n }\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return "object";\n case Function.prototype:\n case AsyncFunction.prototype:\n return "function";\n case Array.prototype:\n return "array";\n case Date.prototype:\n return "date";\n case Uint8Array.prototype:\n return "bytes";\n // TODO: All other structured clone types.\n case RpcStub.prototype:\n return "stub";\n case RpcPromise.prototype:\n return "rpc-promise";\n // TODO: Promise<T> or thenable\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) {\n return "rpc-target";\n } else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) {\n return "rpc-thenable";\n }\n }\n if (value instanceof RpcTarget) {\n return "rpc-target";\n }\n if (value instanceof Error) {\n return "error";\n }\n return "unsupported";\n }\n}\nfunction mapNotLoaded() {\n throw new Error("RPC map() implementation was not loaded.");\n}\nvar mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded, recordCallback: mapNotLoaded };\nvar StubHook = class {\n};\nvar ErrorStubHook = class extends StubHook {\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n return this;\n }\n map(path, captures, instructions) {\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(\n new Error("Attempted to use RPC stub after it has been disposed.")\n);\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol("realStub");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise(doCall(\n stub.hook,\n stub.pathIfPromise || [],\n RpcPayload.fromAppParams(argumentsList)\n ), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return stub;\n } else if (prop in RpcPromise.prototype) {\n return stub[prop];\n } else if (typeof prop === "string") {\n return new RpcPromise(\n stub.hook,\n stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]\n );\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n } else {\n return void 0;\n }\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return true;\n } else if (prop in RpcPromise.prototype) {\n return prop in stub;\n } else if (typeof prop === "string") {\n return true;\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return true;\n } else {\n return false;\n }\n },\n construct(target, args) {\n throw new Error("An RPC stub cannot be used as a constructor.");\n },\n defineProperty(target, property, attributes) {\n throw new Error("Can\'t define properties on RPC stubs.");\n },\n deleteProperty(target, p) {\n throw new Error("Can\'t delete properties on RPC stubs.");\n },\n getOwnPropertyDescriptor(target, p) {\n return void 0;\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error("Can\'t assign properties on RPC stubs.");\n },\n setPrototypeOf(target, v) {\n throw new Error("Can\'t override prototype of RPC stubs.");\n }\n};\nvar RpcStub = class _RpcStub extends RpcTarget {\n // Although `hook` and `path` are declared `public` here, they are effectively hidden by the\n // proxy.\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget || value instanceof Function) {\n hook = TargetStubHook.create(value, void 0);\n } else {\n hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n }\n if (pathIfPromise) {\n throw new TypeError("RpcStub constructor expected one argument, received two.");\n }\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) {\n return new _RpcStub(target.hook.get(target.pathIfPromise));\n } else {\n return new _RpcStub(target.hook.dup());\n }\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return "[object RpcStub]";\n }\n};\nvar RpcPromise = class extends RpcStub {\n // TODO: Support passing target value or promise to constructor.\n constructor(hook, pathIfPromise) {\n super(hook, pathIfPromise);\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return "[object RpcPromise]";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return hook.get(pathIfPromise);\n } else {\n return hook;\n }\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) {\n return hook.get(pathIfPromise);\n } else {\n return hook.dup();\n }\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return void 0;\n }\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) {\n hook = hook.get(pathIfPromise);\n }\n let payload = await hook.pull();\n return payload.deliverResolve();\n}\nvar RpcPayload = class _RpcPayload {\n // Private constructor; use factory functions above to construct.\n constructor(value, source, stubs, promises) {\n this.value = value;\n this.source = source;\n this.stubs = stubs;\n this.promises = promises;\n }\n // Create a payload from a value passed as params to an RPC from the app.\n //\n // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify\n // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not\n // to have the sender and recipient end up sharing the same mutable object. `value` will not be\n // touched again after the call returns synchronously (returns a promise) -- by that point,\n // the value has either been copied or serialized to the wire.\n static fromAppParams(value) {\n return new _RpcPayload(value, "params");\n }\n // Create a payload from a value return from an RPC implementation by the app.\n //\n // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and\n // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It\n // will still avoid modifying `value` and will make a deep copy if it is delivered locally.\n static fromAppReturn(value) {\n return new _RpcPayload(value, "return");\n }\n // Combine an array of payloads into a single payload whose value is an array. Ownership of all\n // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the\n // inputs should not be. (In case of exception, nothing is disposed, though.)\n static fromArray(array) {\n let stubs = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let stub of payload.stubs) {\n stubs.push(stub);\n }\n for (let promise of payload.promises) {\n if (promise.parent === payload) {\n promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n }\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new _RpcPayload(resultArray, "owned", stubs, promises);\n }\n // Create a payload from a value parsed off the wire using Evaluator.evaluate().\n //\n // A payload is constructed with a null value and the given stubs and promises arrays. The value\n // is expected to be filled in by the evaluator, and the stubs and promises arrays are expected\n // to be extended with stubs found during parsing. (This weird usage model is necessary so that\n // if the root value turns out to be a promise, its `parent` in `promises` can be the payload\n // object itself.)\n //\n // When done, the payload takes ownership of the final value and all the stubs within. It may\n // modify the value in preparation for delivery, and may deliver the value directly to the app\n // without copying.\n static forEvaluate(stubs, promises) {\n return new _RpcPayload(null, "owned", stubs, promises);\n }\n // Deep-copy the given value, including dup()ing all stubs.\n //\n // If `value` is a function, it should be bound to `oldParent` as its `this`.\n //\n // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure\n // RpcTargets found within don\'t get duplicate stubs.\n static deepCopyFrom(value, oldParent, owner) {\n let result = new _RpcPayload(null, "owned", [], []);\n result.value = result.deepCopy(\n value,\n oldParent,\n "value",\n result,\n /*dupStubs=*/\n true,\n owner\n );\n return result;\n }\n // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets\n // found in the payload at the time that it is serialized (or deep-copied) for return, so that we\n // can make sure they are not disposed before the pipeline ends.\n //\n // This is initialized on first use.\n rpcTargets;\n // Get the StubHook representing the given RpcTarget found inside this payload.\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === "params") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === "function") {\n target = dupable.dup();\n }\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === "return") {\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n if (dupStubs) {\n return hook.dup();\n } else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n } else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error("owned payload shouldn\'t contain raw RpcTargets");\n }\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n return value;\n case "primitive":\n case "bigint":\n case "date":\n case "bytes":\n case "error":\n case "undefined":\n return value;\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n }\n return result;\n }\n case "object": {\n let result = {};\n let object = value;\n for (let i in object) {\n result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n }\n return result;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook;\n if (dupStubs) {\n hook = unwrapStubAndDup(stub);\n } else {\n hook = unwrapStubTakingOwnership(stub);\n }\n if (stub instanceof RpcPromise) {\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let newStub = new RpcStub(hook);\n this.stubs.push(newStub);\n return newStub;\n }\n }\n case "function":\n if (this.source === "owned" && typeof value === "function" && !(value instanceof RpcTarget)) {\n return value;\n }\n // Fall through to rpc-target handling\n case "rpc-target": {\n let target = value;\n let stub;\n if (owner) {\n stub = new RpcStub(owner.getHookForRpcTarget(target, oldParent, dupStubs));\n } else {\n stub = new RpcStub(TargetStubHook.create(target, oldParent));\n }\n this.stubs.push(stub);\n return stub;\n }\n case "rpc-thenable": {\n let target = value;\n let promise;\n if (owner) {\n promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n } else {\n promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);\n }\n this.promises.push({ parent, property, promise });\n return promise;\n }\n default:\n throw new Error("unreachable");\n }\n }\n // Ensures that if the value originally came from an unowned source, we have replaced it with a\n // deep copy.\n ensureDeepCopied() {\n if (this.source !== "owned") {\n let dupStubs = this.source === "params";\n this.stubs = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);\n } catch (err) {\n this.stubs = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = "owned";\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in deep-copy?");\n }\n this.rpcTargets = void 0;\n }\n }\n // Resolve all promises in this payload and then assign the final value into `parent[property]`.\n deliverTo(parent, property, promises) {\n const unwrapRpcTargets = (value) => {\n if (value instanceof RpcStub) {\n const { hook, pathIfPromise } = unwrapStubAndPath(value);\n if (pathIfPromise == null && hook instanceof TargetStubHook) {\n const target = hook.getTarget();\n return target;\n }\n }\n return value;\n };\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise) {\n _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);\n } else {\n const unwrapped = unwrapRpcTargets(this.value);\n parent[property] = unwrapped;\n for (let record of this.promises) {\n _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) {\n throw new Error("property promises should have been resolved earlier");\n }\n let inner = hook.pull();\n if (inner instanceof _RpcPayload) {\n inner.deliverTo(parent, property, promises);\n } else {\n promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) {\n return Promise.all(subPromises);\n }\n }));\n }\n }\n // Call the given function with the payload as an argument. The call is made synchronously if\n // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,\n // they are awaited and substituted before calling the function. The result of the call is\n // wrapped into another payload.\n //\n // The payload is automatically disposed after the call completes. The caller should not call\n // dispose().\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise) {\n return _RpcPayload.fromAppReturn(result);\n } else {\n return _RpcPayload.fromAppReturn(await result);\n }\n } finally {\n this.dispose();\n }\n }\n // Produce a promise for this payload for return to the application. Any RpcPromises in the\n // payload are awaited and substituted with their results first.\n //\n // The returned object will have a disposer which disposes the payload. The caller should not\n // separately dispose it.\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, "value", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) {\n Object.defineProperty(result, Symbol.dispose, {\n // NOTE: Using `this.dispose.bind(this)` here causes Playwright\'s build of\n // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,\n // with the error:\n // TypeError: Symbol(Symbol.dispose) is not a function\n // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,\n // so maybe it was a short-lived V8 bug or something. To be safe, though, we use\n // `() => this.dispose()`, which seems to always work.\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === "owned") {\n this.stubs.forEach((stub) => stub[Symbol.dispose]());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === "return") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) {\n throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");\n }\n } else ;\n this.source = "owned";\n this.stubs = [];\n this.promises = [];\n }\n // Recursive dispose, called only when `source` is "return".\n disposeImpl(value, parent) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.disposeImpl(array[i], array);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.disposeImpl(object[i], object);\n }\n return;\n }\n case "stub":\n case "rpc-promise": {\n let stub = value;\n let hook = unwrapStubNoProperties(stub);\n if (hook) {\n hook.dispose();\n }\n return;\n }\n case "function":\n case "rpc-target": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else {\n disposeRpcTarget(target);\n }\n return;\n }\n case "rpc-thenable":\n return;\n default:\n return;\n }\n }\n // Ignore unhandled rejections in all promises in this payload -- that is, all promises that\n // *would* be awaited if this payload were to be delivered. See the similarly-named method of\n // StubHook for explanation.\n ignoreUnhandledRejections() {\n if (this.stubs) {\n this.stubs.forEach((stub) => {\n unwrapStubOrParent(stub).ignoreUnhandledRejections();\n });\n this.promises.forEach(\n (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()\n );\n } else {\n this.ignoreUnhandledRejectionsImpl(this.value);\n }\n }\n ignoreUnhandledRejectionsImpl(value) {\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported":\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n case "undefined":\n case "function":\n case "rpc-target":\n return;\n case "array": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) {\n this.ignoreUnhandledRejectionsImpl(array[i]);\n }\n return;\n }\n case "object": {\n let object = value;\n for (let i in object) {\n this.ignoreUnhandledRejectionsImpl(object[i]);\n }\n return;\n }\n case "stub":\n case "rpc-promise":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case "rpc-thenable":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "object":\n case "function":\n if (Object.hasOwn(value, part)) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "array":\n if (Number.isInteger(part) && part >= 0) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case "rpc-target":\n case "rpc-thenable": {\n if (Object.hasOwn(value, part)) {\n throw new TypeError(\n `Attempted to access property \'${part}\', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`\n );\n } else {\n value = value[part];\n }\n owner = null;\n break;\n }\n case "stub":\n case "rpc-promise": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };\n }\n case "primitive":\n case "bigint":\n case "bytes":\n case "date":\n case "error":\n value = void 0;\n break;\n case "undefined":\n value = value[part];\n break;\n case "unsupported": {\n if (i === 0) {\n throw new TypeError(`RPC stub points at a non-serializable type.`);\n } else {\n let prefix = path.slice(0, i).join(".");\n let remainder = path.slice(0, i).join(".");\n throw new TypeError(\n `\'${prefix}\' is not a serializable type, so property ${remainder} cannot be accessed.`\n );\n }\n }\n default:\n throw new TypeError("unreachable");\n }\n }\n if (value instanceof RpcPromise) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise || [] };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n try {\n let { value, owner } = this.getValue();\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.call(followResult.remainingPath, args);\n }\n if (typeof followResult.value != "function") {\n throw new TypeError(`\'${path.join(".")}\' is not a function.`);\n }\n let promise = args.deliverCall(followResult.value, followResult.parent);\n return new PromiseStubHook(promise.then((payload) => {\n return new PayloadStubHook(payload);\n }));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n ;\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (followResult.hook) {\n return followResult.hook.map(followResult.remainingPath, captures, instructions);\n }\n return mapImpl.applyMap(\n followResult.value,\n followResult.parent,\n followResult.owner,\n captures,\n instructions\n );\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n throw new Error("Can\'t dup an RpcTarget stub as a promise.");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.get(followResult.remainingPath);\n }\n return new PayloadStubHook(RpcPayload.deepCopyFrom(\n followResult.value,\n followResult.parent,\n followResult.owner\n ));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class _PayloadStubHook extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n // cleared when disposed\n getPayload() {\n if (this.payload) {\n return this.payload;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n let payload = this.getPayload();\n return { value: payload.value, owner: payload };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new _PayloadStubHook(RpcPayload.deepCopyFrom(\n thisPayload.value,\n void 0,\n thisPayload\n ));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) {\n this.payload.ignoreUnhandledRejections();\n }\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub) {\n this.payload.value.onRpcBroken(callback);\n }\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) {\n try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n }\n}\nvar TargetStubHook = class _TargetStubHook extends ValueStubHook {\n // Constructs a TargetStubHook that is not duplicated from an existing hook.\n //\n // If `value` is a function, `parent` is bound as its "this".\n static create(value, parent) {\n if (typeof value !== "function") {\n parent = void 0;\n }\n return new _TargetStubHook(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) {\n this.refcount = { count: 1 };\n }\n }\n target;\n // cleared when disposed\n parent;\n // `this` parameter when calling `target`\n refcount;\n // undefined if not needed (because target has no disposer)\n getTarget() {\n if (this.target) {\n return this.target;\n } else {\n throw new Error("Attempted to use an RPC StubHook after it was disposed.");\n }\n }\n getValue() {\n return { value: this.getTarget(), owner: null };\n }\n dup() {\n return new _TargetStubHook(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if ("then" in target) {\n return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n } else {\n return Promise.reject(new Error("Tried to resolve a non-promise stub."));\n }\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) {\n disposeRpcTarget(this.target);\n }\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n }\n};\nvar PromiseStubHook = class _PromiseStubHook extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));\n }\n map(path, captures, instructions) {\n return new _PromiseStubHook(this.promise.then(\n (hook) => hook.map(path, captures, instructions),\n (err) => {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n ));\n }\n get(path) {\n return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) {\n return this.resolution.dup();\n } else {\n return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));\n }\n }\n pull() {\n if (this.resolution) {\n return this.resolution.pull();\n } else {\n return this.promise.then((hook) => hook.pull());\n }\n }\n ignoreUnhandledRejections() {\n if (this.resolution) {\n this.resolution.ignoreUnhandledRejections();\n } else {\n this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.promise.then((hook) => {\n hook.dispose();\n }, (err) => {\n });\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n }\n};\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) {\n this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n } else {\n this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n }\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push(\n [\n "remap",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => ["import", cap]),\n this.instructions\n ]\n );\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else {\n return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path, devalued]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push(["pipeline", subject, path]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) {\n return hook.idx;\n }\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else {\n this.context.captures.push(hook);\n }\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n // ---------------------------------------------------------------------------\n // implements Exporter\n exportStub(hook) {\n throw new Error(\n "Can\'t construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback."\n );\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error("RPC map() callbacks cannot be async.");\n }\n return new RpcPromise(builder.makeOutput(result), []);\n};\nmapImpl.recordCallback = (func) => {\n const builder = new MapBuilder(new PayloadStubHook(RpcPayload.fromAppParams([])), []);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n const devaluatedResult = Devaluator.devaluate(result.value, void 0, builder, result);\n const instructions = [...builder.instructions, devaluatedResult];\n const context = builder.context;\n if (context.parent) {\n return ["callback", context.captures.map((cap) => ["import", cap]), instructions];\n } else {\n return ["callback", context.captures, instructions];\n }\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\n "Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects."\n );\n}\nvar MapVariableHook = class extends StubHook {\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n // We don\'t have anything we actually need to dispose, so dup() can just return the same hook.\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) {\n return this;\n } else if (currentMapBuilder) {\n return currentMapBuilder.pushGet(this, path);\n } else {\n throwMapperBuilderUseError();\n }\n }\n // Other methods should never be called.\n call(path, args) {\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n variables;\n dispose() {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) {\n throw new Error("Invalid empty mapper function.");\n }\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n }\n importStub(idx) {\n throw new Error("A mapper function cannot refer to exports.");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) {\n return this.captures[-idx - 1];\n } else {\n return this.variables[idx];\n }\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));\n let mapper = new MapApplicator(captures, inputHook);\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise) {\n throw new Error("applyMap() can\'t be called on RpcPromise");\n } else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) {\n payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n }\n } catch (err) {\n for (let payload of payloads) {\n payload.dispose();\n }\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) {\n result = RpcPayload.fromAppReturn(input);\n } else {\n result = applyMapToElement(input, parent, owner, captures, instructions);\n }\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) {\n cap.dispose();\n }\n }\n};\nvar isExplicitCallback = (arg) => {\n return typeof arg === "function" && "serializationMode" in arg;\n};\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n exportPromise(stub) {\n throw new Error("Cannot serialize RPC stubs without an RPC session.");\n }\n getImport(hook) {\n return void 0;\n }\n unexport(ids) {\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nvar ERROR_TYPES = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n // TODO: DOMError? Others?\n};\nvar Devaluator = class _Devaluator {\n constructor(exporter, source) {\n this.exporter = exporter;\n this.source = source;\n }\n // Devaluate the given value.\n // * value: The value to devaluate.\n // * parent: The value\'s parent object, which would be used as `this` if the value were called\n // as a function.\n // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.\n // * source: The RpcPayload which contains the value, and therefore owns stubs within.\n //\n // Returns: The devaluated value, ready to be JSON-serialized.\n static devaluate(value, parent, exporter = NULL_EXPORTER, source) {\n let devaluator = new _Devaluator(exporter, source);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) {\n try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 64) {\n throw new Error(\n "Serialization exceeded maximum allowed depth. (Does the message contain cycles?)"\n );\n }\n let kind = typeForRpc(value);\n switch (kind) {\n case "unsupported": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = "Cannot serialize value: (couldn\'t stringify value)";\n }\n throw new TypeError(msg);\n }\n case "primitive":\n if (typeof value === "number" && !isFinite(value)) {\n if (value === Infinity) {\n return ["inf"];\n } else if (value === -Infinity) {\n return ["-inf"];\n } else {\n return ["nan"];\n }\n } else {\n return value;\n }\n case "object": {\n let object = value;\n let result = {};\n for (let key in object) {\n result[key] = this.devaluateImpl(object[key], object, depth + 1);\n }\n return result;\n }\n case "array": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.devaluateImpl(array[i], array, depth + 1);\n }\n return [result];\n }\n case "bigint":\n return ["bigint", value.toString()];\n case "date":\n return ["date", value.getTime()];\n case "bytes": {\n let bytes = value;\n if (bytes.toBase64) {\n return ["bytes", bytes.toBase64({ omitPadding: true })];\n } else {\n return [\n "bytes",\n btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))\n ];\n }\n }\n case "error": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) {\n e = rewritten;\n }\n let result = ["error", e.name, e.message];\n if (rewritten && rewritten.stack) {\n result.push(rewritten.stack);\n }\n return result;\n }\n case "undefined":\n return ["undefined"];\n case "stub":\n case "rpc-promise": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) {\n if (pathIfPromise) {\n if (pathIfPromise.length > 0) {\n return ["pipeline", importId, pathIfPromise];\n } else {\n return ["pipeline", importId];\n }\n } else {\n return ["import", importId];\n }\n }\n if (pathIfPromise) {\n hook = hook.get(pathIfPromise);\n } else {\n hook = hook.dup();\n }\n return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);\n }\n case "function":\n case "rpc-target": {\n let shouldRecordReplay = false;\n if (kind === "function") {\n if (isExplicitCallback(value)) {\n const explicitMode = value.serializationMode;\n shouldRecordReplay = explicitMode === "recordReplay";\n } else {\n shouldRecordReplay = getGlobalRpcSessionOptions().recordReplayMode === "all";\n }\n }\n if (shouldRecordReplay) {\n const res = mapImpl.recordCallback(value);\n const captures = res[1];\n if (captures.length === 0 || captures[0] instanceof StubHook) {\n const captureHooks = captures;\n const serializedCaptures = captureHooks.map((stub) => {\n const importId = this.exporter.getImport(stub);\n if (importId !== void 0) {\n return ["import", importId];\n } else {\n return ["export", this.exporter.exportStub(stub)];\n }\n });\n for (const hook2 of captureHooks) {\n hook2.dispose();\n }\n return ["callback", serializedCaptures, res[2]];\n } else {\n return res;\n }\n }\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("export", hook);\n }\n case "rpc-thenable": {\n if (!this.source) {\n throw new Error("Can\'t serialize RPC stubs in this context.");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook("promise", hook);\n }\n default:\n throw new Error("unreachable");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n importPromise(idx) {\n throw new Error("Cannot deserialize RPC stubs without an RPC session.");\n }\n getExport(idx) {\n return void 0;\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nvar Evaluator = class _Evaluator {\n constructor(importer) {\n this.importer = importer;\n }\n stubs = [];\n promises = [];\n // Resolve serialized captures to StubHooks. Used by both "callback" and "remap" evaluation.\n resolveCaptures(capsData) {\n return capsData.map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] !== "number") {\n throw new TypeError(`unknown capture: ${JSON.stringify(cap)}`);\n }\n if (cap[0] === "export") {\n return this.importer.importStub(cap[1]);\n } else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) {\n throw new Error(`no such entry on exports table: ${cap[1]}`);\n }\n return exp.dup();\n }\n });\n }\n evaluate(value) {\n let payload = RpcPayload.forEvaluate(this.stubs, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, "value");\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n // Evaluate the value without destroying it.\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property) {\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) {\n result[i] = this.evaluateImpl(result[i], result, i);\n }\n return result;\n } else switch (value[0]) {\n case "callback": {\n if (value.length < 3 || !(value[1] instanceof Array) || !(value[2] instanceof Array)) {\n break;\n }\n const captures = this.resolveCaptures(value[1]);\n const instructions = value[2];\n const replayFn = (arg) => {\n const capturesForThisCall = captures.map((c) => c.dup());\n const inputHook = new PayloadStubHook(RpcPayload.fromAppParams(arg));\n const applicator = new MapApplicator(capturesForThisCall, inputHook);\n const disposeInvocation = () => {\n applicator.dispose();\n for (const cap of capturesForThisCall) {\n cap.dispose();\n }\n const cleanup = replayFn[CALLBACK_CLEANUP];\n if (typeof cleanup === "function") {\n cleanup();\n }\n };\n let resultPayload;\n try {\n resultPayload = applicator.apply(instructions);\n } catch (err) {\n disposeInvocation();\n throw err;\n }\n return resultPayload.deliverResolve().finally(disposeInvocation);\n };\n replayFn[CALLBACK_CLEANUP] = () => {\n for (const cap of captures) {\n cap.dispose();\n }\n };\n return replayFn;\n }\n case "bigint":\n if (typeof value[1] == "string") {\n return BigInt(value[1]);\n }\n break;\n case "date":\n if (typeof value[1] == "number") {\n return new Date(value[1]);\n }\n break;\n case "bytes": {\n let b64 = Uint8Array;\n if (typeof value[1] == "string") {\n if (b64.fromBase64) {\n return b64.fromBase64(value[1]);\n } else {\n let bs = atob(value[1]);\n let len = bs.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = bs.charCodeAt(i);\n }\n return bytes;\n }\n }\n break;\n }\n case "error":\n if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = new cls(value[2]);\n if (typeof value[3] === "string") {\n result.stack = value[3];\n }\n return result;\n }\n break;\n case "undefined":\n if (value.length === 1) {\n return void 0;\n }\n break;\n case "inf":\n return Infinity;\n case "-inf":\n return -Infinity;\n case "nan":\n return NaN;\n case "import":\n case "pipeline": {\n if (value.length < 2 || value.length > 4) {\n break;\n }\n if (typeof value[1] != "number") {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let isPromise = value[0] == "pipeline";\n let addStub = (hook2) => {\n const unwrapped = maybeUnwrapStubHook(hook2);\n if (unwrapped) {\n hook2.dispose();\n return unwrapped;\n }\n if (isPromise) {\n let promise = new RpcPromise(hook2, []);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n let stub = new RpcPromise(hook2, []);\n this.stubs.push(stub);\n return stub;\n }\n };\n if (value.length == 2) {\n if (isPromise) {\n return addStub(hook.get([]));\n } else {\n return addStub(hook.dup());\n }\n }\n let path = value[2];\n if (!(path instanceof Array)) {\n break;\n }\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n if (value.length == 3) {\n return addStub(hook.get(path));\n }\n let args = value[3];\n if (!(args instanceof Array)) {\n break;\n }\n let subEval = new _Evaluator(this.importer);\n args = subEval.evaluate([args]);\n return addStub(hook.call(path, args));\n }\n case "remap": {\n if (value.length !== 5 || typeof value[1] !== "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let path = value[2];\n if (!path.every(\n (part) => {\n return typeof part == "string" || typeof part == "number";\n }\n )) {\n break;\n }\n let captures = this.resolveCaptures(value[3]);\n let instructions = value[4];\n let resultHook = hook.map(path, captures, instructions);\n let promise = new RpcPromise(resultHook, []);\n this.promises.push({ promise, parent, property });\n return promise;\n }\n case "export":\n case "promise":\n if (typeof value[1] == "number") {\n if (value[0] == "promise") {\n let hook = this.importer.importPromise(value[1]);\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n let stub = new RpcStub(hook);\n this.stubs.push(stub);\n return stub;\n }\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) {\n if (key in Object.prototype || key === "toJSON") {\n this.evaluateImpl(result[key], result, key);\n delete result[key];\n } else {\n result[key] = this.evaluateImpl(result[key], result, key);\n }\n }\n return result;\n } else {\n return value;\n }\n }\n};\nvar maybeUnwrapStubHook = (hook) => {\n if (!(hook instanceof PayloadStubHook)) {\n return void 0;\n }\n const payload = hook.getPayload();\n if (payload.value instanceof RpcStub) {\n const { hook: innerHook, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise == null && innerHook instanceof TargetStubHook) {\n return innerHook.getTarget();\n } else {\n return innerHook;\n }\n }\n return void 0;\n};\nvar ImportTableEntry = class {\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) {\n this.activePull = Promise.withResolvers();\n }\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on\n // this import. Initialized on first use (so `undefined` is the same as an empty list).\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) {\n delete this.session.onBrokenCallbacks[endIndex];\n } else {\n delete this.session.onBrokenCallbacks[i];\n }\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.abort(new Error("RPC was canceled because the RpcPromise was disposed."));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class _RpcImportHook extends StubHook {\n // undefined when we\'re disposed\n // `pulling` is true if we already expect that this import is going to be resolved later, and\n // null if this import is not allowed to be pulled (i.e. it\'s a stub not a promise).\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n entry;\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) {\n return this.entry;\n } else {\n throw new Error("This RpcImportHook was already disposed.");\n }\n }\n // -------------------------------------------------------------------------------------\n // implements StubHook\n call(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.call(path, args);\n } else {\n return entry.session.sendCall(entry.importId, path, args);\n }\n }\n map(path, captures, instructions) {\n let entry;\n try {\n entry = this.getEntry();\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (entry.resolution) {\n return entry.resolution.map(path, captures, instructions);\n } else {\n return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.get(path);\n } else {\n return entry.session.sendCall(entry.importId, path);\n }\n }\n dup() {\n return new _RpcImportHook(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) {\n throw new Error("Can\'t pull this hook because it\'s not a promise hook.");\n }\n if (entry.resolution) {\n return entry.resolution.pull();\n }\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) {\n entry.dispose();\n }\n }\n }\n onBroken(callback) {\n if (this.entry) {\n this.entry.onBroken(callback);\n }\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n this.exports.push({ hook: mainHook, refcount: 1 });\n this.imports.push(new ImportTableEntry(this, 0, false));\n let rejectFunc;\n let abortPromise = new Promise((resolve, reject) => {\n rejectFunc = reject;\n });\n this.cancelReadLoop = rejectFunc;\n this.readLoop(abortPromise).catch((err) => this.abort(err));\n }\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n // We assign positive numbers to imports we initiate, and negative numbers to exports we\n // initiate. So the next import ID is just `imports.length`, but the next export ID needs\n // to be tracked explicitly.\n nextExportId = -1;\n // If set, call this when all incoming calls are complete.\n onBatchDone;\n // How many promises is our peer expecting us to resolve?\n pullCount = 0;\n // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but\n // may be deleted from the middle (hence leaving the array sparse).\n onBrokenCallbacks = [];\n // Should only be called once immediately after construction.\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(new Error("RPC session was shut down by disposing the main stub"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) {\n this.releaseExport(id, 1);\n }\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (entry.refcount < refcount) {\n throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n }\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) {\n return this.options.onSendError(error);\n }\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n ++this.pullCount;\n exp.pull = resolve().then(\n (payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload);\n this.send(["resolve", exportId, value]);\n },\n (error) => {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n }\n ).catch(\n (error) => {\n try {\n this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);\n } catch (error2) {\n this.abort(error2);\n }\n }\n ).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) {\n this.onBatchDone.resolve();\n }\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) {\n return hook.entry.importId;\n } else {\n return void 0;\n }\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(\n /*isPromise=*/\n false,\n entry\n );\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) {\n return new ErrorStubHook(new Error(\n "Bug in RPC system: The peer sent a promise reusing an existing export ID."\n ));\n }\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n send(msg) {\n if (this.abortReason !== void 0) {\n return;\n }\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n this.transport.send(msgText).catch((err) => this.abort(err, false));\n }\n sendCall(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = ["pipeline", id, path];\n if (args) {\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n }\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw this.abortReason;\n }\n let devaluedCaptures = captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) {\n return ["import", importId];\n } else {\n return ["export", this.exportStub(hook)];\n }\n });\n let value = ["remap", id, path, devaluedCaptures, instructions];\n this.send(["push", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send(["pull", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send(["release", id, remoteRefcount]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop(error);\n if (trySendAbortMessage) {\n try {\n this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {\n });\n } catch (err) {\n }\n }\n if (error === void 0) {\n error = "undefined";\n }\n this.abortReason = error;\n if (this.onBatchDone) {\n this.onBatchDone.reject(error);\n }\n if (this.transport.abort) {\n try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.onBrokenCallbacks) {\n try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.imports) {\n this.imports[i].abort(error);\n }\n for (let i in this.exports) {\n this.exports[i].hook.dispose();\n }\n }\n async readLoop(abortPromise) {\n while (!this.abortReason) {\n let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));\n if (this.abortReason) break;\n if (msg instanceof Array) {\n switch (msg[0]) {\n case "push":\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n this.exports.push({ hook, refcount: 1 });\n continue;\n }\n break;\n case "pull": {\n let exportId = msg[1];\n if (typeof exportId == "number") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case "resolve":\n // ["resolve", ExportId, Expression]\n case "reject": {\n let importId = msg[1];\n if (typeof importId == "number" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) {\n if (msg[0] == "resolve") {\n imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));\n } else {\n let payload = new Evaluator(this).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n } else {\n if (msg[0] == "resolve") {\n new Evaluator(this).evaluate(msg[2]).dispose();\n }\n }\n continue;\n }\n break;\n }\n case "release": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == "number" && typeof refcount == "number") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case "abort": {\n let payload = new Evaluator(this).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload, false);\n break;\n }\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) {\n throw this.abortReason;\n }\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = { resolve, reject };\n await promise;\n }\n }\n getStats() {\n let result = { imports: 0, exports: 0 };\n for (let i in this.imports) {\n ++result.imports;\n }\n for (let i in this.exports) {\n ++result.exports;\n }\n return result;\n }\n};\nvar RpcSession = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) {\n mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n } else {\n mainHook = new ErrorStubHook(new Error("This connection has no main object."));\n }\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nvar RpcSession2 = RpcSession;\n\n// src/stream-transport.ts\nfunction concatBuffers(a, b) {\n const result = new Uint8Array(a.length + b.length);\n result.set(a, 0);\n result.set(b, a.length);\n return result;\n}\nvar BufferedReader = class {\n buffer;\n reader;\n constructor(input) {\n this.buffer = new Uint8Array(0);\n this.reader = input.getReader();\n }\n async read(numberOfBytes) {\n if (numberOfBytes <= 0) {\n throw new Error("numberOfBytes must be positive");\n }\n while (this.buffer.length < numberOfBytes) {\n const result2 = await this.reader.read();\n if (result2.done || result2.value == null) {\n throw new Error("Stream closed");\n }\n this.buffer = concatBuffers(this.buffer, result2.value);\n }\n const result = this.buffer.slice(0, numberOfBytes);\n this.buffer = this.buffer.slice(numberOfBytes);\n return result;\n }\n};\nvar StreamTransport = class {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n this.bufferReader = new BufferedReader(input);\n this.writer = output.getWriter();\n }\n bufferReader;\n writer;\n async send(message) {\n const encoder = new TextEncoder();\n const messageBytes = encoder.encode(message);\n const length = messageBytes.length;\n if (length > 4294967295) {\n throw new Error("Message length exceeds maximum allowed size (4GB)");\n }\n const lengthBytes = new Uint8Array(4);\n const view = new DataView(lengthBytes.buffer);\n view.setUint32(0, length, true);\n const combined = new Uint8Array(4 + length);\n combined.set(lengthBytes, 0);\n combined.set(messageBytes, 4);\n await this.writer.write(combined);\n }\n async receive() {\n const lengthBytes = await this.bufferReader.read(4);\n const lengthBuffer = new Uint8Array(lengthBytes).buffer;\n const length = new DataView(lengthBuffer).getUint32(0, true);\n if (length > 100 * 1024 * 1024) {\n throw new Error("Message length exceeds maximum allowed size");\n }\n if (length === 0) {\n return "";\n }\n const messageBytes = await this.bufferReader.read(length);\n const decoder = new TextDecoder();\n return decoder.decode(messageBytes);\n }\n abort(reason) {\n this.input.cancel(reason).catch(() => {\n });\n this.writer.close().catch(() => {\n });\n }\n};\n\n// src/code-mode-runtime.ts\nsetGlobalRpcSessionOptions(() => ({ recordReplayMode: "all" }));\nasync function run(context) {\n const transport = new StreamTransport(context.input, context.output);\n try {\n const session = new RpcSession2(transport);\n const api = session.getRemoteMain();\n const code = await api.__code__();\n const fn = new Function("api", `return (${code})(api)`);\n const result = await fn(api);\n await api.__return__(result);\n } finally {\n transport.abort("done");\n }\n}\nasync function main() {\n if (!__SANDBOX_CONTEXT_PROMISE__) {\n throw new TypeError("__SANDBOX_CONTEXT_PROMISE__ was not replaced prior to execution.");\n }\n const ctx = await __SANDBOX_CONTEXT_PROMISE__;\n const { input, output, onSuccess, onFailure } = ctx;\n return run({ input, output }).then(() => {\n onSuccess();\n }).catch((err) => {\n console.error("runtime error", err);\n onFailure();\n });\n}\nmain();\n';
53
53
  function concatBuffers(a, b) {
54
54
  const result = new Uint8Array(a.length + b.length);
55
55
  result.set(a, 0);
@@ -1,7 +1,32 @@
1
- import { RpcTarget } from "capnweb";
2
1
  import * as kysely0 from "kysely";
3
2
  import { CompiledQuery, Dialect, RawBuilder } from "kysely";
4
3
 
4
+ //#region packages/capnweb/dist/index.d.ts
5
+
6
+ declare const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
7
+ interface RpcTargetBranded {
8
+ [__RPC_TARGET_BRAND]: never;
9
+ }
10
+
11
+ // Types that can be used through `Stub`s
12
+
13
+ /**
14
+ * Classes which are intended to be passed by reference and called over RPC must extend
15
+ * `RpcTarget`. A class which does not extend `RpcTarget` (and which doesn't have built-in support
16
+ * from the RPC system) cannot be passed in an RPC message at all; an exception will be thrown.
17
+ *
18
+ * Note that on Cloudflare Workers, this `RpcTarget` is an alias for the one exported from the
19
+ * "cloudflare:workers" module, so they can be used interchangably.
20
+ */
21
+ interface RpcTarget extends RpcTargetBranded {}
22
+ declare const RpcTarget: {
23
+ new (): RpcTarget;
24
+ };
25
+ /**
26
+ * Empty interface used as default type parameter for sessions where the other side doesn't
27
+ * necessarily export a main interface.
28
+ */
29
+ //#endregion
5
30
  //#region src/rpc-toolset.d.ts
6
31
 
7
32
  declare const callbackMetadataKey: unique symbol;
@@ -81,8 +106,8 @@ type RowLikeRawIn = {
81
106
  };
82
107
  type RowLike = RowLikeRaw | TableBase;
83
108
  type RowLikeIn = RowLikeRawIn | RowLike;
84
- type AsRowLike<R extends RowLikeIn> = R extends TableBase ? R : { [key in keyof R]: R[key] extends SqlExpression ? R[key] : SqlExpression };
85
- type NamespacedExpression<A, R> = (arg: A) => R;
109
+ type AsRowLike<R$1 extends RowLikeIn> = R$1 extends TableBase ? R$1 : { [key in keyof R$1]: R$1[key] extends SqlExpression ? R$1[key] : SqlExpression };
110
+ type NamespacedExpression<A, R$1> = (arg: A) => R$1;
86
111
  type FromItem<N extends string, F extends RowLike> = {
87
112
  alias: N;
88
113
  toRowLike: () => F;
@@ -1,5 +1,5 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
- import { RpcTarget } from '../dist/capnweb';
2
+ import { RpcTarget } from '../packages/capnweb/dist';
3
3
  declare const toolMetadataKey: unique symbol;
4
4
  type ToolMetadata = {
5
5
  [toolMetadataKey]?: {
@@ -1,4 +1,4 @@
1
- import { RpcTransport } from '../dist/capnweb';
1
+ import { RpcTransport } from '../packages/capnweb/dist';
2
2
  export declare class StreamTransport implements RpcTransport {
3
3
  private input;
4
4
  private output;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "exoagent",
3
3
  "type": "module",
4
- "version": "0.0.4",
4
+ "version": "0.0.6",
5
5
  "description": "The OS kernel to safely unleash your agents",
6
6
  "author": "Ryan Rasti <https://github.com/ryanrasti>",
7
7
  "license": "MIT",
@@ -34,14 +34,14 @@
34
34
  "module": "./dist/index.mjs",
35
35
  "types": "./dist/index.d.ts",
36
36
  "files": [
37
- "dist",
38
- "packages/capnweb/dist"
37
+ "dist"
39
38
  ],
40
39
  "scripts": {
41
40
  "clean": "rm -rf dist",
42
- "build": "npm run clean && npm run build:runtime && npm run build:main && npm run build:test-deps",
41
+ "build": "npm run clean && npm run build:runtime && npm run build:main && npm run build:capnweb && npm run build:test-deps",
43
42
  "build:main": "vite build",
44
43
  "build:runtime": "esbuild src/code-mode-runtime.ts --bundle --format=esm --target=es2022 --outfile=dist/code-mode-runtime.mjs --packages=external",
44
+ "build:capnweb": "npm pack ./packages/capnweb --pack-destination dist && mkdir -p dist/capnweb && tar -xzf dist/capnweb-*.tgz --strip-components=1 -C dist/capnweb && rm dist/capnweb-*.tgz",
45
45
  "build:test-deps": "tsdown --config tsdown.test-deps.config.ts",
46
46
  "dev": "tsdown --watch",
47
47
  "lint": "eslint",
@@ -60,7 +60,7 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "camelcase": "^9.0.0",
63
- "capnweb": "file:packages/capnweb",
63
+ "capnweb": "file:dist/capnweb",
64
64
  "json-schema": "^0.4.0",
65
65
  "json-schema-to-typescript": "^15.0.0",
66
66
  "kysely": "^0.28.9",