@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, 06:00 UTC

main
ts 314 lines 12.3 KB
Raw
1 import type * as workers from "@distilled.cloud/cloudflare/workers";
2 import type * as Output from "alchemy/Output";
3 import type { Rpc } from "alchemy/Rpc";
4 import { isYieldableEffectLike } from "alchemy/Util/effect";
5 import * as Config from "effect/Config";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import type { Json } from "effect/Schema";
9 import type { Gateway as AiGateway } from "../AI/Gateway.ts";
10 import type { SearchInstance } from "../AI/SearchInstance.ts";
11 import type { SearchNamespace } from "../AI/SearchNamespace.ts";
12 import { Dataset } from "../AnalyticsEngine/Dataset.ts";
13 import type { Namespace as ArtifactsNamespace } from "../Artifacts/Namespace.ts";
14 import type { Container } from "../Containers/Container.ts";
15 import type { Database as D1Database } from "../D1/Database.ts";
16 import { SendEmail } from "../Email/SendEmail.ts";
17 import type { App as FlagshipApp } from "../Flagship/App.ts";
18 import type { Connection as Hyperdrive } from "../Hyperdrive/Connection.ts";
19 import type { ConnectionLookup as HyperdriveLookup } from "../Hyperdrive/ConnectionLookup.ts";
20 import type { ImagesBinding } from "../Images/ImagesBinding.ts";
21 import type { Stream as K2Stream } from "../K2/Stream.ts";
22 import type { InstantNamespace } from "../KV/InstantNamespace.ts";
23 import type { Namespace } from "../KV/Namespace.ts";
24 import type { MtlsCertificate } from "../MtlsCertificate/MtlsCertificate.ts";
25 import type { LegacyPipeline } from "../Pipelines/LegacyPipeline.ts";
26 import type { Stream as PipelinesStream } from "../Pipelines/Stream.ts";
27 import type { Queue } from "../Queues/Queue.ts";
28 import type { Bucket } from "../R2/Bucket.ts";
29 import type { S3Credentials } from "../R2/S3Credentials.ts";
30 import type { Secret } from "../SecretsStore/Secret.ts";
31 import type { StreamBinding } from "../Stream/StreamBinding.ts";
32 import type { Index as VectorizeIndex } from "../Vectorize/VectorizeIndex.ts";
33 import type { VpcService } from "../VpcService/VpcService.ts";
34 import type { VpcServiceLookup } from "../VpcService/VpcServiceLookup.ts";
35 import type { DispatchNamespace } from "../WorkersForPlatforms/DispatchNamespace.ts";
36 import type { WorkflowLike } from "../Workflows/Workflow.ts";
37 import type { AIBinding } from "./AIBinding.ts";
38 import type { Assets } from "./Assets.ts";
39 import type { AnyBindingEffect } from "./Binding.ts";
40 import type { BrowserBinding } from "./BrowserBinding.ts";
41 import cloudflare_workers from "./cloudflare_workers.ts";
42 import type { DurableObjectLike } from "./DurableObject.ts";
43 import type { RateLimitBinding } from "./RateLimitBinding.ts";
44 import { makeRpcStub } from "./Rpc.ts";
45 import type { SecretKeyBinding } from "./SecretKeyBinding.ts";
46 import type { VersionMetadataBinding } from "./VersionMetadataBinding.ts";
47 import type { URLEffect } from "./Worker.ts";
48 import { Worker, WorkerEnvironment } from "./Worker.ts";
49 import type { WorkerEntrypointBinding } from "./WorkerEntrypoint.ts";
50 import type { WorkerLoader } from "./WorkerLoader.ts";
51
52 type DistilledWorkerBinding = Exclude<
53 workers.PutScriptRequest["metadata"]["bindings"],
54 undefined
55 >[number];
56
57 /**
58 * The `durable_object_namespace` metadata binding extended with alchemy-only
59 * transfer metadata. `transferredFrom` names the Worker(s) — by logical id in
60 * this stack + stage, or by physical script name — that previously hosted the
61 * class, so the provider can drive Cloudflare's data-preserving
62 * `transferred_classes` migration. It is stripped from the binding before the
63 * script upload — Cloudflare never sees it.
64 */
65 export type DurableObjectNamespaceWorkerBinding = Extract<
66 DistilledWorkerBinding,
67 { type: "durable_object_namespace" }
68 > & {
69 transferredFrom?: string | string[];
70 /** The class's declared storage backend; alchemy-only, never uploaded. */
71 storage?: "sqlite" | "legacy-kv";
72 };
73
74 /**
75 * Alchemy-only binding: the host Worker's own public URL (`Worker.URL`). The
76 * provider resolves the URL the Worker will be served at (first custom domain,
77 * else its `workers.dev` URL) and lowers this into a `plain_text` binding
78 * before the script upload — Cloudflare never sees this type.
79 */
80 export interface SelfUrlWorkerBinding {
81 type: "self_url";
82 name: string;
83 }
84
85 /**
86 * Alchemy-only binding: a service binding that points at the host Worker
87 * ITSELF (`Worker.Self`). The provider lowers this into a
88 * `service` binding targeting the Worker's own physical name just before
89 * the script upload — Cloudflare never sees this type. In local dev it
90 * lowers to the runtime's in-process self service (bypassing the assets
91 * middleware), matching production semantics.
92 *
93 * The canonical consumer is OpenNext's `WORKER_SELF_REFERENCE` (the ISR
94 * revalidation queue re-fetches the worker through it).
95 */
96 export interface SelfServiceWorkerBinding {
97 type: "self_service";
98 name: string;
99 /** Named `WorkerEntrypoint` class to target; omitted → default export. */
100 entrypoint?: string;
101 /** `ctx.props` delivered to the entrypoint. */
102 props?: Record<string, unknown>;
103 }
104
105 /**
106 * Alchemy-only, dev-only binding: R2 S3 credentials for a locally-emulated
107 * (`dev:`) bucket (`Cloudflare.R2.S3Credentials`). The local runtime lowers
108 * it into a text binding holding the credentials JSON for the Worker's local
109 * S3 endpoint (`{worker url}/cdn-cgi/local/r2/s3`) and serves the bucket on
110 * that endpoint. Deployed Workers receive a `secret_text` binding instead —
111 * Cloudflare never sees this type.
112 */
113 export interface R2S3CredentialsWorkerBinding {
114 type: "r2_s3_credentials";
115 name: string;
116 bucketName: string;
117 }
118
119 /**
120 * The `queue` metadata binding extended with the alchemy-only `queueId`.
121 * The local worker provider uses it to discriminate a locally-emulated
122 * queue (`dev:` id → local broker) from an `Alchemy.remote()` queue in dev
123 * (real id → remote-proxied producer). Stripped from the binding before
124 * the script upload — Cloudflare never sees it.
125 */
126 export type QueueWorkerBinding = Extract<DistilledWorkerBinding, { type: "queue" }> & {
127 queueId?: string;
128 /**
129 * Alchemy-only (stripped before upload): dev-mode remote-producer shim
130 * for an `Alchemy.remote()` queue. Cloudflare preview sessions reject
131 * queue bindings, so a local worker produces to the live queue through
132 * this deployed shim worker instead (see `Queues/QueueShim.ts`).
133 */
134 shim?: {
135 /** The shim worker's workers.dev URL. */
136 url: string | undefined;
137 /** Bearer token the shim requires. */
138 token: Redacted.Redacted<string> | string;
139 };
140 };
141
142 /**
143 * The `k2` metadata binding: produce-only access to a K2 stream, by stream
144 * id (`Cloudflare.K2.WriteStreamBinding`, or a `K2.Stream` in `env`).
145 */
146 export type K2WorkerBinding = Extract<DistilledWorkerBinding, { type: "k2" }>;
147
148 /**
149 * The `service` metadata binding extended with workerd's `ctx.props`.
150 * `props` is what a `Cloudflare.WorkerEntrypoint(worker, { props })` env
151 * entry lowers to; the local runtime delivers it to the target entrypoint.
152 * The Cloudflare API's binding schema does not carry the field yet, so on
153 * live uploads it is dropped at encode until the distilled `workers`
154 * service adds it.
155 */
156 export type ServiceWorkerBinding = Extract<DistilledWorkerBinding, { type: "service" }> & {
157 props?: Record<string, unknown>;
158 };
159
160 /**
161 * The wire-shape binding union the Cloudflare API accepts — {@link WorkerBinding}
162 * minus the alchemy-only members that must be lowered before upload.
163 */
164 export type WireWorkerBinding = Exclude<
165 WorkerBinding,
166 SelfUrlWorkerBinding | SelfServiceWorkerBinding | R2S3CredentialsWorkerBinding
167 >;
168
169 export type WorkerBinding =
170 | Exclude<
171 DistilledWorkerBinding,
172 { type: "durable_object_namespace" } | { type: "queue" } | { type: "service" }
173 >
174 | DurableObjectNamespaceWorkerBinding
175 | QueueWorkerBinding
176 | ServiceWorkerBinding
177 | SelfUrlWorkerBinding
178 | SelfServiceWorkerBinding
179 | R2S3CredentialsWorkerBinding;
180
181 /**
182 * Drop dev-only binding sentinels ({@link R2S3CredentialsWorkerBinding})
183 * before a live upload. They are only emitted for Workers running locally,
184 * so a live Worker never carries one; this narrows the type for the wire.
185 */
186 export const withoutDevOnlyBindings = <B extends WorkerBinding>(
187 bindings: ReadonlyArray<B>,
188 ): Array<Exclude<B, R2S3CredentialsWorkerBinding>> =>
189 bindings.filter(
190 (binding): binding is Exclude<B, R2S3CredentialsWorkerBinding> =>
191 binding.type !== "r2_s3_credentials",
192 );
193
194 export type WorkerSettingsBinding = Exclude<
195 workers.GetScriptScriptAndVersionSettingResponse["bindings"],
196 null | undefined
197 >[number];
198
199 export type WorkerBindingResource =
200 // Config values
201 | Json
202 | Redacted.Redacted<Json>
203 | Config.Config<Json>
204 // Outputs that resolve to a plain env value (e.g. `Alchemy.makeRandom`,
205 // `Output.literal`), classified by their resolved value at deploy time.
206 // Whole-resource Outputs (`Output.of(bucket)`) cannot be excluded here:
207 // `Input<T>` wraps this whole union in `Output<T>`, so any Output whose
208 // A is structurally Json (most resource attribute shapes) is admitted
209 // upstream regardless of this arm. `bindWorkerAsyncBindings` rejects
210 // them at deploy time instead.
211 | Output.Output<Json | Redacted.Redacted<Json>, unknown>
212 // CF resources
213 | Assets
214 | Bucket
215 | S3Credentials
216 | D1Database
217 | Namespace
218 | InstantNamespace
219 | Queue
220 | AiGateway
221 | AIBinding
222 | SearchInstance
223 | SearchNamespace
224 | Dataset
225 | SendEmail
226 | ArtifactsNamespace
227 | RateLimitBinding
228 | SecretKeyBinding
229 | BrowserBinding
230 | FlagshipApp
231 | ImagesBinding
232 | StreamBinding
233 | PipelinesStream
234 | LegacyPipeline
235 | K2Stream
236 | Hyperdrive
237 | HyperdriveLookup
238 | VectorizeIndex
239 | Secret
240 | Worker
241 | WorkerEntrypointBinding<any>
242 | WorkerLoader
243 | VersionMetadataBinding
244 // The Worker's own URL (`Worker.URL`).
245 | URLEffect
246 // A Worker-only binding lifted by `.pipe(Alchemy.remote())`.
247 | AnyBindingEffect
248 | DispatchNamespace
249 | DurableObjectLike<any>
250 | WorkflowLike<any>
251 | VpcService
252 | VpcServiceLookup
253 // An account-level mTLS certificate becomes an `mtls_certificate` binding.
254 | MtlsCertificate
255 // A Container bound directly in `env` declares a container-backed Durable
256 // Object class (DO namespace binding + ContainerApplication in one).
257 | Container.Decl.Any;
258
259 export type WorkerBindings = {
260 [bindingName in string]: WorkerBindingResource;
261 };
262
263 /**
264 * Whether `target` names the Worker being constructed. A Worker class only
265 * carries its static `LogicalId` (one logical id is one resource within a
266 * stack); a resolved resource carries its full `FQN`, so a `Worker.ref` to
267 * the same logical id in another stack or stage is not the host.
268 */
269 const isHostWorker = (target: unknown, host: Worker): boolean => {
270 if (typeof target !== "function" && (typeof target !== "object" || target === null)) {
271 return false;
272 }
273 if ("FQN" in target) return target.FQN === host.FQN;
274 return "LogicalId" in target && target.LogicalId === host.LogicalId;
275 };
276
277 export const bindWorker = Effect.fn(function* <Shape, Req = never>(
278 workerEff: (Worker & Rpc<Shape>) | Effect.Effect<Worker & Rpc<Shape>, never, Req>,
279 ) {
280 const self = yield* Worker;
281 if (isHostWorker(workerEff, self)) {
282 // A Worker binding itself. Yielding its own class here would wait on
283 // its own construction, and a service binding naming its own script is
284 // unnecessary: workerd's `ctx.exports.default` is a loopback to this
285 // Worker's default entrypoint, so nothing is deployed for the binding.
286 return makeRpcStub<Shape>(
287 cloudflare_workers.pipe(
288 Effect.map(({ exports }) => (exports as Record<string, unknown>).default),
289 ),
290 );
291 }
292 // Worker classes and regular Effects are both yieldable here.
293 const worker = isYieldableEffectLike(workerEff)
294 ? yield* workerEff as Effect.Effect<Worker & Rpc<Shape>, never, Req>
295 : workerEff;
296 yield* self.bind`${worker}`({
297 bindings: [
298 {
299 type: "service",
300 name: worker.LogicalId,
301 service: worker.workerName,
302 },
303 ],
304 });
305
306 // `bindWorker` runs at *init* phase (both at plantime and at runtime
307 // cold-start). `WorkerEnvironment` only exists at exec phase on the
308 // deployed worker, so we hand `makeRpcStub` an `Effect<stub>` that
309 // resolves the binding lazily on each method call.
310 const stubEff = WorkerEnvironment.pipe(
311 Effect.map((env) => (env as Record<string, unknown>)[worker.LogicalId]),
312 );
313 return makeRpcStub<Shape>(stubEff);
314 });