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 { RuntimeContext } from "alchemy/RuntimeContext"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import { fromCloudflareFetcher, type Fetcher } from "../Fetcher.ts"; |
| 7 | import { resolveAccessContext, type WorkerExecutionContextAccess } from "./WorkerAccess.ts"; |
| 8 | |
| 9 | export const WorkerTypeId = "Cloudflare.Worker"; |
| 10 | export type WorkerTypeId = typeof WorkerTypeId; |
| 11 | |
| 12 | export class WorkerEnvironment extends Context.Service<WorkerEnvironment, Record<string, any>>()( |
| 13 | "Cloudflare.Workers.WorkerEnvironment", |
| 14 | ) {} |
| 15 | |
| 16 | export class CachePurgeError extends Data.TaggedError("CachePurgeError")<{ |
| 17 | message: string; |
| 18 | cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | /** |
| 22 | * Effect-native view of the Workers Cache runtime API on the execution |
| 23 | * context (`ctx.cache`). Only available when the Worker has Workers Cache |
| 24 | * enabled (the `cache` prop or `yield* Cloudflare.cache()`). |
| 25 | */ |
| 26 | export interface WorkerExecutionContextCache { |
| 27 | /** |
| 28 | * Purge cached responses by `Cache-Tag`, path prefix, or everything. |
| 29 | */ |
| 30 | purge( |
| 31 | options: cf.CachePurgeOptions, |
| 32 | ): Effect.Effect<cf.CachePurgeResult, CachePurgeError, RuntimeContext>; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Raised by `ctx.exports.Name(...)` when this Worker has no loopback for the named |
| 37 | * entrypoint: the name is not an entrypoint exported by the Worker's main |
| 38 | * module, or `ctx.exports` is unavailable (the `disable_ctx_exports` |
| 39 | * compatibility flag). |
| 40 | */ |
| 41 | export class EntrypointUnavailableError extends Data.TaggedError("EntrypointUnavailableError")<{ |
| 42 | message: string; |
| 43 | entrypoint: string; |
| 44 | }> {} |
| 45 | |
| 46 | /** |
| 47 | * Options for minting a loopback stub to one of this Worker's own |
| 48 | * entrypoints. See {@link WorkerExecutionContext} `exports`. |
| 49 | */ |
| 50 | export interface EntrypointOptions { |
| 51 | /** |
| 52 | * Properties the target entrypoint reads from `ctx.props` — via |
| 53 | * `WorkerExecutionContext.props` in an Effect Worker. Must be |
| 54 | * structured-cloneable. |
| 55 | */ |
| 56 | props?: Record<string, unknown>; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Mint a {@link Fetcher} for an entrypoint of this Worker from workerd's |
| 61 | * `exports` loopback (`ctx.exports[name]({ props })`), shared by |
| 62 | * {@link WorkerExecutionContext} and `DurableObjectState`. |
| 63 | * @internal |
| 64 | */ |
| 65 | export const getLoopbackEntrypoint = ( |
| 66 | exports: cf.ExecutionContext["exports"] | undefined, |
| 67 | name = "default", |
| 68 | options?: EntrypointOptions, |
| 69 | ): Effect.Effect<Fetcher, EntrypointUnavailableError> => |
| 70 | Effect.suspend(() => { |
| 71 | const loopback = (exports as Record<string, unknown> | undefined)?.[name]; |
| 72 | if (typeof loopback !== "function") { |
| 73 | return Effect.fail( |
| 74 | new EntrypointUnavailableError({ |
| 75 | entrypoint: name, |
| 76 | message: |
| 77 | exports === undefined |
| 78 | ? `ctx.exports is not available, so entrypoint "${name}" cannot be ` + |
| 79 | "minted — remove the `disable_ctx_exports` compatibility flag." |
| 80 | : `"${name}" is not a WorkerEntrypoint exported by this Worker's main module.`, |
| 81 | }), |
| 82 | ); |
| 83 | } |
| 84 | return Effect.succeed( |
| 85 | fromCloudflareFetcher( |
| 86 | (loopback as (opts: { props?: Record<string, unknown> }) => cf.Fetcher)({ |
| 87 | props: options?.props ?? {}, |
| 88 | }), |
| 89 | ), |
| 90 | ); |
| 91 | }); |
| 92 | |
| 93 | /** |
| 94 | * This Worker's own entrypoints, by export name (`default` for the Worker's |
| 95 | * own Effect handlers): the Effect view of workerd's `ctx.exports`. Calling |
| 96 | * one mints a stub that delivers `props` as the target's `ctx.props`. |
| 97 | */ |
| 98 | export type EntrypointExports = { |
| 99 | readonly [name: string]: ( |
| 100 | options?: EntrypointOptions, |
| 101 | ) => Effect.Effect<Fetcher, EntrypointUnavailableError, RuntimeContext>; |
| 102 | }; |
| 103 | |
| 104 | /** |
| 105 | * Build {@link EntrypointExports} over a lookup of workerd's `exports` |
| 106 | * (resolved when an entry is called, not when it is read). |
| 107 | * @internal |
| 108 | */ |
| 109 | export const makeEntrypointExports = ( |
| 110 | call: ( |
| 111 | name: string, |
| 112 | options?: EntrypointOptions, |
| 113 | ) => Effect.Effect<Fetcher, EntrypointUnavailableError, RuntimeContext>, |
| 114 | ): EntrypointExports => |
| 115 | new Proxy({} as EntrypointExports, { |
| 116 | get: (_, name) => |
| 117 | typeof name === "string" ? (options?: EntrypointOptions) => call(name, options) : undefined, |
| 118 | }); |
| 119 | |
| 120 | /** |
| 121 | * The shape of {@link WorkerExecutionContext}. |
| 122 | */ |
| 123 | export interface WorkerExecutionContextService { |
| 124 | /** |
| 125 | * Run an Effect in the background without blocking the response, keeping |
| 126 | * the Worker alive until it settles. The Effect runs with the caller's |
| 127 | * full context (services, tracing), and the resulting promise is |
| 128 | * registered with workerd's `ctx.waitUntil`. |
| 129 | * |
| 130 | * `Cloudflare.waitUntil` is shorthand that skips yielding the context |
| 131 | * first: |
| 132 | * |
| 133 | * ```typescript |
| 134 | * yield* Cloudflare.waitUntil(writeAuditLog(event)); |
| 135 | * // same as |
| 136 | * yield* (yield* Cloudflare.WorkerExecutionContext).waitUntil(writeAuditLog(event)); |
| 137 | * ``` |
| 138 | */ |
| 139 | waitUntil<A, E, R>( |
| 140 | effect: Effect.Effect<A, E, R>, |
| 141 | ): Effect.Effect<void, never, R | RuntimeContext>; |
| 142 | /** |
| 143 | * Forward the request to the origin if the Worker throws an unhandled |
| 144 | * exception, instead of returning an error page. |
| 145 | */ |
| 146 | passThroughOnException(): Effect.Effect<void, never, RuntimeContext>; |
| 147 | /** |
| 148 | * The Workers Cache runtime API (`ctx.cache`). |
| 149 | */ |
| 150 | readonly cache: WorkerExecutionContextCache; |
| 151 | /** |
| 152 | * The Cloudflare Access context for the current request (`ctx.access`), |
| 153 | * or `undefined` when the request did not pass through Access. Under |
| 154 | * `alchemy dev` the Worker's `dev.access` config simulates it. |
| 155 | */ |
| 156 | readonly access: Effect.Effect<WorkerExecutionContextAccess | undefined, never, RuntimeContext>; |
| 157 | /** |
| 158 | * The properties this invocation was called with (`ctx.props`): the |
| 159 | * `props` of the service binding or loopback stub the caller went |
| 160 | * through, e.g. `Cloudflare.WorkerEntrypoint(worker, { props })` or |
| 161 | * {@link exports}. An empty object for an external request. |
| 162 | */ |
| 163 | readonly props: Effect.Effect<Record<string, unknown>, never, RuntimeContext>; |
| 164 | /** |
| 165 | * This Worker's own entrypoints (workerd's `ctx.exports`): |
| 166 | * `yield* ctx.exports.default({ props })` mints a stub to the Worker's |
| 167 | * own Effect handlers that delivers `props` as the target's `ctx.props`; |
| 168 | * `ctx.exports.Name(...)` targets a named `WorkerEntrypoint`. The |
| 169 | * {@link Fetcher} can be passed to APIs that route traffic to a Worker |
| 170 | * entrypoint, such as a container's `interceptOutboundHttps` or a |
| 171 | * dynamic Worker's `globalOutbound`; its `raw` is the native `Fetcher`. |
| 172 | */ |
| 173 | readonly exports: EntrypointExports; |
| 174 | /** |
| 175 | * The raw workerd ExecutionContext, for interop with async APIs. |
| 176 | */ |
| 177 | readonly raw: cf.ExecutionContext; |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * The workerd `ExecutionContext` of the current event. |
| 182 | * |
| 183 | * A `Context.Reference`: the Worker's init phase (plan and runtime module |
| 184 | * init) never stores it, so yielding it there returns |
| 185 | * {@link deferredExecutionContext}, whose methods resolve the live per-event |
| 186 | * context when run inside a handler. Because init never stores the key, a |
| 187 | * context captured at init (e.g. by `HttpApiBuilder.group`, which re-provides |
| 188 | * its build-time context over each handler) can't shadow the per-event one |
| 189 | * the bridge provides. |
| 190 | */ |
| 191 | export const WorkerExecutionContext = Context.Reference<WorkerExecutionContextService>( |
| 192 | "Cloudflare.Workers.WorkerExecutionContext", |
| 193 | { defaultValue: () => deferredExecutionContext }, |
| 194 | ); |
| 195 | export type WorkerExecutionContext = typeof WorkerExecutionContext; |
| 196 | |
| 197 | export const fromExecutionContext = ( |
| 198 | ctx: cf.ExecutionContext, |
| 199 | env?: Record<string, unknown>, |
| 200 | ): WorkerExecutionContextService => ({ |
| 201 | raw: ctx, |
| 202 | access: Effect.sync(() => resolveAccessContext(ctx, env)), |
| 203 | props: Effect.sync(() => (ctx.props as Record<string, unknown> | undefined) ?? {}), |
| 204 | exports: makeEntrypointExports((name, options) => |
| 205 | getLoopbackEntrypoint(ctx.exports, name, options), |
| 206 | ), |
| 207 | waitUntil: <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 208 | Effect.gen(function* () { |
| 209 | const context = yield* Effect.context<R>(); |
| 210 | // Register the promise with workerd un-awaited — waitUntil extends the |
| 211 | // invocation's lifetime without blocking the response. |
| 212 | yield* Effect.sync(() => ctx.waitUntil(Effect.runPromiseWith(context)(effect))); |
| 213 | }), |
| 214 | passThroughOnException: () => Effect.sync(() => ctx.passThroughOnException()), |
| 215 | cache: { |
| 216 | purge: (options) => |
| 217 | ctx.cache |
| 218 | ? Effect.tryPromise({ |
| 219 | try: () => ctx.cache!.purge(options), |
| 220 | catch: (cause) => |
| 221 | new CachePurgeError({ |
| 222 | message: cause instanceof Error ? cause.message : "Unknown cache purge error", |
| 223 | cause, |
| 224 | }), |
| 225 | }) |
| 226 | : Effect.fail( |
| 227 | new CachePurgeError({ |
| 228 | message: |
| 229 | "ctx.cache is not available — enable Workers Cache on this " + |
| 230 | "Worker (the `cache` prop or `yield* Cloudflare.cache()`) " + |
| 231 | "and note it is not supported in local dev.", |
| 232 | }), |
| 233 | ), |
| 234 | }, |
| 235 | }); |
| 236 | |
| 237 | /** |
| 238 | * A {@link WorkerExecutionContext} whose methods resolve the live per-event |
| 239 | * context from the calling fiber at call time. The reference's default, so |
| 240 | * the service can be yielded and closed over in the Worker's top-level |
| 241 | * closure; every method is colored with |
| 242 | * `RuntimeContext`, so it can only be *run* inside a handler, where the |
| 243 | * bridge provides the real per-event context that these methods defer to. |
| 244 | */ |
| 245 | export const deferredExecutionContext: WorkerExecutionContextService = { |
| 246 | get raw(): cf.ExecutionContext { |
| 247 | throw new Error("WorkerExecutionContext.raw is only available inside a request handler"); |
| 248 | }, |
| 249 | waitUntil: <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 250 | liveExecutionContext.pipe(Effect.flatMap((live) => live.waitUntil(effect))) as Effect.Effect< |
| 251 | void, |
| 252 | never, |
| 253 | R | RuntimeContext |
| 254 | >, |
| 255 | passThroughOnException: () => |
| 256 | liveExecutionContext.pipe( |
| 257 | Effect.flatMap((live) => live.passThroughOnException()), |
| 258 | ) as Effect.Effect<void, never, RuntimeContext>, |
| 259 | cache: { |
| 260 | purge: (options) => |
| 261 | liveExecutionContext.pipe( |
| 262 | Effect.flatMap((live) => live.cache.purge(options)), |
| 263 | ) as Effect.Effect<cf.CachePurgeResult, CachePurgeError, RuntimeContext>, |
| 264 | }, |
| 265 | exports: makeEntrypointExports( |
| 266 | (name, options) => |
| 267 | liveExecutionContext.pipe( |
| 268 | Effect.flatMap((live) => live.exports[name](options)), |
| 269 | ) as Effect.Effect<Fetcher, EntrypointUnavailableError, RuntimeContext>, |
| 270 | ), |
| 271 | get props() { |
| 272 | return liveExecutionContext.pipe(Effect.flatMap((live) => live.props)) as Effect.Effect< |
| 273 | Record<string, unknown>, |
| 274 | never, |
| 275 | RuntimeContext |
| 276 | >; |
| 277 | }, |
| 278 | // A getter so this module-level literal doesn't eagerly reference |
| 279 | // `liveExecutionContext` before its declaration below. |
| 280 | get access() { |
| 281 | return liveExecutionContext.pipe(Effect.flatMap((live) => live.access)) as Effect.Effect< |
| 282 | WorkerExecutionContextAccess | undefined, |
| 283 | never, |
| 284 | RuntimeContext |
| 285 | >; |
| 286 | }, |
| 287 | }; |
| 288 | |
| 289 | const liveExecutionContext = WorkerExecutionContext.pipe( |
| 290 | Effect.flatMap((live) => |
| 291 | live === deferredExecutionContext |
| 292 | ? Effect.die(new Error("WorkerExecutionContext can only be used inside a request handler")) |
| 293 | : Effect.succeed(live), |
| 294 | ), |
| 295 | ); |
| 296 | |
| 297 | /** |
| 298 | * Run an Effect in the background without blocking the response, keeping the |
| 299 | * Worker alive until it settles. Shorthand for |
| 300 | * `(yield* WorkerExecutionContext).waitUntil(effect)`. |
| 301 | * |
| 302 | * @example |
| 303 | * ```typescript |
| 304 | * fetch: Effect.gen(function* () { |
| 305 | * yield* Cloudflare.waitUntil(writeAuditLog(event)); |
| 306 | * return HttpServerResponse.text("accepted", { status: 202 }); |
| 307 | * }), |
| 308 | * ``` |
| 309 | */ |
| 310 | export const waitUntil = <A, E, R>( |
| 311 | effect: Effect.Effect<A, E, R>, |
| 312 | ): Effect.Effect<void, never, R | RuntimeContext> => |
| 313 | WorkerExecutionContext.pipe(Effect.flatMap((ctx) => ctx.waitUntil(effect))); |
| 314 | |
| 315 | export type WorkerEvent = Exclude< |
| 316 | { |
| 317 | [type in keyof cf.ExportedHandler]: { |
| 318 | kind: "Cloudflare.Workers.WorkerEvent"; |
| 319 | type: type; |
| 320 | input: Parameters<Exclude<cf.ExportedHandler[type], undefined>>[0]; |
| 321 | env: Parameters<Exclude<cf.ExportedHandler[type], undefined>>[1]; |
| 322 | context: Parameters<Exclude<cf.ExportedHandler[type], undefined>>[2]; |
| 323 | }; |
| 324 | }[keyof cf.ExportedHandler], |
| 325 | undefined |
| 326 | >; |
| 327 | |
| 328 | export const isWorkerEvent = (value: any): value is WorkerEvent => |
| 329 | value?.kind === "Cloudflare.Workers.WorkerEvent"; |
| 330 | |
| 331 | export const ExportedHandlerMethods = [ |
| 332 | "fetch", |
| 333 | "tail", |
| 334 | "trace", |
| 335 | "tailStream", |
| 336 | "scheduled", |
| 337 | "test", |
| 338 | "email", |
| 339 | "queue", |
| 340 | ] as const satisfies (keyof cf.ExportedHandler)[]; |