The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers"; |
| 2 | import { HEADER_ERROR_STACK, INIT_PATH } from "./constants.shared.ts"; |
| 3 | import type { Env as WrapperEnv } from "./env.worker.ts"; |
| 4 | import { getEntryEnvironment, stripInternalEnv } from "./env.worker.ts"; |
| 5 | import { |
| 6 | DURABLE_OBJECT_KEYS, |
| 7 | IGNORED_KEYS, |
| 8 | WORKER_ENTRYPOINT_KEYS, |
| 9 | WORKFLOW_ENTRYPOINT_KEYS, |
| 10 | } from "./keys.shared.ts"; |
| 11 | import { getWorkerEntryExport } from "./module-runner.worker.ts"; |
| 12 | |
| 13 | /** |
| 14 | * Constructor interface for `WorkerEntrypoint` class. |
| 15 | * @template T - The `env` type |
| 16 | */ |
| 17 | interface WorkerEntrypointConstructor<T = Cloudflare.Env> { |
| 18 | new (...args: ConstructorParameters<typeof WorkerEntrypoint<T>>): WorkerEntrypoint<T>; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * Constructor interface for `DurableObject` class. |
| 23 | * @template T - The `env` type |
| 24 | */ |
| 25 | interface DurableObjectConstructor<T = Cloudflare.Env> { |
| 26 | new (...args: ConstructorParameters<typeof DurableObject<T>>): DurableObject<T>; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Constructor interface for `WorkflowEntrypoint` class. |
| 31 | * @template T - The `env` type |
| 32 | */ |
| 33 | interface WorkflowEntrypointConstructor<T = Cloudflare.Env> { |
| 34 | new (...args: ConstructorParameters<typeof WorkflowEntrypoint<T>>): WorkflowEntrypoint<T>; |
| 35 | } |
| 36 | |
| 37 | export { |
| 38 | DURABLE_OBJECT_KEYS, |
| 39 | IGNORED_KEYS, |
| 40 | WORKER_ENTRYPOINT_KEYS, |
| 41 | WORKFLOW_ENTRYPOINT_KEYS, |
| 42 | } from "./keys.shared.ts"; |
| 43 | |
| 44 | /** |
| 45 | * Creates a proxy wrapper for `WorkerEntrypoint` classes that enables RPC functionality. |
| 46 | * The wrapper intercepts property access and delegates to the user code, handling both direct method calls and RPC property access. |
| 47 | * @param exportName - The name of the `WorkerEntrypoint` export to wrap |
| 48 | * @returns A `WorkerEntrypoint` constructor that acts as a proxy to the user code |
| 49 | */ |
| 50 | export function createWorkerEntrypointWrapper( |
| 51 | exportName: string, |
| 52 | ): WorkerEntrypointConstructor<WrapperEnv> { |
| 53 | class Wrapper extends WorkerEntrypoint<WrapperEnv> { |
| 54 | constructor(ctx: ExecutionContext, env: WrapperEnv) { |
| 55 | super(ctx, env); |
| 56 | |
| 57 | return new Proxy(this, { |
| 58 | get(target, key, receiver) { |
| 59 | const value = Reflect.get(target, key, receiver); |
| 60 | |
| 61 | if (value !== undefined) { |
| 62 | return value; |
| 63 | } |
| 64 | |
| 65 | if ( |
| 66 | typeof key === "symbol" || |
| 67 | (IGNORED_KEYS as ReadonlyArray<string>).includes(key) || |
| 68 | // The class methods are accessed to determine the type of the export. |
| 69 | // We should therefore avoid proxying `DurableObject` methods on the `WorkerEntrypoint` class. |
| 70 | (DURABLE_OBJECT_KEYS as ReadonlyArray<string>).includes(key) |
| 71 | ) { |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | const property = getWorkerEntrypointRpcProperty.call(receiver, exportName, key); |
| 76 | |
| 77 | return getRpcPropertyCallableThenable(key, property); |
| 78 | }, |
| 79 | }); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | for (const key of WORKER_ENTRYPOINT_KEYS) { |
| 84 | Wrapper.prototype[key] = async function (arg) { |
| 85 | const proxy = async () => { |
| 86 | const exportValue = await getWorkerEntryExport(this.env, exportName); |
| 87 | const userEnv = stripInternalEnv(this.env); |
| 88 | |
| 89 | if (typeof exportValue === "object" && exportValue !== null) { |
| 90 | // The export is an `ExportedHandler` |
| 91 | const maybeFn = (exportValue as Record<string, unknown>)[key]; |
| 92 | |
| 93 | if (typeof maybeFn !== "function") { |
| 94 | throw new TypeError( |
| 95 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to define a \`${key}()\` function.`, |
| 96 | ); |
| 97 | } |
| 98 | |
| 99 | return maybeFn.call(exportValue, arg, userEnv, this.ctx); |
| 100 | } else if (typeof exportValue === "function") { |
| 101 | // The export is a `WorkerEntrypoint` |
| 102 | const ctor = exportValue as WorkerEntrypointConstructor; |
| 103 | const instance = new ctor(this.ctx, userEnv); |
| 104 | |
| 105 | if (!(instance instanceof WorkerEntrypoint)) { |
| 106 | throw new TypeError( |
| 107 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be a subclass of \`WorkerEntrypoint\`.`, |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | const maybeFn = instance[key]; |
| 112 | |
| 113 | if (typeof maybeFn !== "function") { |
| 114 | throw new TypeError( |
| 115 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to define a \`${key}()\` method.`, |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | return (maybeFn as (arg: unknown) => unknown).call(instance, arg); |
| 120 | } else { |
| 121 | throw new TypeError( |
| 122 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be an object or a class.`, |
| 123 | ); |
| 124 | } |
| 125 | }; |
| 126 | |
| 127 | if (key === "fetch") { |
| 128 | const request = arg as Request; |
| 129 | const url = new URL(request.url); |
| 130 | // Initialize the module runner |
| 131 | if (url.pathname === INIT_PATH) { |
| 132 | const stub = this.env.__DISTILLED_MODULE_RUNNER__.get("singleton"); |
| 133 | return stub.fetch(request); |
| 134 | } |
| 135 | try { |
| 136 | return await proxy(); |
| 137 | } catch (error) { |
| 138 | // The default export's errors go to Vite's error page, as under |
| 139 | // `@cloudflare/vite-plugin`: the dev server revives this response. |
| 140 | if (exportName === "default") { |
| 141 | return Response.json(reduceError(error), { |
| 142 | status: 500, |
| 143 | headers: { [HEADER_ERROR_STACK]: "true" }, |
| 144 | }); |
| 145 | } |
| 146 | console.error("Error calling fetch", error); |
| 147 | throw error; |
| 148 | } |
| 149 | } |
| 150 | return await proxy(); |
| 151 | }; |
| 152 | } |
| 153 | |
| 154 | return Wrapper; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Retrieves an RPC property from a `WorkerEntrypoint` export, creating an instance and returning the bound method or property value. |
| 159 | * @param exportName - The name of the `WorkerEntrypoint` export |
| 160 | * @param key - The property key to access on the `WorkerEntrypoint` instance |
| 161 | * @returns The property value, with methods bound to the instance |
| 162 | * @throws TypeError if the export is not a `WorkerEntrypoint` subclass |
| 163 | */ |
| 164 | async function getWorkerEntrypointRpcProperty( |
| 165 | this: WorkerEntrypoint<WrapperEnv>, |
| 166 | exportName: string, |
| 167 | key: string, |
| 168 | ): Promise<unknown> { |
| 169 | const ctor = (await getWorkerEntryExport(this.env, exportName)) as WorkerEntrypointConstructor; |
| 170 | const userEnv = stripInternalEnv(this.env); |
| 171 | const expectedWorkerEntrypointMessage = `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be a subclass of \`WorkerEntrypoint\` for RPC.`; |
| 172 | |
| 173 | if (typeof ctor !== "function") { |
| 174 | throw new TypeError(expectedWorkerEntrypointMessage); |
| 175 | } |
| 176 | |
| 177 | const instance = new ctor(this.ctx, userEnv); |
| 178 | |
| 179 | if (!(instance instanceof WorkerEntrypoint)) { |
| 180 | throw new TypeError(expectedWorkerEntrypointMessage); |
| 181 | } |
| 182 | |
| 183 | const value = getRpcProperty(ctor, instance, key); |
| 184 | |
| 185 | if (typeof value === "function") { |
| 186 | return value.bind(instance); |
| 187 | } |
| 188 | |
| 189 | return value; |
| 190 | } |
| 191 | |
| 192 | /** Symbol key for storing the `DurableObject` instance */ |
| 193 | const kInstance = Symbol("kInstance"); |
| 194 | /** Symbol key for the instance initialization method */ |
| 195 | const kEnsureInstance = Symbol("kEnsureInstance"); |
| 196 | |
| 197 | /** |
| 198 | * Container for a `DurableObject` constructor and its instance. |
| 199 | */ |
| 200 | interface DurableObjectInstance { |
| 201 | ctor: DurableObjectConstructor; |
| 202 | instance: DurableObject; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Extended `DurableObject` interface that includes instance management methods. |
| 207 | */ |
| 208 | interface DurableObjectWrapper extends DurableObject<WrapperEnv> { |
| 209 | [kInstance]?: DurableObjectInstance; |
| 210 | [kEnsureInstance](): Promise<DurableObjectInstance>; |
| 211 | } |
| 212 | |
| 213 | /** |
| 214 | * Retrieves an RPC property from a `DurableObject` export, ensuring an instance is properly initialized and returning the bound method or property value. |
| 215 | * @param exportName - The name of the `DurableObject` export |
| 216 | * @param key - The property key to access on the `DurableObject` instance |
| 217 | * @returns The property value, with methods bound to the instance |
| 218 | * @throws TypeError if the export is not a `DurableObject` subclass |
| 219 | */ |
| 220 | async function getDurableObjectRpcProperty( |
| 221 | this: DurableObjectWrapper, |
| 222 | exportName: string, |
| 223 | key: string, |
| 224 | ): Promise<unknown> { |
| 225 | const { ctor, instance } = await this[kEnsureInstance](); |
| 226 | |
| 227 | if (!(instance instanceof DurableObject)) { |
| 228 | throw new TypeError( |
| 229 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be a subclass of \`DurableObject\` for RPC.`, |
| 230 | ); |
| 231 | } |
| 232 | |
| 233 | const value = getRpcProperty(ctor, instance, key); |
| 234 | |
| 235 | if (typeof value === "function") { |
| 236 | return value.bind(instance); |
| 237 | } |
| 238 | |
| 239 | return value; |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Creates a proxy wrapper for `DurableObject` classes that enables RPC functionality. |
| 244 | * The wrapper manages instance lifecycle and delegates method calls to the user code, handling both direct method calls and RPC property access. |
| 245 | * @param exportName - The name of the `DurableObject` export to wrap |
| 246 | * @returns A `DurableObject` constructor that acts as a proxy to the user code |
| 247 | */ |
| 248 | export function createDurableObjectWrapper( |
| 249 | exportName: string, |
| 250 | ): DurableObjectConstructor<WrapperEnv> { |
| 251 | class Wrapper extends DurableObject<WrapperEnv> implements DurableObjectWrapper { |
| 252 | [kInstance]?: DurableObjectInstance; |
| 253 | |
| 254 | constructor(ctx: DurableObjectState, env: WrapperEnv) { |
| 255 | super(ctx, env); |
| 256 | |
| 257 | return new Proxy(this, { |
| 258 | get(target, key, receiver) { |
| 259 | const value = Reflect.get(target, key, receiver); |
| 260 | |
| 261 | if (value !== undefined) { |
| 262 | return value; |
| 263 | } |
| 264 | |
| 265 | if ( |
| 266 | typeof key === "symbol" || |
| 267 | (IGNORED_KEYS as ReadonlyArray<string>).includes(key) || |
| 268 | // The class methods are accessed to determine the type of the export. |
| 269 | // We should therefore avoid proxying `WorkerEntrypoint` methods on the `DurableObject` class. |
| 270 | (WORKER_ENTRYPOINT_KEYS as ReadonlyArray<string>).includes(key) |
| 271 | ) { |
| 272 | return; |
| 273 | } |
| 274 | |
| 275 | const property = getDurableObjectRpcProperty.call(receiver, exportName, key); |
| 276 | |
| 277 | return getRpcPropertyCallableThenable(key, property); |
| 278 | }, |
| 279 | }); |
| 280 | } |
| 281 | |
| 282 | async [kEnsureInstance]() { |
| 283 | const ctor = (await getWorkerEntryExport(this.env, exportName)) as DurableObjectConstructor; |
| 284 | |
| 285 | if (typeof ctor !== "function") { |
| 286 | throw new TypeError( |
| 287 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be a subclass of \`DurableObject\`.`, |
| 288 | ); |
| 289 | } |
| 290 | |
| 291 | // We reuse the same instance unless the constructor changes |
| 292 | if (!this[kInstance] || this[kInstance].ctor !== ctor) { |
| 293 | const userEnv = stripInternalEnv(this.env); |
| 294 | const instance = new ctor(this.ctx, userEnv); |
| 295 | |
| 296 | this[kInstance] = { ctor, instance }; |
| 297 | |
| 298 | // Wait for `blockConcurrencyWhile()`s in the constructor to complete |
| 299 | await this.ctx.blockConcurrencyWhile(async () => {}); |
| 300 | } |
| 301 | |
| 302 | return this[kInstance]; |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | for (const key of DURABLE_OBJECT_KEYS) { |
| 307 | Wrapper.prototype[key] = async function (...args: Array<unknown>) { |
| 308 | const { instance } = await this[kEnsureInstance](); |
| 309 | const maybeFn = instance[key]; |
| 310 | |
| 311 | if (typeof maybeFn !== "function") { |
| 312 | throw new TypeError( |
| 313 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to define a \`${key}()\` function.`, |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | return (maybeFn as (...args: Array<unknown>) => any).apply(instance, args); |
| 318 | }; |
| 319 | } |
| 320 | |
| 321 | return Wrapper; |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Creates a proxy wrapper for `WorkflowEntrypoint` classes. |
| 326 | * The wrapper delegates method calls to the user code. |
| 327 | * @param exportName - The name of the `WorkflowEntrypoint` export to wrap |
| 328 | * @returns A `WorkflowEntrypoint` constructor that acts as a proxy to the user code |
| 329 | */ |
| 330 | export function createWorkflowEntrypointWrapper( |
| 331 | exportName: string, |
| 332 | ): WorkflowEntrypointConstructor<WrapperEnv> { |
| 333 | class Wrapper extends WorkflowEntrypoint<WrapperEnv> {} |
| 334 | |
| 335 | for (const key of WORKFLOW_ENTRYPOINT_KEYS) { |
| 336 | Wrapper.prototype[key] = async function (...args: Array<unknown>) { |
| 337 | const ctor = (await getWorkerEntryExport( |
| 338 | this.env, |
| 339 | exportName, |
| 340 | )) as WorkflowEntrypointConstructor; |
| 341 | const userEnv = stripInternalEnv(this.env); |
| 342 | const instance = new ctor(this.ctx, userEnv); |
| 343 | |
| 344 | if (!(instance instanceof WorkflowEntrypoint)) { |
| 345 | throw new TypeError( |
| 346 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to be a subclass of \`WorkflowEntrypoint\`.`, |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | const maybeFn = instance[key]; |
| 351 | |
| 352 | if (typeof maybeFn !== "function") { |
| 353 | throw new TypeError( |
| 354 | `Expected "${exportName}" export of "${getEntryEnvironment().entryName}" to define a \`${key}()\` function.`, |
| 355 | ); |
| 356 | } |
| 357 | |
| 358 | return (maybeFn as (...args: Array<unknown>) => any).apply(instance, args); |
| 359 | }; |
| 360 | } |
| 361 | |
| 362 | return Wrapper; |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Creates a callable thenable that is used to access the properties of an RPC target. |
| 367 | * It can be both awaited and invoked as a function. |
| 368 | * This enables RPC properties to be used both as promises and callable functions. |
| 369 | * @param key - The property key name used for error messages |
| 370 | * @param property - The promise that resolves to the property value |
| 371 | * @returns A callable thenable that implements both Promise and function interfaces |
| 372 | */ |
| 373 | function getRpcPropertyCallableThenable( |
| 374 | key: string, |
| 375 | property: Promise<unknown>, |
| 376 | ): Promise<unknown> & ((...args: Array<unknown>) => Promise<unknown>) { |
| 377 | const fn = async function (...args: Array<unknown>) { |
| 378 | const maybeFn = await property; |
| 379 | |
| 380 | if (typeof maybeFn !== "function") { |
| 381 | throw new TypeError(`"${key}" is not a function.`); |
| 382 | } |
| 383 | |
| 384 | return maybeFn(...args); |
| 385 | } as Promise<unknown> & ((...args: Array<unknown>) => Promise<unknown>); |
| 386 | |
| 387 | // oxlint-disable-next-line unicorn/no-thenable |
| 388 | fn.then = (onFulfilled, onRejected) => property.then(onFulfilled, onRejected); |
| 389 | fn.catch = (onRejected) => property.catch(onRejected); |
| 390 | fn.finally = (onFinally) => property.finally(onFinally); |
| 391 | |
| 392 | return fn; |
| 393 | } |
| 394 | |
| 395 | /** |
| 396 | * Retrieves an RPC property from a constructor prototype, ensuring it exists on the prototype rather than the instance to maintain RPC compatibility. |
| 397 | * @param ctor - The constructor function (`WorkerEntrypoint` or `DurableObject`) |
| 398 | * @param instance - The instance to bind methods to |
| 399 | * @param key - The property key to retrieve |
| 400 | * @returns The property value from the prototype |
| 401 | * @throws TypeError if the property doesn't exist on the prototype |
| 402 | */ |
| 403 | function getRpcProperty( |
| 404 | ctor: WorkerEntrypointConstructor | DurableObjectConstructor, |
| 405 | instance: WorkerEntrypoint | DurableObject, |
| 406 | key: string, |
| 407 | ): unknown { |
| 408 | const prototypeHasKey = Reflect.has(ctor.prototype, key); |
| 409 | |
| 410 | if (!prototypeHasKey) { |
| 411 | const instanceHasKey = Reflect.has(instance, key); |
| 412 | |
| 413 | if (instanceHasKey) { |
| 414 | throw new TypeError( |
| 415 | [ |
| 416 | `The RPC receiver's prototype does not implement "${key}", but the receiver instance does.`, |
| 417 | "Only properties and methods defined on the prototype can be accessed over RPC.", |
| 418 | `Ensure properties are declared as \`get ${key}() { ... }\` instead of \`${key} = ...\`,`, |
| 419 | `and methods are declared as \`${key}() { ... }\` instead of \`${key} = () => { ... }\`.`, |
| 420 | ].join("\n"), |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | throw new TypeError(`The RPC receiver does not implement "${key}".`); |
| 425 | } |
| 426 | |
| 427 | return Reflect.get(ctor.prototype, key, instance); |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Serializes an error for the dev server to revive (Wrangler's |
| 432 | * `middleware-miniflare3-json-error.ts`). |
| 433 | */ |
| 434 | function reduceError(e: unknown): unknown { |
| 435 | const errorObj = (e ?? {}) as Record<string, unknown>; |
| 436 | return { |
| 437 | name: errorObj.name, |
| 438 | message: errorObj.message ?? String(e), |
| 439 | stack: errorObj.stack, |
| 440 | cause: errorObj.cause === undefined ? undefined : reduceError(errorObj.cause), |
| 441 | }; |
| 442 | } |