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
| 1 | import type * as cf from "@cloudflare/workers-types"; |
| 2 | import type { HttpEffect } from "alchemy/Http"; |
| 3 | import * as Output from "alchemy/Output"; |
| 4 | import type { FunctionContext, FunctionListener } from "alchemy/Runtime/Function"; |
| 5 | import { packEnvValueKeepRedacted, unpackEnvValue } from "alchemy/RuntimeContext"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import type { WorkflowExport } from "../Workflows/Workflow.ts"; |
| 10 | import type { DurableObjectExport } from "./DurableObject.ts"; |
| 11 | import { makeRequestHandler } from "./HttpServer.ts"; |
| 12 | import type { SqlMigrationsExport } from "./SqlMigrationsRuntime.ts"; |
| 13 | import { WebhookHostLive } from "./WebhookHost.ts"; |
| 14 | import { |
| 15 | ExportedHandlerMethods, |
| 16 | WorkerEnvironment, |
| 17 | WorkerTypeId, |
| 18 | type WorkerEvent, |
| 19 | } from "./WorkerRuntime.ts"; |
| 20 | |
| 21 | export type WorkerExport = DurableObjectExport | WorkflowExport | SqlMigrationsExport; |
| 22 | |
| 23 | export interface WorkerRuntimeContext extends FunctionContext { |
| 24 | export(name: string, value: any): Effect.Effect<void>; |
| 25 | shape: () => Record<string, any>; |
| 26 | } |
| 27 | |
| 28 | export const makeWorkerRuntimeContext = (id: string): WorkerRuntimeContext => { |
| 29 | const listeners: Effect.Effect<FunctionListener>[] = []; |
| 30 | const exports: Record<string, WorkerExport> = {}; |
| 31 | const env: Record<string, any> = {}; |
| 32 | let userShape: Record<string, unknown> | undefined; |
| 33 | |
| 34 | const ctx = { |
| 35 | Type: WorkerTypeId, |
| 36 | id, |
| 37 | env, |
| 38 | shape: () => userShape!, |
| 39 | get: (key: string) => |
| 40 | Effect.serviceOption(WorkerEnvironment).pipe( |
| 41 | Effect.map(Option.getOrUndefined), |
| 42 | // Key is already canonical (see RuntimeContext.sanitizeKey). Read |
| 43 | // straight from `WorkerEnvironment` — see `unpackEnvValue` for why |
| 44 | // this must never resolve through `Config.String`. |
| 45 | Effect.map((env) => unpackEnvValue(env?.[key])), |
| 46 | ) as any, |
| 47 | set: (key: string, output: Output.Output) => |
| 48 | Effect.sync(() => { |
| 49 | // `packEnvValueKeepRedacted` keeps the Redacted wrapper on the |
| 50 | // outside so the put-worker loop can deploy secrets via |
| 51 | // `secret_text` instead of leaking them as `plain_text`, while the |
| 52 | // inner marker lets the runtime `get` accessor rebuild the wrapper |
| 53 | // after Cloudflare hands the binding back as a plain string. |
| 54 | env[key] = output.pipe(Output.map(packEnvValueKeepRedacted)); |
| 55 | return key; |
| 56 | }), |
| 57 | serve: <Req = never>( |
| 58 | handler: HttpEffect<Req> | Effect.Effect<HttpEffect<Req>>, |
| 59 | options?: { shape?: Record<string, unknown> }, |
| 60 | ) => { |
| 61 | // Capture the user's full default-export shape so `exports` can |
| 62 | // expose any non-handler methods on it as RPC methods on the |
| 63 | // deployed `WorkerEntrypoint` subclass — see `__rpc__` below. |
| 64 | if (options?.shape) userShape = options.shape; |
| 65 | return ctx.listen(makeRequestHandler(handler)); |
| 66 | }, |
| 67 | listen: ((handler: FunctionListener | Effect.Effect<FunctionListener>) => |
| 68 | Effect.sync(() => |
| 69 | Effect.isEffect(handler) |
| 70 | ? listeners.push(handler) |
| 71 | : listeners.push(Effect.succeed(handler)), |
| 72 | )) as any as FunctionContext["listen"], |
| 73 | export: (name: string, value: any) => |
| 74 | Effect.sync(() => { |
| 75 | exports[name] = value; |
| 76 | }), |
| 77 | // Every Worker can receive webhooks, so event sources need no host wiring. |
| 78 | hostServices: WebhookHostLive, |
| 79 | planServices: Layer.mergeAll(Layer.succeed(WorkerEnvironment, {})), |
| 80 | exports: Effect.gen(function* () { |
| 81 | const handlers = yield* Effect.all(listeners, { |
| 82 | concurrency: "unbounded", |
| 83 | }); |
| 84 | const services = yield* Effect.context(); |
| 85 | |
| 86 | const dispatch = |
| 87 | (type: WorkerEvent["type"]) => |
| 88 | (request: any, env: unknown, context: cf.ExecutionContext) => { |
| 89 | const event: WorkerEvent = { |
| 90 | kind: "Cloudflare.Workers.WorkerEvent", |
| 91 | type, |
| 92 | input: request, |
| 93 | env, |
| 94 | context, |
| 95 | }; |
| 96 | const effects: Effect.Effect<unknown>[] = []; |
| 97 | for (const handler of handlers) { |
| 98 | const eff = handler(event); |
| 99 | if (Effect.isEffect(eff)) { |
| 100 | effects.push(eff); |
| 101 | } |
| 102 | } |
| 103 | if (effects.length === 1) { |
| 104 | return [effects[0], services]; |
| 105 | } |
| 106 | if (effects.length > 1) { |
| 107 | return [ |
| 108 | Effect.all(effects, { concurrency: "unbounded" }).pipe( |
| 109 | Effect.map((results) => { |
| 110 | for (const result of results) { |
| 111 | if (result instanceof Response) return result; |
| 112 | } |
| 113 | return results[results.length - 1]; |
| 114 | }), |
| 115 | ), |
| 116 | services, |
| 117 | ]; |
| 118 | } |
| 119 | return [ |
| 120 | Effect.die(new Error(`No event handler found for event type '${type}'`)), |
| 121 | services, |
| 122 | ]; |
| 123 | }; |
| 124 | |
| 125 | // RPC method dispatchers — one per non-handler method on the user's |
| 126 | // shape. Each dispatcher is invoked by the WorkerEntrypoint bridge |
| 127 | // as `dispatcher(args, ctx)`: `args` are the user-facing call args, |
| 128 | // `ctx` is the `this.ctx` that Cloudflare hands the bridge per RPC |
| 129 | // request. The dispatcher runs the user effect with the same runtime |
| 130 | // layer the fetch path uses, then envelope-encodes the result so |
| 131 | // `Effect.fail` round-trips as `RpcErrorEnvelope` and `Stream` as |
| 132 | // `RpcStreamEnvelope` (consumers wrap the binding with |
| 133 | // `toRpcAsync`/`bindWorker` to decode). |
| 134 | |
| 135 | return { |
| 136 | ...exports, |
| 137 | default: Object.fromEntries( |
| 138 | ExportedHandlerMethods.map((method) => [method, dispatch(method)]), |
| 139 | ), |
| 140 | }; |
| 141 | }), |
| 142 | }; |
| 143 | return ctx; |
| 144 | }; |