@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 637 lines 23.9 KB
Raw
1 import type { Dependencies } from "alchemy/Dependencies";
2 import type { HttpEffect } from "alchemy/Http";
3 import type { Input } from "alchemy/Input";
4 import { RuntimeContext } from "alchemy/RuntimeContext";
5 import { effectClass, taggedFunction } from "alchemy/Util/effect";
6 import type { ConfigError } from "effect/Config";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as Fiber from "effect/Fiber";
11 import type { HttpServerError } from "effect/http/HttpServerError";
12 import { HttpServerRequest } from "effect/http/HttpServerRequest";
13 import type { HttpServerResponse } from "effect/http/HttpServerResponse";
14 import * as Layer from "effect/Layer";
15 import type { Rpc, RpcGroup } from "effect/rpc";
16 import * as RpcClient from "effect/rpc/RpcClient";
17 import * as RpcClientError from "effect/rpc/RpcClientError";
18 import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
19 import * as RpcSerialization from "effect/rpc/RpcSerialization";
20 import * as RpcServer from "effect/rpc/RpcServer";
21 import * as Scope from "effect/Scope";
22 import {
23 DurableObject,
24 type DurableObjectGetDurableObjectOptions,
25 type DurableObjectLike,
26 type DurableObjectProps,
27 type DurableObject as DurableObjectType,
28 type DurableObjectServices,
29 } from "./DurableObject.ts";
30 import { DurableObjectState } from "./DurableObjectState.ts";
31 import { bindEffectRpc } from "./Rpc.ts";
32 import * as RpcWebSocket from "./RpcWebSocket.ts";
33 import type { Worker as WorkerService } from "./Worker.ts";
34
35 export interface RpcDurableObjectProps<Rpcs extends Rpc.Any> {
36 /** The RPC schema shared by the Durable Object and its clients. */
37 readonly schema: RpcGroup.RpcGroup<Rpcs>;
38 }
39
40 type HandlerImplementation<Rpcs extends Rpc.Any, Provided, InnerR, InitReq> = Effect.Effect<
41 Effect.Effect<
42 Layer.Layer<Rpc.ToHandler<Rpcs> | Provided, never, InnerR | RuntimeContext>,
43 never,
44 DurableObjectServices | RuntimeContext
45 >,
46 ConfigError,
47 InitReq
48 >;
49
50 type HandlerRequirements<Rpcs extends Rpc.Any, Provided, InnerR, InitReq> =
51 | WorkerService
52 | Exclude<
53 InitReq | InnerR | Exclude<Rpc.Middleware<Rpcs>, Provided> | Rpc.ServicesServer<Rpcs>,
54 DurableObjectServices | RuntimeContext
55 >;
56
57 /**
58 * The runtime value bound to a typed rpc Durable Object namespace.
59 * Same shape as the underlying {@link DurableObjectType} for
60 * binding metadata (name, namespaceId, kind), but `getByName(id)`
61 * returns a typed Effect `RpcClient` over the rpc server living on
62 * the DO's `fetch` handler.
63 */
64 export interface RpcDurableObject<Self, Rpcs extends Rpc.Any = Rpc.Any> extends Omit<
65 DurableObjectType<{ fetch: HttpEffect<DurableObjectState> }>,
66 "getByName" | "get" | "Shape"
67 > {
68 /** @internal phantom — keeps `Self` reachable through the inferred type */
69 Self?: Self;
70 /**
71 * Select a named instance and forward an HTTP request or WebSocket upgrade.
72 * Every RPC on the upgraded socket targets that same instance.
73 */
74 readonly fetch: (
75 id: string,
76 request: HttpServerRequest,
77 options?: DurableObjectGetDurableObjectOptions,
78 ) => Effect.Effect<HttpServerResponse, HttpServerError>;
79 readonly getByName: (
80 id: string,
81 options?: DurableObjectGetDurableObjectOptions,
82 ) => Effect.Effect<
83 RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError>,
84 never,
85 Rpc.MiddlewareClient<Rpcs>
86 >;
87 }
88
89 // Context tag carrying the surrounding `RpcDurableObject`
90 // inside an rpc DO impl. Yield it from within a DO handler to refer
91 // back to the surrounding namespace (e.g. to fan a call out to
92 // sibling instances). Documented as part of the main
93 // `RpcDurableObject` JSDoc below.
94 export class RpcDurableObjectScope extends Context.Service<
95 RpcDurableObjectScope,
96 RpcDurableObject<unknown>
97 >()("Cloudflare.RpcDurableObject") {}
98
99 export interface RpcDurableObjectClass extends Effect.Effect<
100 RpcDurableObject<unknown>,
101 never,
102 RpcDurableObjectScope
103 > {
104 /**
105 * Class-based forms: `class Counter extends RpcDurableObject<Counter>()(...)`.
106 *
107 * Modular (no impl):
108 * ```ts
109 * class Counter extends RpcDurableObject<Counter>()(
110 * "Counter",
111 * { schema: CounterRpcs },
112 * ) {}
113 * export const CounterLive = Counter.make(/* impl *\/);
114 * ```
115 * Inline impl:
116 * ```ts
117 * class Counter extends RpcDurableObject<Counter>()(
118 * "Counter",
119 * { schema: CounterRpcs },
120 * Effect.gen(function* () { ... }),
121 * ) {}
122 * ```
123 */
124 <Self>(): {
125 /** Modular form: separate `static make(impl)` + `static from(scriptName | Worker)`. */
126 <Rpcs extends Rpc.Any>(
127 name: string,
128 props: RpcDurableObjectProps<Rpcs>,
129 ): Effect.Effect<RpcDurableObject<Self, Rpcs>, never, WorkerService | Self> & {
130 new (_: never): {};
131 from(
132 scriptName: Input<string>,
133 ): Effect.Effect<RpcDurableObject<Self, Rpcs>, never, WorkerService>;
134 from<Req = never>(
135 worker: Dependencies<Self> | Effect.Effect<Dependencies<Self>, ConfigError, Req>,
136 ): Effect.Effect<RpcDurableObject<Self, Rpcs>, never, WorkerService | Req>;
137 make<Provided = never, InnerR = never, InitReq = never>(
138 impl: HandlerImplementation<Rpcs, Provided, InnerR, InitReq>,
139 ): Layer.Layer<Self, never, HandlerRequirements<Rpcs, Provided, InnerR, InitReq>>;
140 make<InnerR = never, InitReq = never>(
141 impl: Effect.Effect<
142 Effect.Effect<
143 Effect.Effect<HttpEffect<InnerR>, never, InnerR | RuntimeContext>,
144 never,
145 DurableObjectServices | RuntimeContext
146 >,
147 ConfigError,
148 InitReq
149 >,
150 ): Layer.Layer<Self, never, WorkerService | Exclude<InitReq | InnerR, DurableObjectServices>>;
151 };
152 /** Inline handler Layer; the runtime supplies the RPC transports. */
153 <Rpcs extends Rpc.Any, Provided = never, InnerR = never, InitReq = never>(
154 name: string,
155 props: RpcDurableObjectProps<Rpcs>,
156 impl: HandlerImplementation<Rpcs, Provided, InnerR, InitReq>,
157 ): Effect.Effect<
158 RpcDurableObject<Self, Rpcs>,
159 never,
160 HandlerRequirements<Rpcs, Provided, InnerR, InitReq>
161 > & { new (_: never): {} };
162 /** Inline-impl form. */
163 <Rpcs extends Rpc.Any, InnerR = never, InitReq = never>(
164 name: string,
165 props: RpcDurableObjectProps<Rpcs>,
166 impl: Effect.Effect<
167 Effect.Effect<
168 Effect.Effect<HttpEffect<InnerR>, never, InnerR | RuntimeContext>,
169 never,
170 DurableObjectServices | RuntimeContext
171 >,
172 ConfigError,
173 InitReq
174 >,
175 ): Effect.Effect<
176 RpcDurableObject<Self, Rpcs>,
177 never,
178 WorkerService | Exclude<InitReq | InnerR, DurableObjectServices>
179 > & {
180 new (_: never): {};
181 };
182 };
183 /** Descriptor-only form, for `worker.bind` declarations */
184 <Rpcs extends Rpc.Any>(
185 name: string,
186 props: {
187 readonly schema: RpcGroup.RpcGroup<Rpcs>;
188 } & Partial<DurableObjectProps>,
189 ): DurableObjectLike<{ fetch: HttpEffect<DurableObjectState> }>;
190 /** Bare handler-Layer form. */
191 <Rpcs extends Rpc.Any, Provided = never, InnerR = never, InitReq = never>(
192 name: string,
193 props: RpcDurableObjectProps<Rpcs>,
194 impl: HandlerImplementation<Rpcs, Provided, InnerR, InitReq>,
195 ): Effect.Effect<
196 RpcDurableObject<unknown, Rpcs>,
197 never,
198 HandlerRequirements<Rpcs, Provided, InnerR, InitReq>
199 >;
200 /** Bare form: `(name, { schema }, impl)` */
201 <Rpcs extends Rpc.Any, InnerR = never, InitReq = never>(
202 name: string,
203 props: RpcDurableObjectProps<Rpcs>,
204 impl: Effect.Effect<
205 Effect.Effect<Effect.Effect<HttpEffect<InnerR>, never, InnerR>, never, DurableObjectServices>,
206 ConfigError,
207 InitReq
208 >,
209 ): Effect.Effect<
210 RpcDurableObject<unknown, Rpcs>,
211 never,
212 WorkerService | Exclude<InitReq | InnerR, DurableObjectServices>
213 >;
214 }
215
216 /**
217 * `RpcDurableObject` is sugar over {@link DurableObject}
218 * for Durable Objects whose surface is a typed Effect `RpcGroup`. The
219 * inner Effect returns the group's handler Layer, automatically enabling
220 * HTTP RPC with NDJSON and hibernating WebSocket RPC with JSON. Incoming
221 * requests select the transport. Consumers see `namespace.getByName(id)`
222 * as a typed HTTP `RpcClient`.
223 * Existing implementations returning `RpcServer.toHttpEffect(group)` remain
224 * supported for HTTP.
225 *
226 * Use this over alchemy's built-in DO method bridge whenever values
227 * crossing the DO boundary contain `Schema.Class` instances. The
228 * built-in bridge `JSON.stringify`s every method return value, which
229 * strips class identity (e.g. an `effect/ai` `Response.Usage` instance
230 * becomes a plain struct on the consumer side). With
231 * `RpcDurableObject`, both ends go through the same
232 * `RpcSerialization` codec, so `Schema.decode` reconstructs class
233 * instances correctly.
234 *
235 *
236 * ### Defining the rpc group
237 * **Example:** DO-scoped rpc schemas
238 * The DO instance *is* the session, so the group payloads typically
239 * don't include any per-session identifier — only the per-call inputs.
240 * ```typescript
241 * import * as Schema from "effect/Schema";
242 * import { Rpc, RpcGroup } from "effect/rpc";
243 *
244 * const setTitle = Rpc.make("setTitle", {
245 * success: Schema.Void,
246 * payload: { title: Schema.String },
247 * });
248 *
249 * const getTitle = Rpc.make("getTitle", {
250 * success: Schema.String,
251 * payload: {},
252 * });
253 *
254 * export class CounterRpcs extends RpcGroup.make(setTitle, getTitle) {}
255 * ```
256 *
257 * ### Implementing the Durable Object
258 * **Example:** Class form (recommended)
259 * Mirrors `Cloudflare.DurableObject<Self>()(...)` — same
260 * outer/inner Effect pattern. The outer Effect resolves shared deps;
261 * the per-instance inner Effect returns the RPC handler Layer.
262 * ```typescript
263 * import * as Cloudflare from "@alchemy.run/cloudflare";
264 * import * as Effect from "effect/Effect";
265 * import { CounterRpcs } from "./rpcs.ts";
266 *
267 * export default class Counter extends Cloudflare.RpcDurableObject<Counter>()(
268 * "Counter",
269 * { schema: CounterRpcs },
270 * Effect.gen(function* () {
271 * // outer init: shared deps + the instance state reference
272 * const state = yield* Cloudflare.DurableObjectState;
273 * return Effect.gen(function* () {
274 * // inner (runtime): state.storage is RuntimeContext-colored, so
275 * // the handler closures that call it live here
276 * return CounterRpcs.toLayer({
277 * setTitle: ({ title }) => state.storage.put("title", title),
278 * getTitle: () =>
279 * Effect.map(state.storage.get<string>("title"), (t) => t ?? ""),
280 * });
281 * });
282 * }),
283 * ) {}
284 * ```
285 *
286 * ### Calling the DO from a Worker
287 * **Example:** Typed rpc client at the call site
288 * `yield* Counter` resolves to a value whose `getByName(id)` returns
289 * an `Effect<RpcClient<CounterRpcs>>`. Each rpc method is a typed
290 * Effect/Stream factory — no `RpcClient.make` setup needed. Yield
291 * the client inside a per-request `Effect.scoped` handler so it's
292 * freed with the request.
293 * ```typescript
294 * import Counter from "./counter.ts";
295 *
296 * Effect.gen(function* () {
297 * const counters = yield* Counter;
298 * const client = yield* counters.getByName("global");
299 * yield* client.setTitle({ title: "Hello" });
300 * const title = yield* client.getTitle({});
301 * return title;
302 * }).pipe(Effect.scoped);
303 * ```
304 *
305 * ### WebSocket RPC
306 * **Example:** Forward a browser connection from the Worker
307 * Handler-Layer implementations accept WebSocket upgrades automatically;
308 * ordinary HTTP RPC remains available on the same object.
309 * ```typescript
310 * import { HttpServerRequest } from "effect/http/HttpServerRequest";
311 * import * as HttpServerResponse from "effect/http/HttpServerResponse";
312 *
313 * const counters = yield* Counter;
314 * return {
315 * fetch: Effect.gen(function* () {
316 * const request = yield* HttpServerRequest;
317 * const path = new URL(request.url, "https://worker").pathname;
318 * const name = /^\/counters\/([a-zA-Z0-9_-]+)$/.exec(path)?.[1];
319 * if (!name) return HttpServerResponse.empty({ status: 404 });
320 * return yield* counters.fetch(name, request);
321 * }),
322 * };
323 * ```
324 * A client connecting to `wss://example.com/counters/alice` targets the
325 * `"alice"` instance. Every RPC on that socket stays on that object; RPC
326 * payloads do not need an object ID. Another name selects another object.
327 * The Worker defines this URL mapping, not Alchemy.
328 * Authenticate and authorize access to the selected name before forwarding.
329 * See the [Effect RPC guide](/cloudflare/apis/effect-rpc#connect-over-a-websocket)
330 * for a browser client whose Layer owns the connection lifetime. Clients use
331 * Effect's `RpcClient.layerProtocolSocket` with JSON serialization. Idle
332 * connections survive hibernation. Restored sockets with unfinished requests
333 * close with code `1012`; platform resets can also cause transport errors.
334 * Requests and streams are never replayed. No application acknowledgment
335 * methods or checkpoints are required.
336 *
337 * ### Modular form: separate the class from its runtime
338 * **Example:** Class declaration with no impl + `static make(impl)`
339 * The inline class form above bundles the runtime into the class
340 * declaration. The two-arg form `(name, { schema })` declares the
341 * class as a pure tagged identifier; provide the runtime separately
342 * via `Class.make(impl)`. Consumer Workers can import the class for
343 * binding (`Counter.from(HostWorker)`) without pulling the runtime
344 * into their bundle.
345 * ```typescript
346 * import * as Cloudflare from "@alchemy.run/cloudflare";
347 * import * as Effect from "effect/Effect";
348 * import { CounterRpcs } from "./rpcs.ts";
349 *
350 * export class Counter extends Cloudflare.RpcDurableObject<Counter>()(
351 * "Counter",
352 * { schema: CounterRpcs },
353 * ) {}
354 *
355 * // Only the host script imports this default export.
356 * export default Counter.make(
357 * Effect.gen(function* () {
358 * const state = yield* Cloudflare.DurableObjectState;
359 * return Effect.gen(function* () {
360 * return CounterRpcs.toLayer({
361 * setTitle: ({ title }) => state.storage.put("title", title),
362 * getTitle: () =>
363 * Effect.map(state.storage.get<string>("title"), (t) => t ?? ""),
364 * });
365 * });
366 * }),
367 * );
368 * ```
369 *
370 * ### Cross-script binding via `Counter.from(Worker)`
371 * **Example:** Hosting on WorkerA, binding from WorkerB
372 * The host Worker declares `Counter` in its `Deps` (third type
373 * arg of `Worker<Self, Bindings, Deps>` or second of
374 * `RpcWorker<Self, Deps>`) and provides `CounterLive`. Any other
375 * Worker uses `Counter.from(HostWorker)` to bind to the same DO
376 * instances — writes through `HostWorker.getByName(name)` are
377 * visible from `Counter.from(HostWorker).getByName(name)`.
378 * ```typescript
379 * // host worker (declares + provides Counter)
380 * import CounterLive, { Counter } from "./counter.ts";
381 *
382 * export class WorkerA extends Cloudflare.Worker<WorkerA, {}, Counter>()(
383 * "WorkerA",
384 * { main: import.meta.url },
385 * ) {}
386 *
387 * export default WorkerA.make(
388 * Effect.gen(function* () {
389 * const counters = yield* Counter; // local host binding
390 * // ... fetch handler ...
391 * }).pipe(Effect.provide(CounterLive)),
392 * );
393 *
394 * // consumer worker (binds via .from)
395 * export default class WorkerB extends Cloudflare.Worker<WorkerB>()(
396 * "WorkerB",
397 * { main: import.meta.url },
398 * Effect.gen(function* () {
399 * const counters = yield* Counter.from(WorkerA);
400 * return {
401 * fetch: Effect.gen(function* () {
402 * const client = yield* counters.getByName("shared");
403 * yield* client.setTitle({ title: "via WorkerB" });
404 * return HttpServerResponse.text("ok");
405 * }).pipe(Effect.scoped),
406 * };
407 * }),
408 * ) {}
409 * ```
410 *
411 * **Example:** Self-hosted isolated namespace
412 * A Worker that declares `Counter` in its own `Deps` and provides
413 * `CounterLive` hosts its own isolated namespace — instances under
414 * it are separate from any other host's. Use `Counter.from(Self)`
415 * inside the host to be explicit about which script's namespace
416 * you're binding to.
417 * ```typescript
418 * export class WorkerC extends Cloudflare.Worker<WorkerC, {}, Counter>()(
419 * "WorkerC",
420 * { main: import.meta.url },
421 * ) {}
422 *
423 * export default WorkerC.make(
424 * Effect.gen(function* () {
425 * const counters = yield* Counter.from(WorkerC); // explicit self
426 * // ... fetch handler ...
427 * }).pipe(Effect.provide(CounterLive)),
428 * );
429 * ```
430 *
431 * ### Yielding the surrounding namespace from inside a DO
432 * **Example:** `yield* RpcDurableObject` inside the DO impl
433 * Lets a DO instance refer to its own namespace — e.g. to fan a call
434 * out to sibling instances. Mirrors `yield* DurableObject`
435 * on the regular `DurableObject`.
436 * ```typescript
437 * Effect.gen(function* () {
438 * const self = yield* Cloudflare.RpcDurableObject;
439 * const peer = yield* self.getByName("peer-1");
440 * yield* peer.setTitle({ title: "Sibling call" });
441 * }).pipe(Effect.scoped);
442 * ```
443 *
444 * @resource
445 * @product Workers
446 * @category Workers & Compute
447 */
448 export const RpcDurableObject: RpcDurableObjectClass = taggedFunction(
449 RpcDurableObjectScope,
450 (...args: any[]) => {
451 // Class-form: zero args returns the inner builder. Inner-arg arity
452 // distinguishes modular (`(name, { schema })`, no impl — `static
453 // from`/`static make` provide the runtime) from inline-impl
454 // (`(name, { schema }, impl)`).
455 if (args.length === 0) {
456 return (...inner: any[]) => {
457 if (inner.length === 2) {
458 const [name, props] = inner as [string, RpcDurableObjectProps<any>];
459 return buildModular(name, props);
460 }
461 const [name, props, impl] = inner as [
462 string,
463 RpcDurableObjectProps<any>,
464 Effect.Effect<Effect.Effect<any>>,
465 ];
466 return build(name, props, impl);
467 };
468 }
469 // Descriptor-only form: `(name, { schema })` — no impl.
470 if (args.length === 2) {
471 const [name, props] = args as [
472 string,
473 {
474 readonly schema: RpcGroup.RpcGroup<any>;
475 } & Partial<DurableObjectProps>,
476 ];
477 return {
478 kind: "Cloudflare.DurableObject" as const,
479 name,
480 className: props?.className,
481 } satisfies DurableObjectLike<any>;
482 }
483 // Bare form: `(name, { schema }, impl)`.
484 const [name, props, impl] = args as [
485 string,
486 RpcDurableObjectProps<any>,
487 Effect.Effect<Effect.Effect<any>>,
488 ];
489 return build(name, props, impl);
490 },
491 ) as any;
492
493 // Wrap a raw `DurableObject` so its `getByName` returns a typed
494 // Effect `RpcClient` (via `bindEffectRpc`) instead of the built-in
495 // method-bridge stub. Used in every branch that produces a yieldable
496 // `RpcDurableObject` value.
497 const rpcWrap = (
498 rawNs: DurableObjectType<any>,
499 schema: RpcGroup.RpcGroup<any>,
500 ): RpcDurableObject<any> => {
501 const rpcView = bindEffectRpc(rawNs as any, schema);
502 return Object.assign({}, rawNs, {
503 getByName: rpcView.getByName,
504 fetch: (
505 id: string,
506 request: HttpServerRequest,
507 options?: DurableObjectGetDurableObjectOptions,
508 ) => rawNs.getByName(id, options).fetch(request),
509 }) as unknown as RpcDurableObject<any>;
510 };
511
512 const wrapImpl = (impl: Effect.Effect<Effect.Effect<any>>, props: RpcDurableObjectProps<any>) =>
513 impl.pipe(
514 Effect.map((inner) =>
515 inner.pipe(
516 Effect.flatMap((value) => {
517 if (Layer.isLayer(value)) {
518 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- untyped impl value; layer requirements are provided by the DO bridge
519 return makeHandlers(props, value as Layer.Layer<any, never, any>);
520 }
521 return Effect.succeed({ fetch: value });
522 }),
523 ),
524 ),
525 ) as Effect.Effect<Effect.Effect<any>>;
526
527 class RpcRequestLifetime extends RpcMiddleware.Service<RpcRequestLifetime>()(
528 "Cloudflare.RpcDurableObject.RequestLifetime",
529 ) {}
530
531 const makeHandlers = Effect.fn(function* (
532 props: RpcDurableObjectProps<any>,
533 handlers: Layer.Layer<any, never, any>,
534 ) {
535 // The protocol outlives the constructor's temporary layer scope.
536 return yield* Effect.acquireUseRelease(
537 Scope.make(),
538 (instanceScope) =>
539 Effect.gen(function* () {
540 const memoMap = Layer.makeMemoMapUnsafe();
541 const context = yield* Layer.buildWithMemoMap(handlers, memoMap, instanceScope);
542 const services = Layer.succeedContext(context);
543 const http = Effect.gen(function* () {
544 const handler = yield* RpcServer.toHttpEffect(props.schema).pipe(
545 Effect.provide(Layer.mergeAll(services, RpcSerialization.layerNdjson)),
546 );
547 return yield* handler;
548 });
549 const state = yield* DurableObjectState;
550 const runtime = yield* RuntimeContext;
551 const lifetime = Layer.succeed(RpcRequestLifetime, (effect) =>
552 Effect.withFiber((fiber) =>
553 // RpcServer sends Exit before finalization and drops sends after disconnect.
554 state
555 .waitUntil(Fiber.await(fiber))
556 .pipe(Effect.provideService(RuntimeContext, runtime), Effect.andThen(effect)),
557 ),
558 );
559 const transport = yield* RpcWebSocket.make.pipe(Effect.provide(RpcSerialization.layerJson));
560 yield* Layer.buildWithMemoMap(
561 RpcServer.layer(props.schema.middleware(RpcRequestLifetime)).pipe(
562 Layer.provide(
563 Layer.mergeAll(
564 services,
565 lifetime,
566 Layer.succeed(RpcServer.Protocol, transport.protocol),
567 ),
568 ),
569 ),
570 memoMap,
571 instanceScope,
572 );
573 return {
574 webSocketMessage: transport.webSocketMessage,
575 webSocketClose: transport.webSocketClose,
576 webSocketError: transport.webSocketError,
577 fetch: Effect.gen(function* () {
578 const request = yield* HttpServerRequest;
579 return yield* request.headers.upgrade?.toLowerCase() === "websocket"
580 ? transport.fetch
581 : http;
582 }),
583 };
584 }),
585 (instanceScope, exit) =>
586 Exit.isFailure(exit) ? Scope.close(instanceScope, exit) : Effect.void,
587 );
588 });
589
590 const build = (
591 name: string,
592 props: RpcDurableObjectProps<any>,
593 impl: Effect.Effect<Effect.Effect<any>>,
594 ) => {
595 // Inline-impl class form: delegate to `DurableObject`'s
596 // inline class form, then expose the rpc-wrapped view at yield
597 // time. No `static from`/`static make` because the impl is provided
598 // eagerly here (consumers wanting cross-script binding use the
599 // modular form below).
600 const underlying = (DurableObject as any)()(name, wrapImpl(impl, props));
601 // `underlying` is itself an Effect now, no `.asEffect()` hop required.
602 const underlyingEff = underlying as Effect.Effect<DurableObjectType<any>, never, any>;
603 const rpcBound = underlyingEff.pipe(
604 Effect.map((rawNs) => rpcWrap(rawNs, props.schema)),
605 ) as unknown as Effect.Effect<RpcDurableObject<any>>;
606 return effectClass(rpcBound);
607 };
608
609 const buildModular = (name: string, props: RpcDurableObjectProps<any>) => {
610 const { schema } = props;
611 // Delegate to `DurableObject<Self>()(name)` (no-impl class
612 // form) so we inherit its Self-tag plumbing for free:
613 // - yielding the class resolves to the live namespace via the tag
614 // (populated by `static make(impl)`'s Layer)
615 // - `static from(scriptName | Worker)` registers a foreign-script
616 // binding on the surrounding worker and yields a fresh handle
617 // We just rpc-wrap each output so consumers see a typed `getByName`.
618 const Underlying: any = (DurableObject as any)()(name);
619 // `Underlying` is itself an Effect now, no `.asEffect()` hop required.
620 const underlyingEff = Underlying as Effect.Effect<DurableObjectType<any>, never, any>;
621
622 return class extends effectClass(
623 underlyingEff.pipe(Effect.map((rawNs) => rpcWrap(rawNs, schema))) as unknown as Effect.Effect<
624 RpcDurableObject<any>
625 >,
626 ) {
627 static make = (impl: Effect.Effect<Effect.Effect<any>>) =>
628 Underlying.make(wrapImpl(impl, props));
629
630 static from = (
631 worker: string | object | Effect.Effect<any, any, any>,
632 ): Effect.Effect<RpcDurableObject<any>, any, any> =>
633 Underlying.from(worker).pipe(
634 Effect.map((rawNs: DurableObjectType<any>) => rpcWrap(rawNs, schema)),
635 );
636 };
637 };