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

main
ts 842 lines 31.7 KB
Raw
1 import type { InputProps } from "alchemy/Input";
2 import * as Namespace from "alchemy/Namespace";
3 import * as Output from "alchemy/Output";
4 import { defaultProviderMode } from "alchemy/ProviderMode";
5 import type { ResourceBinding } from "alchemy/Resource";
6 import { isYieldableEffectLike } from "alchemy/Util/effect";
7 import * as Effect from "effect/Effect";
8 import * as Redacted from "effect/Redacted";
9 import type { Json } from "effect/Schema";
10 import {
11 Application,
12 isApplication,
13 type Application as AccessApplication,
14 } from "../Access/Application.ts";
15 import { isAiGateway } from "../AI/Gateway.ts";
16 import { isSearchInstance } from "../AI/SearchInstance.ts";
17 import { isSearchNamespace } from "../AI/SearchNamespace.ts";
18 import { isDataset } from "../AnalyticsEngine/Dataset.ts";
19 import { isNamespace } from "../Artifacts/Namespace.ts";
20 import type { Container } from "../Containers/Container.ts";
21 import type { ContainerApplication } from "../Containers/ContainerApplication.ts";
22 import {
23 containerApplicationSettings,
24 DurableObjectContainerBindingError,
25 durableObjectContainerBinding,
26 isDurableObjectContainerResource,
27 workerContainerBinding,
28 } from "../Containers/ContainerConfiguration.ts";
29 import { declareDurableObjectApplication } from "../Containers/DurableObjectApplication.ts";
30 import { isDatabase } from "../D1/Database.ts";
31 import { isSendEmail } from "../Email/SendEmail.ts";
32 import { isApp } from "../Flagship/App.ts";
33 import { getHyperdriveDevOriginForHost } from "../Hyperdrive/ConnectBinding.ts";
34 import { isHyperdriveConnection } from "../Hyperdrive/Connection.ts";
35 import { isImages } from "../Images/Images.ts";
36 import { isStream as isK2Stream } from "../K2/Stream.ts";
37 import { isInstantNamespace } from "../KV/InstantNamespace.ts";
38 import { isNamespace as isKVNamespace } from "../KV/Namespace.ts";
39 import { isMtlsCertificate } from "../MtlsCertificate/MtlsCertificate.ts";
40 import { isLegacyPipeline } from "../Pipelines/LegacyPipeline.ts";
41 import { isStream as isPipelinesStream } from "../Pipelines/Stream.ts";
42 import { isQueue } from "../Queues/Queue.ts";
43 import { maybeQueueShim } from "../Queues/QueueShim.ts";
44 import { isBucket } from "../R2/Bucket.ts";
45 import { bindS3Credentials, isS3Credentials, resolveBucket } from "../R2/S3CredentialsBinding.ts";
46 import { isSecret } from "../SecretsStore/Secret.ts";
47 import { isStream } from "../Stream/Stream.ts";
48 import { isIndex } from "../Vectorize/VectorizeIndex.ts";
49 import { isVpcService } from "../VpcService/VpcService.ts";
50 import type { VpcServiceLookup } from "../VpcService/VpcServiceLookup.ts";
51 import { isDispatchNamespace } from "../WorkersForPlatforms/DispatchNamespace.ts";
52 import { isWorkflowLike, WorkflowResource, type WorkflowBinding } from "../Workflows/Workflow.ts";
53 import { asScriptNameOutput, makeWorkflowName } from "../Workflows/WorkflowName.ts";
54 import { isAI } from "./AI.ts";
55 import { isAssets } from "./Assets.ts";
56 import { isBinding as isWorkerOnlyBinding } from "./Binding.ts";
57 import { isBrowser } from "./Browser.ts";
58 import {
59 type DurableObjectLike,
60 isDurableObjectLike,
61 normalizeTransferredFrom,
62 } from "./DurableObject.ts";
63 import { isRateLimit } from "./RateLimit.ts";
64 import { isSecretKey } from "./SecretKey.ts";
65 import { isVersionMetadata } from "./VersionMetadata.ts";
66 import type { WorkerBindingProps } from "./Worker.ts";
67 import {
68 isSelf,
69 isSelfUrl,
70 isWorker,
71 type Worker,
72 type WorkerObservability,
73 type WorkerProps,
74 } from "./Worker.ts";
75 import type { WorkerAccessApplication } from "./WorkerAccess.ts";
76 import type { WorkerBinding, WorkerBindingResource } from "./WorkerBinding.ts";
77 import { isWorkerEntrypoint } from "./WorkerEntrypoint.ts";
78 import { isWorkerLoader } from "./WorkerLoader.ts";
79
80 export const bindWorkerAsyncBindings = Effect.fn(function* (
81 resource: Worker,
82 props: InputProps<WorkerProps<WorkerBindingProps>>,
83 ) {
84 if (globalThis.__ALCHEMY_RUNTIME__) return;
85
86 // Access enrollment (`access` prop): push this Worker's
87 // `worker`/`preview_worker` destinations onto the application's binding
88 // contract. The application deploys with — and converges on — every
89 // enrolled Worker's destinations, including at create time, where
90 // Cloudflare requires a self-hosted app to be born with a domain or
91 // destinations.
92 //
93 // Skipped when this Worker runs locally (`alchemy dev`): a local worker
94 // has no cloud script (no immutable ID to enroll), and Access cannot
95 // front a localhost URL — the `dev.access` stub covers the runtime
96 // instead. A Worker opted out via `Alchemy.remote()` enrolls normally.
97 const accessHostMode = resource.Mode ?? (yield* defaultProviderMode);
98 if (props.access && accessHostMode !== "local") {
99 const accessInput = props.access;
100 // The shared form is the application itself — as the module-scope
101 // declaration Effect (`const App = Cloudflare.Access.Application(...)`)
102 // or an already-yielded resource. Resolve the yieldable spelling first,
103 // then discriminate.
104 const access = (
105 isYieldableEffectLike(accessInput) && !Output.isOutput(accessInput)
106 ? yield* accessInput as Effect.Effect<unknown>
107 : accessInput
108 ) as AccessApplication | InputProps<WorkerAccessApplication>;
109 const application = isApplication(access)
110 ? access
111 : // Dedicated form: declare an application owned by this Worker —
112 // per-Worker Access configuration means a per-Worker application
113 // (Cloudflare attaches policies to applications, not Workers). It
114 // lives in the Worker's namespace: `<Worker>/Access`.
115 yield* Application("Access", {
116 type: "self_hosted",
117 name: access.name,
118 policies: access.policies,
119 sessionDuration: access.sessionDuration,
120 allowedIdps: access.allowedIdps,
121 autoRedirectToIdentity: access.autoRedirectToIdentity,
122 appLauncherVisible: access.appLauncherVisible,
123 }).pipe(Namespace.push(resource.LogicalId));
124 const previews = isApplication(access) || access.previews !== false;
125 yield* application.bind(`enroll:${resource.FQN}`, {
126 destinations: [
127 { type: "worker", workerId: resource.workerId },
128 ...(previews
129 ? [
130 {
131 type: "preview_worker" as const,
132 workerId: resource.workerId,
133 },
134 ]
135 : []),
136 ],
137 });
138 }
139 const env: Record<string, unknown> = props.assets
140 ? { ASSETS: { kind: "Cloudflare.Workers.Assets" } }
141 : {};
142 if (props.env) {
143 for (const bindingName in props.env) {
144 // @ts-expect-error
145 const bindingEff = props.env?.[bindingName] as
146 | WorkerBindingResource
147 | Effect.Effect<WorkerBindingResource>;
148 // A Container bound directly in `env` declares a container-backed
149 // Durable Object class: the Container IS the DO namespace binding plus
150 // its ContainerApplication. Handled before the generic Effect
151 // resolution below — yielding the Container class would resolve its
152 // *started instance* tag, which only exists inside a Durable Object.
153 if (isContainerDecl(bindingEff)) {
154 env[bindingName] = bindingEff;
155 yield* bindContainerClass(resource, bindingName, bindingEff);
156 continue;
157 }
158 // `Cloudflare.R2.S3Credentials` is also an Effect (its Effect-native
159 // form resolves to a runtime accessor): bind its deploy-time half under
160 // the env key instead of yielding it.
161 if (isS3Credentials(bindingEff)) {
162 env[bindingName] = bindingEff;
163 yield* bindS3Credentials(
164 resource,
165 bindingName,
166 yield* resolveBucket(bindingEff.bucket),
167 bindingEff.access,
168 );
169 continue;
170 }
171 // Bindings can be passed as a plain resource value, an Effect that
172 // yields a resource, or an effect-class (e.g. a `Cloudflare.Worker`
173 // class). Resolve the yieldable forms before deriving binding metadata.
174 // Avoid yielding outputs as this requires `RuntimeContext`;
175 // allow the engine to resolve them instead.
176 const binding = (
177 isYieldableEffectLike(bindingEff) && !Output.isOutput(bindingEff)
178 ? yield* bindingEff as Effect.Effect<unknown>
179 : bindingEff
180 ) as WorkerBindingResource;
181 env[bindingName] = binding;
182
183 // Queue producer bindings may need the dev-mode remote-producer shim
184 // (a LOCAL worker binding a LIVE queue): `maybeQueueShim` registers
185 // the shim worker + token resources at eval time — the same idiom as
186 // the WorkflowResource registration below — and contributes their
187 // outputs to the binding data.
188 if (isQueue(binding)) {
189 const shim = yield* maybeQueueShim(binding, resource);
190 yield* resource.bind`${bindingName}`({
191 bindings: [
192 {
193 type: "queue",
194 name: bindingName,
195 queueName: binding.queueName,
196 // Alchemy-only mode discriminator for dev (stripped before
197 // upload).
198 queueId: binding.queueId,
199 ...(shim ? { shim } : {}),
200 },
201 ],
202 });
203 continue;
204 }
205
206 const bindingMeta: BindingSpec | Output.Output<WorkerBinding> | undefined = toBinding(
207 bindingName,
208 binding,
209 );
210
211 if (Output.isOutput(bindingMeta)) {
212 // A whole-resource Output resolves to the resource's raw attributes;
213 // uploading those as a plaintext json env var is never intended.
214 // This cannot be rejected at compile time (`Input<T>` admits any
215 // Output whose A is structurally Json), so this guard is the
216 // enforcement point.
217 if (Output.isResourceExpr(binding) || Output.isRefExpr(binding)) {
218 return yield* Effect.die(
219 `Cannot bind whole-resource Output "${bindingName}": pass the resource (or a typed ref) directly, or bind one of its attribute Outputs`,
220 );
221 }
222 // Deferred classification (see `toBinding`'s Output arm): the engine
223 // resolves the Output inside the binding data before the Worker
224 // provider reads it.
225 yield* resource.bind`${bindingName}`({ bindings: [bindingMeta] });
226 continue;
227 }
228
229 if (bindingMeta) {
230 let resolvedBindingMeta: InputProps<WorkerBinding> = bindingMeta;
231
232 if (isWorkflowLike(binding)) {
233 const className = binding.className ?? binding.name;
234 const scriptName = binding.scriptName ?? resource.workerName;
235 const workflowName = binding.workflowName ?? makeWorkflowName(scriptName, className);
236 resolvedBindingMeta = {
237 ...resolvedBindingMeta,
238 workflowName,
239 };
240
241 // A locally-hosted Workflow (no `scriptName`) must be registered
242 // with Cloudflare via `putWorkflow` once the host Worker exists.
243 // Cross-script references are binding-only; both sides use the
244 // explicit physical name when supplied, or derive the same default
245 // from the host script and class.
246 const workflow = binding.scriptName
247 ? undefined
248 : yield* WorkflowResource(binding.name, {
249 workflowName: binding.workflowName,
250 className,
251 scriptName: binding.workflowName === undefined ? resource.workerName : undefined,
252 limits: binding.limits,
253 schedules: binding.schedules,
254 jurisdiction: binding.jurisdiction,
255 });
256 if (workflow) {
257 // Host linkage must not block the named identity's adoption probe.
258 if (binding.workflowName !== undefined) {
259 yield* workflow.bind`${resource}`({
260 scriptName: resource.workerName,
261 });
262 }
263 resolvedBindingMeta = {
264 ...resolvedBindingMeta,
265 workflowName: binding.workflowName ?? workflow.workflowName,
266 };
267 }
268
269 // Local outputs depend on registration and preserve deployed identity.
270 env[bindingName] = {
271 kind: binding.kind,
272 name: binding.name,
273 className,
274 workflowName: workflow ? workflow.workflowName : Output.asOutput(workflowName),
275 scriptName: workflow ? workflow.scriptName : asScriptNameOutput(scriptName),
276 } satisfies WorkflowBinding;
277 }
278
279 // Durable Object-managed Containers attached to a hosted class. Both
280 // halves describe this env entry, so they share its `sid`.
281 const containers =
282 isDurableObjectLike(binding) && binding.containers?.length
283 ? yield* bindDurableObjectContainers(resource, bindingName, binding)
284 : undefined;
285
286 yield* resource.bind`${bindingName}`({
287 bindings: [resolvedBindingMeta],
288 containers,
289 hyperdrives: isHyperdriveConnection(binding)
290 ? yield* getHyperdriveDevOriginForHost(binding, resource)
291 : undefined,
292 // Dev-only local-emulation opt-out channel (like `hyperdrives`):
293 // worker-only bindings and `SendEmail` descriptors piped through
294 // `Alchemy.remote()` carry the internal `devRemote` flag on their
295 // binding value; contribute it as binding data so the wire binding
296 // stays pure.
297 devRemote:
298 (isWorkerOnlyBinding(binding) || isSendEmail(binding)) && binding.devRemote
299 ? { [bindingName]: true }
300 : undefined,
301 });
302 } else {
303 // Defensive catch-all: `toBinding` currently always classifies
304 // (its final arm is the `json` fallback), but keep the branch so a
305 // future gap fails loudly instead of silently skipping the binding.
306 return yield* Effect.die(`Unknown binding type: ${bindingName}`);
307 }
308 }
309 }
310 if (resource.Props?.isExternal === true) {
311 Object.assign(resource, { env });
312 }
313 });
314
315 /**
316 * Structural check for a `Cloudflare.Container` class declaration. Keyed on
317 * the `~alchemy/Container/ClassName` marker (rather than importing from
318 * `Containers/Container.ts`) to avoid a value-level import cycle through
319 * `ContainerPlatform` → `Worker.ts` → this module.
320 *
321 * A Container declaration is Effect-shaped (yielding it resolves the
322 * *started instance* tag, which only exists inside a Durable Object), so
323 * every env-resolution site must check this before `Effect.isEffect`.
324 */
325 export const isContainerDecl = (value: unknown): value is Container.Decl.Any =>
326 (typeof value === "function" || typeof value === "object") &&
327 value !== null &&
328 "~alchemy/Container/ClassName" in value;
329
330 /**
331 * Structural check for a yielded {@link ContainerApplication} resource
332 * instance (same import-cycle note as above).
333 */
334 const isContainerApplicationResource = (value: unknown): value is ContainerApplication =>
335 typeof value === "object" &&
336 value !== null &&
337 (value as { Type?: unknown }).Type === "Cloudflare.Container";
338
339 /**
340 * Wire a fleet Container bound directly on an async Worker's `env`
341 * (`env: { Sandbox: Cloudflare.Container("Sandbox", { image }) }`). A
342 * Durable Object-managed Container fails with
343 * {@link DurableObjectContainerBindingError}: it attaches through
344 * `Cloudflare.DurableObject(className, { containers })` instead. Mirrors
345 * v1 alchemy, where a Container binding is a Durable Object namespace plus
346 * its ContainerApplication in one declaration:
347 *
348 * 1. emit the `durable_object_namespace` binding for the class,
349 * 2. attach the class's namespace id to the ContainerApplication, and
350 * 3. contribute `containers: [{ className }]` binding data so the Worker's
351 * script metadata marks the class as container-backed.
352 *
353 * The namespace id only exists once the Worker uploads, while the Worker's
354 * metadata needs the container class — the same circularity as the
355 * Effect-native path (`ContainerPlatform.bind`), resolved through bindings +
356 * precreate.
357 */
358 const bindContainerClass = Effect.fn(function* (
359 resource: Worker,
360 bindingName: string,
361 decl: Container.Decl.Any,
362 ) {
363 // Effect-valued container props (the shape that threads a sibling
364 // resource's outputs into `env`) can only surface `className` here, once
365 // the props Effect runs.
366 const declaredClassName = decl["~alchemy/Container/ClassName"];
367 const className =
368 (Effect.isEffect(declaredClassName) ? yield* declaredClassName : declaredClassName) ??
369 bindingName;
370 // Resolve the ContainerApplication resource declaration carried on the
371 // class. An effectful (`main`) container has no application declaration of
372 // its own here (it is created by its `.make()` Layer inside a Durable
373 // Object host), so it cannot back an async class.
374 const declaration = (decl as { Application?: unknown }).Application;
375 const application =
376 isYieldableEffectLike(declaration) && !Output.isOutput(declaration)
377 ? yield* declaration as Effect.Effect<unknown>
378 : undefined;
379 if (!isContainerApplicationResource(application)) {
380 return yield* Effect.die(
381 `Worker binding '${bindingName}' is a Container without a deployable image. Declare the container with props (image, or context/dockerfile) to bind it on an async Worker — effectful (main) containers require an Effect-native Durable Object host.`,
382 );
383 }
384 if (isDurableObjectContainerResource(application)) {
385 return yield* Effect.die(
386 new DurableObjectContainerBindingError({
387 bindingName,
388 message: `Worker binding '${bindingName}' is a Durable Object-managed Container ('${application.LogicalId}'). Attach it to the Durable Object class that starts it: env: { ${bindingName}: Cloudflare.DurableObject("${className}", { containers: [${application.LogicalId}] }) }.`,
389 }),
390 );
391 }
392 // Both halves of the Worker's side describe the same env entry, so they
393 // share one `sid`. Binding rows are collapsed by sid (last write wins), so
394 // splitting them across two `bind` calls silently drops the namespace
395 // binding whenever the two sids coincide — e.g. the env key and the
396 // Container's logical id match (`Sandbox: Container("Sandbox", …)`). The
397 // Worker then uploads the Container declaration itself as a `json` binding
398 // and `env.NAME` is not a DO namespace at runtime.
399 yield* resource.bind`${bindingName}`({
400 bindings: [
401 {
402 type: "durable_object_namespace",
403 name: bindingName,
404 className,
405 },
406 ],
407 containers: [workerContainerBinding(className, application)],
408 });
409 yield* application.bind`${bindingName}`({
410 durableObjects: {
411 namespaceId: resource.durableObjectNamespaces.pipe(
412 Output.map((namespaces) => namespaces?.[className]),
413 ),
414 },
415 });
416 });
417
418 /**
419 * Binding mistakes die with a {@link DurableObjectContainerBindingError}: the
420 * Worker declaration hook cannot fail, and these are programmer errors.
421 *
422 * Attach the Durable Object-managed Containers of
423 * `Cloudflare.DurableObject(className, { containers })` to the class: each
424 * adds its image to the class's one container application (declared once per
425 * class, deduped by id) and returns the Worker's `containers` row for it. The
426 * same machinery as an Effect-native Durable Object's `yield* Container`.
427 */
428 const bindDurableObjectContainers = Effect.fn(function* (
429 resource: Worker,
430 bindingName: string,
431 binding: DurableObjectLike,
432 ) {
433 const className = binding.className ?? binding.name;
434 if (binding.scriptName !== undefined) {
435 return yield* Effect.die(
436 new DurableObjectContainerBindingError({
437 bindingName,
438 message: `Worker binding '${bindingName}' attaches containers to Durable Object class '${className}' hosted by another Worker. Attach containers where the class is hosted.`,
439 }),
440 );
441 }
442 const classApplication = yield* declareDurableObjectApplication(resource, className);
443 const namespaceId = resource.durableObjectNamespaces.pipe(
444 Output.map((namespaces) => namespaces?.[className]),
445 );
446 const rows = [];
447 for (const decl of binding.containers ?? []) {
448 const declaration = (decl as { Application?: unknown }).Application;
449 const application =
450 isYieldableEffectLike(declaration) && !Output.isOutput(declaration)
451 ? yield* declaration as Effect.Effect<unknown>
452 : undefined;
453 if (
454 !isContainerApplicationResource(application) ||
455 !isDurableObjectContainerResource(application)
456 ) {
457 return yield* Effect.die(
458 new DurableObjectContainerBindingError({
459 bindingName,
460 message: `Cloudflare.DurableObject("${className}", { containers }) lists a Container that is not Durable Object-managed. Declare it with schedulingPolicy: "durable_object" and an image source (image, or context/dockerfile).`,
461 }),
462 );
463 }
464 yield* classApplication.bind`${application.LogicalId}`({
465 durableObjects: { namespaceId },
466 container: {
467 id: application.LogicalId,
468 settings: containerApplicationSettings(application),
469 },
470 });
471 rows.push({
472 ...durableObjectContainerBinding(className, classApplication, application),
473 attachedBy: "binding" as const,
474 });
475 }
476 return rows;
477 });
478
479 type BindingSpec = InputProps<WorkerBinding>;
480
481 /**
482 * Classify a plain env value (string / Redacted / Json) into its wire
483 * binding. Called by {@link toBinding} both eagerly (literal values) and
484 * deferred (the resolved value of an Output env entry).
485 */
486 const toValueBinding = (
487 bindingName: string,
488 value: Json | Redacted.Redacted<Json>,
489 ): WorkerBinding => {
490 if (typeof value === "string") {
491 return {
492 type: "plain_text",
493 name: bindingName,
494 text: value,
495 };
496 }
497 if (Redacted.isRedacted(value)) {
498 const val = Redacted.value(value);
499 return {
500 type: "secret_text",
501 name: bindingName,
502 text: typeof val === "string" ? val : JSON.stringify(val),
503 };
504 }
505 return {
506 type: "json",
507 name: bindingName,
508 json: value,
509 };
510 };
511
512 /**
513 * Classify a binding into its wire shape.
514 *
515 * An Output that no native classifier recognized resolves to a plain env
516 * value, unknown until the engine resolves it, so its classification
517 * (plain_text vs secret_text vs json) is deferred to resolution time via
518 * {@link toValueBinding} — classifying eagerly would fall through to the
519 * `json` fallback and deploy e.g. a resolved `Redacted` secret as an
520 * unencrypted json binding. Resource refs never land in the Output arm:
521 * they surface their target's `Type` statically, so a native classifier
522 * (kv_namespace, r2_bucket, ...) already matched above. Whole-resource
523 * Outputs also land here (lazily, nothing is resolved); the caller rejects
524 * them before the returned Output is ever bound.
525 */
526 const toBinding = (
527 bindingName: string,
528 binding: WorkerBindingResource,
529 ): BindingSpec | Output.Output<WorkerBinding, unknown> => {
530 if (typeof binding === "string" || Redacted.isRedacted(binding)) {
531 return toValueBinding(bindingName, binding);
532 } else if (isAssets(binding)) {
533 return {
534 type: "assets",
535 name: bindingName,
536 };
537 } else if (isNamespace(binding)) {
538 return {
539 type: "artifacts",
540 name: bindingName,
541 namespace: binding.namespace,
542 };
543 } else if (isImages(binding)) {
544 return {
545 type: "images",
546 name: bindingName,
547 };
548 } else if (isBrowser(binding)) {
549 return {
550 type: "browser",
551 name: bindingName,
552 };
553 } else if (isStream(binding)) {
554 return {
555 type: "stream",
556 name: bindingName,
557 };
558 } else if (isApp(binding)) {
559 return {
560 type: "flagship",
561 name: bindingName,
562 appId: binding.appId,
563 };
564 } else if (isDataset(binding)) {
565 return {
566 type: "analytics_engine",
567 name: bindingName,
568 dataset: binding.dataset,
569 };
570 } else if (isRateLimit(binding)) {
571 return {
572 type: "ratelimit",
573 name: bindingName,
574 namespaceId: binding.namespaceId,
575 simple: binding.simple,
576 };
577 } else if (isSecretKey(binding)) {
578 return {
579 type: "secret_key",
580 name: bindingName,
581 format: binding.format,
582 algorithm: binding.algorithm,
583 usages: binding.usages,
584 keyBase64: binding.keyBase64,
585 keyJwk: binding.keyJwk,
586 };
587 } else if (isSendEmail(binding)) {
588 return {
589 type: "send_email",
590 name: bindingName,
591 destinationAddress: binding.destinationAddress,
592 allowedDestinationAddresses: binding.allowedDestinationAddresses,
593 allowedSenderAddresses: binding.allowedSenderAddresses,
594 };
595 } else if (isDurableObjectLike(binding)) {
596 return {
597 type: "durable_object_namespace",
598 name: bindingName,
599 className: binding.className ?? binding.name,
600 scriptName: binding.scriptName,
601 transferredFrom: normalizeTransferredFrom(binding.transferredFrom),
602 storage: binding.storage,
603 };
604 } else if (isWorkflowLike(binding)) {
605 return {
606 type: "workflow",
607 name: bindingName,
608 workflowName: binding.workflowName ?? binding.name,
609 className: binding.className ?? binding.name,
610 scriptName: binding.scriptName,
611 };
612 } else if (isVpcService(binding)) {
613 return {
614 type: "vpc_service",
615 name: bindingName,
616 serviceId: binding.serviceId,
617 };
618 } else if (isMtlsCertificate(binding)) {
619 // `env.NAME` is a Fetcher whose subrequests present the certificate.
620 return {
621 type: "mtls_certificate",
622 name: bindingName,
623 certificateId: binding.mtlsCertificateId,
624 };
625 } else if (isDatabase(binding)) {
626 return {
627 type: "d1",
628 databaseId: binding.databaseId,
629 name: bindingName,
630 };
631 } else if (isBucket(binding)) {
632 return {
633 type: "r2_bucket",
634 name: bindingName,
635 bucketName: binding.bucketName,
636 jurisdiction: binding.jurisdiction.pipe(
637 Output.map((jurisdiction) => (jurisdiction === "default" ? undefined : jurisdiction)),
638 ),
639 };
640 } else if (isKVNamespace(binding) || isInstantNamespace(binding)) {
641 return {
642 type: "kv_namespace",
643 name: bindingName,
644 namespaceId: binding.namespaceId,
645 };
646 } else if (isQueue(binding)) {
647 return {
648 type: "queue",
649 name: bindingName,
650 queueName: binding.queueName,
651 // Alchemy-only mode discriminator for dev (stripped before upload).
652 queueId: binding.queueId,
653 };
654 } else if (isDispatchNamespace(binding)) {
655 return {
656 type: "dispatch_namespace",
657 name: bindingName,
658 namespace: binding.name,
659 };
660 } else if (isAiGateway(binding)) {
661 return {
662 type: "ai",
663 name: bindingName,
664 };
665 } else if (isAI(binding)) {
666 return {
667 type: "ai",
668 name: bindingName,
669 };
670 } else if (isSearchInstance(binding)) {
671 // Single-instance binding: `env.NAME` is the instance itself. The
672 // `namespace` qualifies which namespace the instance lives in (the
673 // account-provided `default` when unspecified).
674 return {
675 type: "ai_search",
676 name: bindingName,
677 instanceName: binding.instanceId,
678 namespace: binding.namespace,
679 };
680 } else if (isSearchNamespace(binding)) {
681 // Namespace binding: `env.NAME.get(instanceName)` selects an instance
682 // within the namespace at runtime.
683 return {
684 type: "ai_search_namespace",
685 name: bindingName,
686 namespace: binding.name,
687 };
688 } else if (isHyperdriveConnection(binding)) {
689 return {
690 type: "hyperdrive",
691 name: bindingName,
692 id: binding.hyperdriveId,
693 };
694 } else if (isWorkerEntrypoint(binding)) {
695 // A named-entrypoint service binding (`Cloudflare.WorkerEntrypoint`).
696 // Tested BEFORE `isWorker` — the marker carries the Worker rather than
697 // being one, but keep the specific classifier ahead of the general one.
698 if (binding.worker === undefined) {
699 // One of this Worker's own named entrypoints: lowered like `Self`.
700 return {
701 type: "self_service",
702 name: bindingName,
703 entrypoint: binding.entrypoint,
704 props: binding.props,
705 };
706 }
707 return {
708 type: "service",
709 name: bindingName,
710 service: binding.worker.workerName,
711 entrypoint: binding.entrypoint,
712 props: binding.props,
713 };
714 } else if (isWorker(binding)) {
715 return {
716 type: "service",
717 name: bindingName,
718 service: binding.workerName,
719 };
720 } else if (isIndex(binding)) {
721 return {
722 type: "vectorize",
723 name: bindingName,
724 indexName: binding.indexName,
725 };
726 } else if (isSecret(binding)) {
727 return {
728 type: "secrets_store_secret",
729 name: bindingName,
730 secretName: binding.secretName,
731 storeId: binding.storeId,
732 };
733 } else if (isVersionMetadata(binding)) {
734 return {
735 type: "version_metadata",
736 name: bindingName,
737 };
738 } else if (isSelfUrl(binding)) {
739 // The Worker's own URL. The provider lowers this sentinel into a
740 // `plain_text` binding holding the resolved URL just before upload.
741 return {
742 type: "self_url",
743 name: bindingName,
744 };
745 } else if (isSelf(binding)) {
746 // A service binding to the Worker itself. The provider lowers this
747 // sentinel into a `service` binding targeting the Worker's own
748 // physical name just before upload.
749 return {
750 type: "self_service",
751 name: bindingName,
752 };
753 } else if (isWorkerLoader(binding)) {
754 return {
755 type: "worker_loader",
756 name: bindingName,
757 };
758 } else if (isPipelinesStream(binding)) {
759 return {
760 type: "pipelines",
761 name: bindingName,
762 pipeline: binding.streamId,
763 };
764 } else if (isLegacyPipeline(binding)) {
765 return {
766 type: "pipelines",
767 name: bindingName,
768 pipeline: binding.name,
769 };
770 } else if (isK2Stream(binding)) {
771 return {
772 type: "k2",
773 name: bindingName,
774 stream: binding.streamId,
775 };
776 } else if (Output.isOutput(binding)) {
777 return Output.map(binding, (value: Json | Redacted.Redacted<Json> | VpcServiceLookup) =>
778 // A `VpcService.lookup(...)` data source resolves to the service's
779 // attributes branded with the resource `Type`; classify it like the
780 // managed resource instead of a plain json env value.
781 isVpcService(value)
782 ? {
783 type: "vpc_service" as const,
784 name: bindingName,
785 serviceId: (value as VpcServiceLookup).serviceId,
786 }
787 : toValueBinding(bindingName, value as Json | Redacted.Redacted<Json>),
788 );
789 } else {
790 return {
791 type: "json",
792 name: bindingName,
793 json: binding,
794 };
795 }
796 };
797
798 export const getCronBindings = (bindings: ReadonlyArray<ResourceBinding<Worker["Binding"]>>) =>
799 Array.from(new Set(bindings.flatMap((b) => b.data.crons ?? [])));
800
801 /**
802 * Merge the Workers Cache settings contributed by `yield* Cloudflare.cache()`
803 * bindings. Commutative: the cache is enabled (and cross-version) if any
804 * contributor asked for it.
805 */
806 export const getCacheBinding = (bindings: ReadonlyArray<ResourceBinding<Worker["Binding"]>>) => {
807 const configs = bindings.flatMap((b) => (b.data.cache ? [b.data.cache] : []));
808 if (configs.length === 0) {
809 return undefined;
810 }
811 return {
812 enabled: configs.some((c) => c.enabled),
813 crossVersionCache: configs.some((c) => c.crossVersionCache) || undefined,
814 };
815 };
816
817 const DEFAULT_OBSERVABILITY: WorkerObservability = {
818 enabled: true,
819 logs: {
820 enabled: true,
821 invocationLogs: true,
822 },
823 };
824
825 /**
826 * Resolve the observability metadata to upload. An explicit
827 * `news.observability.traces` wins; otherwise the traces contributed by
828 * `Cloudflare.Telemetry()` (a single binding row — rows are collapsed by
829 * sid) fill in without clobbering the logs config. A cache-style `??` on
830 * the whole object would drop the default `logs.invocationLogs`.
831 */
832 export const resolveObservability = (
833 news: Pick<WorkerProps, "observability">,
834 bindings: ReadonlyArray<ResourceBinding<Worker["Binding"]>>,
835 ): WorkerObservability => {
836 const observability = news.observability ?? DEFAULT_OBSERVABILITY;
837 const bound = bindings.find((b) => b.data.observability?.traces != null)?.data.observability
838 ?.traces;
839 return observability.traces != null || bound == null
840 ? observability
841 : { ...observability, traces: bound };
842 };