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 { |
| 2 | BindingHook, |
| 3 | BindingServices, |
| 4 | HyperdriveOrigin, |
| 5 | Assets as RuntimeAssets, |
| 6 | DurableObjectNamespace as RuntimeDurableObject, |
| 7 | QueueConsumer as RuntimeQueueConsumer, |
| 8 | RuntimeServices, |
| 9 | RuntimeWorker, |
| 10 | } from "@alchemy.run/cloudflare-runtime/core"; |
| 11 | import type { Artifacts } from "alchemy/Artifacts"; |
| 12 | import type * as Bundle from "alchemy/Bundle/Bundle"; |
| 13 | import type * as Context from "effect/Context"; |
| 14 | import * as Data from "effect/Data"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import type * as FileSystem from "effect/FileSystem"; |
| 17 | import type * as Path from "effect/Path"; |
| 18 | import type { PlatformError } from "effect/PlatformError"; |
| 19 | import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 20 | import type * as Scope from "effect/Scope"; |
| 21 | import type * as Stream from "effect/Stream"; |
| 22 | import type { AssetReadResult, ValidationError } from "./Assets.ts"; |
| 23 | import { getToolingCompatibility } from "./Compatibility.ts"; |
| 24 | import { makeInlineScriptSource } from "./Sources/InlineScript.ts"; |
| 25 | import { makePrebuiltSource } from "./Sources/Prebuilt.ts"; |
| 26 | import { isPythonMain, makePythonSource } from "./Sources/Python.ts"; |
| 27 | import { makeRolldownSource } from "./Sources/Rolldown.ts"; |
| 28 | import type { WorkerAssetsConfig, WorkerProps, WorkerSourceDescriptor } from "./Worker.ts"; |
| 29 | import type { WorkerExport } from "./WorkerRuntimeContext.ts"; |
| 30 | |
| 31 | /** |
| 32 | * The hash slots a Worker source contributes to |
| 33 | * `Worker["Attributes"]["hash"]`. Slots a source doesn't use are |
| 34 | * `undefined`. The `metadata` hash (#745) is deliberately NOT a source |
| 35 | * slot — it covers the deploy-time metadata surface and stays owned by |
| 36 | * the WorkerProvider. |
| 37 | */ |
| 38 | export interface SourceHash { |
| 39 | readonly bundle: string | undefined; |
| 40 | readonly assets: string | undefined; |
| 41 | readonly input: string | undefined; |
| 42 | /** |
| 43 | * Auxiliary metadata for the `input` hash (vite's auto-detected |
| 44 | * workspace directories, relative to the source root). Never compared |
| 45 | * as a change signal — only carried so the next `hash()` call can |
| 46 | * recompute `input` over the same workspace set. |
| 47 | */ |
| 48 | readonly additionalWorkspaces: string[] | undefined; |
| 49 | } |
| 50 | |
| 51 | export interface SourceBuildOutput { |
| 52 | /** |
| 53 | * Server bundle. `undefined` for assets-only workers (e.g. a static |
| 54 | * vite site with no server environment). |
| 55 | */ |
| 56 | readonly bundle: Bundle.BundleOutput | undefined; |
| 57 | /** |
| 58 | * Static assets, already read and manifest-hashed. `undefined` when the |
| 59 | * source doesn't own assets — the WorkerProvider merges in the |
| 60 | * props-level `assets` for those sources (see |
| 61 | * {@link SourceProvider.ownsAssets}). |
| 62 | */ |
| 63 | readonly assets: AssetReadResult | undefined; |
| 64 | /** Source-owned hash slots. Slots the source doesn't use are omitted. */ |
| 65 | readonly hash: Partial<SourceHash>; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Everything a source may need, derived once by the WorkerProvider from |
| 70 | * `(id, props, stack)`. Source-specific inputs (entry module path, vite |
| 71 | * options, inline script, ...) are closed over by the provider instance |
| 72 | * itself — providers are resolved per Worker from props, not injected |
| 73 | * once per stack. |
| 74 | */ |
| 75 | export interface SourceContext { |
| 76 | /** Resolved runtime storage directory, excluded from source inputs. */ |
| 77 | readonly dotAlchemy?: string; |
| 78 | /** Logical id of the Worker resource. */ |
| 79 | readonly id: string; |
| 80 | /** Namespace-qualified id (`ns/Worker`) — the display prefix for log lines. */ |
| 81 | readonly fqn: string; |
| 82 | /** Physical script name. */ |
| 83 | readonly workerName: string; |
| 84 | readonly compatibility: { |
| 85 | readonly date: string; |
| 86 | readonly flags: string[]; |
| 87 | }; |
| 88 | /** Effect-entry vs external-entry (async workers). Drives the virtual-entry plugin. */ |
| 89 | readonly entry: |
| 90 | | { readonly kind: "external" } |
| 91 | | { |
| 92 | readonly kind: "effect"; |
| 93 | readonly exports: Record<string, WorkerExport>; |
| 94 | }; |
| 95 | readonly stack: { readonly name: string; readonly stage: string }; |
| 96 | /** |
| 97 | * Raw `props.env`. Deliberately unresolved: env entries may be Effects |
| 98 | * whose evaluation requires plan-phase context that is not available |
| 99 | * inside lifecycle operations — a source that needs literal values |
| 100 | * (e.g. vite's `import.meta.env` defines) resolves them itself, exactly |
| 101 | * as the vite arm always has. |
| 102 | */ |
| 103 | readonly env: Record<string, unknown> | undefined; |
| 104 | /** |
| 105 | * This Worker's own URL, when it has one and an env entry refers to |
| 106 | * it (`Worker.URL`). Only the WorkerProvider knows it — a source that |
| 107 | * resolves `env` substitutes it for that entry. |
| 108 | */ |
| 109 | readonly selfUrl: string | undefined; |
| 110 | /** `props.build` passthrough for rolldown-based sources. */ |
| 111 | readonly extraOptions: Bundle.BundleExtraOptions | undefined; |
| 112 | /** |
| 113 | * Raw `props.assets`. Sources that own their assets (vite) merge its |
| 114 | * routing config into the assets they read out of the build; sources |
| 115 | * that don't own assets never touch it (the WorkerProvider reads and |
| 116 | * diffs props-level assets centrally). |
| 117 | */ |
| 118 | readonly assets: WorkerAssetsConfig | undefined; |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Runtime settings of a Worker beyond its bindings, Durable Objects, |
| 123 | * Hyperdrives, queue consumers and assets: cron triggers, Workflows, tail |
| 124 | * consumers, the Cache API, `request.cf`, the zone, Access and the workerd |
| 125 | * process overrides. |
| 126 | */ |
| 127 | export type DevWorkerOptions = Pick< |
| 128 | RuntimeWorker, |
| 129 | | "workflows" |
| 130 | | "crons" |
| 131 | | "tails" |
| 132 | | "streamingTails" |
| 133 | | "cache" |
| 134 | | "cf" |
| 135 | | "zone" |
| 136 | | "access" |
| 137 | | "workerd" |
| 138 | >; |
| 139 | |
| 140 | /** |
| 141 | * Runtime wiring for local dev, derived by the LocalWorkerProvider. |
| 142 | * Server-mode sources that embed their own workerd (the vite plugin) |
| 143 | * consume `worker` + `runtimeContext`; bundle-mode sources ignore both. |
| 144 | */ |
| 145 | export interface DevContext extends SourceContext { |
| 146 | readonly worker: { |
| 147 | readonly bindings: BindingHook<BindingServices>[]; |
| 148 | readonly durableObjectNamespaces: (RuntimeDurableObject & { |
| 149 | uniqueKey: string; |
| 150 | })[]; |
| 151 | readonly hyperdrives: Record<string, Required<HyperdriveOrigin>>; |
| 152 | /** Re-read on each (re)start so late-registered consumers are observed. */ |
| 153 | readonly queueConsumers: Effect.Effect<RuntimeQueueConsumer[]>; |
| 154 | readonly assets: RuntimeAssets | undefined; |
| 155 | /** |
| 156 | * The Worker's other runtime settings. A source that runs the Worker in |
| 157 | * workerd spreads them whole into its runtime Worker, so a setting added |
| 158 | * here reaches every source. |
| 159 | */ |
| 160 | readonly options: DevWorkerOptions; |
| 161 | }; |
| 162 | /** RuntimeServices context for providers that embed cloudflare-runtime. */ |
| 163 | readonly runtimeContext: Context.Context<RuntimeServices>; |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * How a source serves local dev. Two irreducible modes: |
| 168 | * |
| 169 | * - `bundle` — the host runs workerd; the source supplies rebuild events |
| 170 | * and the host restarts workerd with each successful bundle. |
| 171 | * - `server` — the source runs its own dev server (vite dev); the host |
| 172 | * points the WorkerProxy at `url`. |
| 173 | */ |
| 174 | export type SourceDevHandle = |
| 175 | | { |
| 176 | readonly mode: "bundle"; |
| 177 | readonly bundles: Stream.Stream<Bundle.BundleWatchEvent, SourceError, SourceDevServices>; |
| 178 | } |
| 179 | | { |
| 180 | readonly mode: "server"; |
| 181 | readonly url: URL; |
| 182 | /** Register an HTTP forwarding Worker when the server does not run in workerd. */ |
| 183 | readonly serviceBinding?: "http"; |
| 184 | }; |
| 185 | |
| 186 | /** |
| 187 | * The closed requirements channel of a source. Anything else a source |
| 188 | * needs (vite module loading, framework CLIs, workerd runtime services |
| 189 | * for dev) it constructs internally — external providers must NOT demand |
| 190 | * bespoke services from the WorkerProvider. |
| 191 | */ |
| 192 | export type SourceServices = |
| 193 | | FileSystem.FileSystem |
| 194 | | Path.Path |
| 195 | | ChildProcessSpawner |
| 196 | | Scope.Scope |
| 197 | | Artifacts; |
| 198 | |
| 199 | /** Requirements available to `dev()` (no per-run Artifacts cache in the local host). */ |
| 200 | export type SourceDevServices = |
| 201 | | FileSystem.FileSystem |
| 202 | | Path.Path |
| 203 | | ChildProcessSpawner |
| 204 | | Scope.Scope; |
| 205 | |
| 206 | /** |
| 207 | * An error raised by an external source provider, wrapped at the load |
| 208 | * boundary so the WorkerProvider's lifecycle error union stays closed. |
| 209 | */ |
| 210 | export class SourceProviderError extends Data.TaggedError( |
| 211 | "Cloudflare.Workers.SourceProviderError", |
| 212 | )<{ |
| 213 | /** Module specifier or built-in kind. */ |
| 214 | readonly provider: string; |
| 215 | readonly message: string; |
| 216 | readonly cause?: unknown; |
| 217 | }> {} |
| 218 | |
| 219 | export type SourceError = |
| 220 | | Bundle.BundleError |
| 221 | | ValidationError |
| 222 | | PlatformError |
| 223 | | SourceProviderError; |
| 224 | |
| 225 | /** |
| 226 | * A Worker source provider: supplies the static assets, the server |
| 227 | * bundle, and hashes for memoization, plus a dev-serving story. The five |
| 228 | * built-in arms (inline script, rolldown, python, prebuilt, vite) live in |
| 229 | * `Workers/Sources/`; framework providers implement the same interface. |
| 230 | */ |
| 231 | export interface SourceProvider { |
| 232 | /** |
| 233 | * Whether this source produces its own static assets from its build |
| 234 | * (vite, framework builds). When `false`, the WorkerProvider reads and |
| 235 | * diffs the props-level `assets` directory centrally — including the |
| 236 | * AssetsWithHash fast path — and the source only supplies the bundle. |
| 237 | */ |
| 238 | readonly ownsAssets: boolean; |
| 239 | |
| 240 | /** |
| 241 | * Whether a server-mode `dev()` hosts `ctx.worker.bindings` in a runtime |
| 242 | * whose assets service is configured: the Vite plugin (which serves |
| 243 | * `publicDir` and the app's HTML), or a platform proxy given the app's |
| 244 | * static directory. The host then adds the `ASSETS` binding to |
| 245 | * `ctx.worker.bindings`, as a deployed Worker with assets has it. Leave |
| 246 | * unset otherwise: the binding fails when the assets service is |
| 247 | * unconfigured. |
| 248 | * |
| 249 | * @default false |
| 250 | */ |
| 251 | readonly devAssetsBinding?: boolean; |
| 252 | |
| 253 | /** |
| 254 | * Full build. Called from reconcile (`putWorker`). If the build is |
| 255 | * expensive it MUST be memoized per run via `Artifacts.cached` under |
| 256 | * the same key `hash()` uses, so a diff that had to build doesn't |
| 257 | * build twice. |
| 258 | */ |
| 259 | readonly build: ( |
| 260 | ctx: SourceContext, |
| 261 | ) => Effect.Effect<SourceBuildOutput, SourceError, SourceServices>; |
| 262 | |
| 263 | /** |
| 264 | * Recompute the source-owned hash slots for diff, as cheaply as |
| 265 | * possible and WITHOUT a full build when the source supports it. |
| 266 | * `previous` is `output.hash` from state. Returns only the slots this |
| 267 | * source uses; the WorkerProvider compares slot-wise against |
| 268 | * `previous` — any defined slot that differs ⇒ update. |
| 269 | * |
| 270 | * Invariants: |
| 271 | * - MUST be deterministic for an unchanged source tree and |
| 272 | * machine-independent for identical bytes (never hash absolute paths). |
| 273 | * - If it cannot avoid building, it MUST route the build through the |
| 274 | * same `Artifacts.cached` key as `build()` so diff→reconcile builds |
| 275 | * once. |
| 276 | * - `previous` is a hint, never truth: a source must not skip |
| 277 | * recomputation because `previous` looks fresh — it may only use it |
| 278 | * for auxiliary inputs (`additionalWorkspaces`). |
| 279 | */ |
| 280 | readonly hash: ( |
| 281 | ctx: SourceContext, |
| 282 | previous: SourceHash | undefined, |
| 283 | ) => Effect.Effect<Partial<SourceHash>, SourceError, SourceServices>; |
| 284 | |
| 285 | /** |
| 286 | * Local dev. Scoped: closing the Scope stops the watcher / dev server. |
| 287 | */ |
| 288 | readonly dev: ( |
| 289 | ctx: DevContext, |
| 290 | ) => Effect.Effect<SourceDevHandle, SourceError, SourceDevServices | Scope.Scope>; |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * The contract of a dynamically-imported source-provider module: its |
| 295 | * default export builds a {@link SourceProvider} from the descriptor's |
| 296 | * (JSON-serializable) options. `make` provides the package's own layers |
| 297 | * internally, so the closed {@link SourceServices} requirement holds. |
| 298 | */ |
| 299 | export interface WorkerSourceModule { |
| 300 | readonly make: ( |
| 301 | options: unknown, |
| 302 | ) => Effect.Effect<SourceProvider, SourceProviderError, SourceServices>; |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Validated provider modules memoized per specifier for the process |
| 307 | * lifetime — a Worker resolves its source at least twice per deploy |
| 308 | * (diff, then reconcile). `make(options)` still runs per resolution: a |
| 309 | * stack can host several Workers of the same provider with different |
| 310 | * options. |
| 311 | */ |
| 312 | const sourceModules = new Map<string, WorkerSourceModule>(); |
| 313 | |
| 314 | const importSourceModule = ( |
| 315 | specifier: string, |
| 316 | ): Effect.Effect<WorkerSourceModule, SourceProviderError> => |
| 317 | Effect.suspend(() => { |
| 318 | const cached = sourceModules.get(specifier); |
| 319 | if (cached) { |
| 320 | return Effect.succeed(cached); |
| 321 | } |
| 322 | return Effect.tryPromise({ |
| 323 | try: () => import(/* @vite-ignore */ specifier), |
| 324 | catch: (cause) => |
| 325 | new SourceProviderError({ |
| 326 | provider: specifier, |
| 327 | message: |
| 328 | `Failed to import Worker source provider "${specifier}". ` + |
| 329 | `Is the package installed in your project? Install it and re-run.`, |
| 330 | cause, |
| 331 | }), |
| 332 | }).pipe( |
| 333 | Effect.flatMap((mod: { default?: Partial<WorkerSourceModule> }) => { |
| 334 | if (typeof mod.default?.make !== "function") { |
| 335 | return Effect.fail( |
| 336 | new SourceProviderError({ |
| 337 | provider: specifier, |
| 338 | message: |
| 339 | `Module "${specifier}" is not a Worker source provider: ` + |
| 340 | `its default export must satisfy WorkerSourceModule ({ make(options) }).`, |
| 341 | }), |
| 342 | ); |
| 343 | } |
| 344 | const module = mod.default as WorkerSourceModule; |
| 345 | sourceModules.set(specifier, module); |
| 346 | return Effect.succeed(module); |
| 347 | }), |
| 348 | ); |
| 349 | }); |
| 350 | |
| 351 | /** |
| 352 | * Load an external source provider from its serializable descriptor: |
| 353 | * dynamically import the module, validate the shape, and call |
| 354 | * `make(options)`. |
| 355 | */ |
| 356 | export const loadSource = ( |
| 357 | descriptor: WorkerSourceDescriptor, |
| 358 | ): Effect.Effect<SourceProvider, SourceProviderError, SourceServices> => |
| 359 | importSourceModule(descriptor.provider).pipe( |
| 360 | Effect.flatMap((mod) => mod.make(descriptor.options)), |
| 361 | ); |
| 362 | |
| 363 | /** |
| 364 | * Whether a Worker has no code at all — no `main`, `script`, `vite` or |
| 365 | * `source` — and only serves its `assets`. Every other Worker resolves a |
| 366 | * {@link SourceProvider} with {@link resolveSource}. |
| 367 | */ |
| 368 | export const isAssetsOnly = (props: WorkerProps) => |
| 369 | props.main === undefined && props.script === undefined && !props.vite && !props.source; |
| 370 | |
| 371 | /** |
| 372 | * Resolve the {@link SourceProvider} for a Worker from its props. The |
| 373 | * `source` descriptor (external providers) wins; legacy props map to the |
| 374 | * built-in providers, preserving the historical precedence exactly: |
| 375 | * `script` → `vite` → `.py` main → `bundle: false` → rolldown (default). |
| 376 | * |
| 377 | * `source` is mutually exclusive with `script`/`vite`/`main` — a source |
| 378 | * is self-contained, and a provider that needs a custom entry takes it |
| 379 | * in its own `options`. |
| 380 | */ |
| 381 | export const resolveSource = ( |
| 382 | props: WorkerProps, |
| 383 | ): Effect.Effect<SourceProvider, SourceProviderError, SourceServices> => { |
| 384 | if (props.source) { |
| 385 | const conflict = |
| 386 | props.script !== undefined |
| 387 | ? "script" |
| 388 | : props.vite |
| 389 | ? "vite" |
| 390 | : props.main !== undefined |
| 391 | ? "main" |
| 392 | : undefined; |
| 393 | if (conflict) { |
| 394 | return Effect.fail( |
| 395 | new SourceProviderError({ |
| 396 | provider: props.source.provider, |
| 397 | message: |
| 398 | `Worker prop "source" is mutually exclusive with "${conflict}": ` + |
| 399 | `a source provider is self-contained — pass a custom entry via the provider's own options instead.`, |
| 400 | }), |
| 401 | ); |
| 402 | } |
| 403 | return loadSource(props.source); |
| 404 | } |
| 405 | if (props.script !== undefined) { |
| 406 | return Effect.succeed(makeInlineScriptSource(props.script)); |
| 407 | } |
| 408 | if (props.vite) { |
| 409 | // Loaded lazily: `./Sources/Vite.ts` pulls in |
| 410 | // `@alchemy.run/cloudflare-runtime/vite` (~0.5s), which is only |
| 411 | // needed for vite-based workers — not for every Worker resolution. |
| 412 | const vite = props.vite; |
| 413 | return Effect.promise(() => import("./Sources/Vite.ts")).pipe( |
| 414 | Effect.map((Vite) => Vite.makeViteSource(vite)), |
| 415 | ); |
| 416 | } |
| 417 | if (isPythonMain(props.main)) { |
| 418 | return Effect.succeed(makePythonSource(props.main)); |
| 419 | } |
| 420 | if (props.bundle === false) { |
| 421 | return Effect.succeed(makePrebuiltSource({ main: props.main!, rules: props.rules })); |
| 422 | } |
| 423 | return Effect.succeed(makeRolldownSource({ main: props.main!, rules: props.rules })); |
| 424 | }; |
| 425 | |
| 426 | /** |
| 427 | * Derive the shared {@link SourceContext} from a Worker's props. Pure — |
| 428 | * the physical `workerName` is computed by the caller (it may come from |
| 429 | * persisted output state rather than the name generator). |
| 430 | */ |
| 431 | export const makeSourceContext = (params: { |
| 432 | dotAlchemy?: string; |
| 433 | id: string; |
| 434 | fqn: string; |
| 435 | workerName: string; |
| 436 | props: WorkerProps; |
| 437 | compatibility: { date: string; flags: string[] }; |
| 438 | stack: { name: string; stage: string }; |
| 439 | selfUrl?: string; |
| 440 | }): SourceContext => ({ |
| 441 | dotAlchemy: params.dotAlchemy, |
| 442 | id: params.id, |
| 443 | fqn: params.fqn, |
| 444 | workerName: params.workerName, |
| 445 | compatibility: getToolingCompatibility(params.compatibility, params.props.main), |
| 446 | entry: params.props.isExternal |
| 447 | ? { kind: "external" } |
| 448 | : { kind: "effect", exports: params.props.exports ?? {} }, |
| 449 | stack: { name: params.stack.name, stage: params.stack.stage }, |
| 450 | env: params.props.env, |
| 451 | selfUrl: params.selfUrl, |
| 452 | extraOptions: params.props.build, |
| 453 | assets: params.props.assets, |
| 454 | }); |