sailfork / t3code-github / .repos/ alchemy-effect/ packages/ cloudflare/ src/ Workers/ WorkerProvider.ts

import * as crypto from "node:crypto";
import * as durableObjectsApi from "@distilled.cloud/cloudflare/durable-objects";
import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
import * as workers from "@distilled.cloud/cloudflare/workers";
import * as wfp from "@distilled.cloud/cloudflare/workers-for-platforms";
import { Unowned, Unresolved } from "alchemy/AdoptPolicy";
import { dotAlchemyDirectory } from "alchemy/AlchemyContext";
import { havePropsChanged, isResolved, stripEffects } from "alchemy/Diff";
import * as ProviderLayer from "alchemy/Local/ProviderLayer";
import * as Provider from "alchemy/Provider";
import type { ScopedPlanStatusSession } from "alchemy/Report";
import { type ResourceBinding } from "alchemy/Resource";
import { isRedactedMarker } from "alchemy/RuntimeContext";
import { Stack } from "alchemy/Stack";
import { cachedFunction } from "alchemy/Util/cached-function";
import { sha256Object } from "alchemy/Util/sha256";
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import { isHttpClientError } from "effect/http/HttpClientError";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as Redacted from "effect/Redacted";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
import {
  assertBindingContainersOnAsyncClasses,
  mergeWorkerContainers,
} from "../Containers/ContainerConfiguration.ts";
import * as DomainVersion from "../Domain/Version.ts";
import { localRuntimeServices } from "../LocalRuntime.ts";
import { CloudflareLogs } from "../Logs.ts";
import { detachQueueConsumersOfScript } from "../Queues/Consumer.ts";
import { resolveZoneId, type Reference as ZoneReference } from "../Zone/lookup.ts";
import {
  getAssetsPathPrefix,
  mergeAssetsConfigFiles,
  readAssets,
  readAssetsConfigFiles,
  uploadAssets,
} from "./Assets.ts";
import { getCompatibility } from "./Compatibility.ts";
import { isDurableObjectExport } from "./DurableObject.ts";
import { LocalWorkerProvider } from "./LocalWorkerProvider.ts";
import { placeholderResetReason } from "./Placeholder.ts";
import { routePatternUrl } from "./RoutePattern.ts";
import { isAssetsOnly, makeSourceContext, resolveSource } from "./Source.ts";
import { assertCloudflareTelemetryCompatibility } from "./Telemetry.ts";
import {
  Worker,
  type WorkerProps,
  type WorkerRouteConfig,
  type WorkerVersionAffinity,
} from "./Worker.ts";
import { getCacheBinding, getCronBindings, resolveObservability } from "./WorkerAsyncBindings.ts";
import {
  type WireWorkerBinding,
  type WorkerBinding,
  type WorkerSettingsBinding,
  withoutDevOnlyBindings,
} from "./WorkerBinding.ts";
import { createWorkerName } from "./WorkerName.ts";
class MissingDurableObjects extends Data.TaggedError("MissingDurableObjects")<{
  scriptName: string;
  expected: string[];
}> {}

/**
 * A Durable Object class is being dropped from this Worker while a binding in
 * the same deploy still references it on another script — the class moved
 * cross-script, but its namespace (and every stored object in it) still lives
 * on this Worker. Cloudflare rejects a single upload that both deletes the
 * class and ships a binding referencing it, and silently deleting would
 * destroy the namespace's data irreversibly, so the deploy fails before any
 * upload.
 *
 * Moving a Durable Object class between Workers is always declared: set
 * `transferredFrom` on the Durable Object at its **new host** — naming the
 * former host by Worker logical id (same stack) or physical script name — and
 * Alchemy moves the namespace, with its data, on the new host's deploy; this
 * deploy then converges on its own. To abandon the
 * data instead, remove the binding entirely in one deploy (which deletes the
 * class and its data), then add the cross-script binding in a second deploy.
 */
export class DurableObjectTransferRequired extends Data.TaggedError(
  "DurableObjectTransferRequired",
)<{ scriptName: string; className: string; targetScriptName: string | undefined }> {
  override get message() {
    return (
      `Durable Object class '${this.className}' still lives on Worker '${this.scriptName}' but this deploy re-binds it as a cross-script reference` +
      (this.targetScriptName ? ` to '${this.targetScriptName}'` : "") +
      ". Durable Object data does NOT move with the class automatically. " +
      `To move the data, set transferredFrom: "${this.scriptName}" (the former host's script name, or its Worker logical id for same-stack moves) on the Durable Object declaration in its new host Worker. ` +
      "To abandon the data, remove the binding entirely in one deploy before re-adding it as a cross-script reference."
    );
  }
}

/**
 * More than one script matches the `transferredFrom` declaration of a Durable
 * Object (e.g. an orphaned script left behind by a `name` prop change still
 * carries the same alchemy tags, or the host history lists several scripts
 * that each still hold a same-class namespace). Alchemy refuses to guess
 * which namespace's data to move — narrow the declaration to the exact
 * physical script name that holds the data.
 */
export class AmbiguousDurableObjectTransfer extends Data.TaggedError(
  "AmbiguousDurableObjectTransfer",
)<{ scriptName: string; logicalId: string; className: string; sources: string[] }> {
  override get message() {
    return (
      `Durable Object '${this.logicalId}' (class '${this.className}') is new to Worker '${this.scriptName}' and multiple scripts match its transferredFrom declaration: ${this.sources.join(", ")}. ` +
      `Narrow transferredFrom to the exact physical script name that holds the data.`
    );
  }
}

/**
 * Resolve the Workers for Platforms dispatch-namespace *name* from a resolved
 * `namespace` prop or persisted attribute. The engine resolves a passed
 * {@link DispatchNamespace} resource to its Attributes object (see
 * `Input.Resolve` / Plan.ts), so the value is either the namespace name
 * string, that attributes object, or `undefined` for a regular Worker.
 *
 * @internal
 */
export const resolveNamespaceName = (namespace: unknown): string | undefined => {
  if (namespace == null) return undefined;
  if (typeof namespace === "string") return namespace;
  return (namespace as { name?: string }).name;
};

/**
 * Resolve a Worker's `tailConsumers` / `streamingTailConsumers` prop into
 * the wire-shape consumer list
 * (`[{ service }]`). The engine resolves a passed {@link Worker} to its
 * Attributes object — possibly stables-only during planning, but
 * `workerName` is always a stable — so each entry is either a script-name
 * string or that attributes object. Whole-resource entries are reduced to
 * the script name alone so hashing/diffing never sees the consumer's
 * per-deploy fields (`hash`, `url`, ...), mirroring
 * {@link resolveVersionParentName}.
 *
 * An empty array resolves to `[]` (explicitly detach every consumer);
 * `undefined`/absent resolves to `undefined`.
 *
 * This is also the seam for local emulation: the local provider lowers this
 * same resolved list into workerd's `Worker.tails` / `Worker.streamingTails`
 * service designators (`RuntimeWorker.tails` / `RuntimeWorker.streamingTails`).
 *
 * @internal
 */
export const resolveTailConsumers = (
  tailConsumers: WorkerProps["tailConsumers" | "streamingTailConsumers"],
): { service: string }[] | undefined => {
  if (tailConsumers == null) return undefined;
  return tailConsumers.flatMap((consumer) => {
    const service =
      typeof consumer === "string" ? consumer : (consumer as { workerName?: unknown }).workerName;
    return typeof service === "string" ? [{ service }] : [];
  });
};

/**
 * A Worker's `version` configuration is invalid — a prop that can't be
 * combined with `version.parent` (script-level settings belong to the
 * parent), a locally-hosted Durable Object / Workflow class on a version
 * worker, an out-of-range `traffic`, or a gradual rollout that requires
 * changes the versions API can't carry (assets, DO migrations).
 */
export class WorkerVersionConfigError extends Data.TaggedError("WorkerVersionConfigError")<{
  message: string;
}> {}

/**
 * Resolve the parent script *name* from a resolved `version.parent` prop or
 * persisted props. The engine resolves a passed {@link Worker} (or
 * `Worker.ref(...)`) to its Attributes object — possibly stables-only during
 * planning, but `workerName` is always a stable — so the value is either the
 * script name string, that attributes object, or `undefined`.
 *
 * @internal
 */
export const resolveVersionParentName = (version: WorkerProps["version"]): string | undefined => {
  const parent = version?.parent;
  if (parent == null) return undefined;
  if (typeof parent === "string") return parent;
  const workerName = (parent as { workerName?: unknown }).workerName;
  return typeof workerName === "string" ? workerName : undefined;
};

/**
 * A Worker's `preview` configuration is invalid — combined with
 * `version.parent`, missing `preview.of`, a bad Preview name, or a
 * script-level setting that belongs to the parent.
 */
export class WorkerPreviewConfigError extends Data.TaggedError("WorkerPreviewConfigError")<{
  message: string;
}> {}

/**
 * Resolve the parent script *name* from a resolved `preview.of` prop.
 *
 * @internal
 */
export const resolvePreviewParentName = (preview: WorkerProps["preview"]): string | undefined => {
  const parent = preview?.of;
  if (parent == null) return undefined;
  if (typeof parent === "string") return parent;
  const workerName = (parent as { workerName?: unknown }).workerName;
  return typeof workerName === "string" ? workerName : undefined;
};

const toPreviewWireKey = (key: string) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);

const toPreviewWire = (value: unknown): unknown => {
  if (Array.isArray(value)) return value.map(toPreviewWire);
  if (value !== null && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value as Record<string, unknown>).map(([k, v]) => [
        toPreviewWireKey(k),
        toPreviewWire(v),
      ]),
    );
  }
  return value;
};

const previewVerbatimFields = new Set(["json", "algorithm", "keyJwk", "props"]);

/** Convert Alchemy's binding array into wrangler's Preview `env` map. */
const bindingsToPreviewEnv = (bindings: WorkerBinding[]): Record<string, unknown> => {
  const env: Record<string, unknown> = {};
  for (const binding of bindings) {
    const { name, ...rest } = binding as unknown as { name?: unknown } & Record<string, unknown>;
    if (typeof name !== "string") continue;
    env[name] = Object.fromEntries(
      Object.entries(rest).map(([k, v]) => [
        toPreviewWireKey(k),
        previewVerbatimFields.has(k) ? v : toPreviewWire(v),
      ]),
    );
  }
  return env;
};

/**
 * The traffic percentage a *self-owned* Worker's new version should receive,
 * or `undefined` for the default full cutover. Only a `version` prop without
 * a `parent` participates — version workers handle traffic separately.
 *
 * @internal
 */
const getSelfRolloutTraffic = (news: WorkerProps): number | undefined => {
  if (!news.version || news.version.parent != null) return undefined;
  const traffic = news.version.traffic;
  return traffic === undefined || traffic >= 100 ? undefined : traffic;
};

const validateTraffic = (traffic: number | undefined) =>
  traffic !== undefined && (!Number.isFinite(traffic) || traffic < 0 || traffic > 100)
    ? Effect.fail(
        new WorkerVersionConfigError({
          message: `version.traffic must be a percentage between 0 and 100, got ${traffic}`,
        }),
      )
    : Effect.void;

/** The request header Cloudflare hashes to pin a request to a version. */
const AFFINITY_HEADER = "Cloudflare-Workers-Version-Key";

/**
 * `version.affinity` normalized to a single key source plus the optional
 * IP fallback.
 *
 * @internal exported for unit testing.
 */
export interface ResolvedVersionAffinity {
  source:
    | { kind: "cookie" | "header"; name: string }
    | { kind: "ip" }
    | { kind: "key"; expression: string };
  ipFallback: boolean;
}

// Cookie / header names are interpolated into a double-quoted Rules-language
// string literal — restrict them to the token characters real-world names
// use so a name can never terminate the literal or smuggle expression text.
const AFFINITY_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;

/**
 * Validate `version.affinity` and normalize it to its key source: exactly
 * one of `cookie` / `header` / `key`, or `ip: true` alone; `ip` combines
 * with `cookie` / `header` as the absent-source fallback.
 *
 * @internal exported for unit testing.
 */
export const resolveVersionAffinity = (
  affinity: WorkerVersionAffinity,
): Effect.Effect<ResolvedVersionAffinity, WorkerVersionConfigError> =>
  Effect.gen(function* () {
    const declared = [
      ...(affinity.cookie !== undefined ? ["cookie"] : []),
      ...(affinity.header !== undefined ? ["header"] : []),
      ...(affinity.key !== undefined ? ["key"] : []),
    ];
    if (declared.length > 1) {
      return yield* new WorkerVersionConfigError({
        message: `version.affinity accepts exactly one key source, got ${declared.join(" and ")}. Combine sources with a raw \`key\` expression instead.`,
      });
    }
    if (declared.length === 0 && affinity.ip !== true) {
      return yield* new WorkerVersionConfigError({
        message:
          "version.affinity requires a key source: set `cookie`, `header`, `key`, or `ip: true`.",
      });
    }
    if (affinity.key !== undefined && affinity.ip === true) {
      return yield* new WorkerVersionConfigError({
        message:
          "version.affinity: `ip` is the fallback for an absent `cookie`/`header` — a raw `key` expression has no absence condition to fall back from. Fold `ip.src` into the expression instead.",
      });
    }
    for (const [prop, name] of [
      ["cookie", affinity.cookie],
      ["header", affinity.header],
    ] as const) {
      if (name !== undefined && !AFFINITY_NAME_PATTERN.test(name)) {
        return yield* new WorkerVersionConfigError({
          message: `version.affinity.${prop} '${name}' is not a valid ${prop} name: expected only letters, digits, '_', '.', and '-'.`,
        });
      }
    }
    const source: ResolvedVersionAffinity["source"] =
      affinity.cookie !== undefined
        ? { kind: "cookie", name: affinity.cookie }
        : affinity.header !== undefined
          ? // Rules-language header map keys are lowercase.
            { kind: "header", name: affinity.header.toLowerCase() }
          : affinity.key !== undefined
            ? { kind: "key", expression: affinity.key }
            : { kind: "ip" };
    return {
      source,
      ipFallback: affinity.ip === true && (source.kind === "cookie" || source.kind === "header"),
    };
  });

/** A hostname a Worker serves on within one zone. */
interface AffinityZoneHost {
  host: string;
  /** `true` when `host` came from a route pattern containing `*`. */
  wildcard: boolean;
}

/**
 * The `http.host` clause scoping a zone's affinity rules to the Worker's
 * own hostnames, so unrelated zone traffic — and other Workers' rollouts
 * on the same zone — never get this Worker's version key.
 *
 * @internal exported for unit testing.
 */
export const affinityHostExpression = (hosts: readonly AffinityZoneHost[]): string => {
  const dedupe = (values: string[]) => [...new Set(values)].sort();
  const exact = dedupe(hosts.filter((h) => !h.wildcard).map((h) => h.host));
  const wild = dedupe(hosts.filter((h) => h.wildcard).map((h) => h.host));
  const clauses = [
    ...(exact.length === 1
      ? [`http.host eq "${exact[0]}"`]
      : exact.length > 1
        ? [`http.host in {${exact.map((h) => `"${h}"`).join(" ")}}`]
        : []),
    ...wild.map((h) => `http.host wildcard "${h}"`),
  ];
  return clauses.length === 1 ? clauses[0] : `(${clauses.join(" or ")})`;
};

interface AffinityRuleSpec {
  description: string;
  expression: string;
  /** Rules-language expression producing the header value. */
  value: string;
}

const affinityRulePrefix = (scriptName: string) => `alchemy:worker:${scriptName}:affinity`;

/**
 * The transform rules pinning one zone's traffic: a primary rule filling
 * the version-key header from the configured source, plus — for
 * `cookie`/`header` sources with `ip: true` — a fallback rule keying
 * requests that lack the source by client IP.
 *
 * @internal exported for unit testing.
 */
export const buildAffinityZoneRules = (
  scriptName: string,
  affinity: ResolvedVersionAffinity,
  hosts: readonly AffinityZoneHost[],
): AffinityRuleSpec[] => {
  const prefix = affinityRulePrefix(scriptName);
  const hostExpr = affinityHostExpression(hosts);
  const { source } = affinity;
  if (source.kind === "ip" || source.kind === "key") {
    return [
      {
        description: `${prefix}:key`,
        expression: hostExpr,
        value: source.kind === "ip" ? "to_string(ip.src)" : source.expression,
      },
    ];
  }
  const field =
    source.kind === "cookie"
      ? `http.request.cookies["${source.name}"]`
      : `http.request.headers["${source.name}"]`;
  return [
    {
      description: `${prefix}:key`,
      expression: `${hostExpr} and len(${field}) > 0`,
      value: `${field}[0]`,
    },
    ...(affinity.ipFallback
      ? [
          {
            // An absent cookie/header is a *missing* value in the Rules
            // language, and every comparison on missing evaluates false —
            // `len(field) == 0` can never match. `not (len(field) > 0)`
            // is the complement that does: missing → false → `not` → true.
            description: `${prefix}:ip`,
            expression: `${hostExpr} and not (len(${field}) > 0)`,
            value: "to_string(ip.src)",
          },
        ]
      : []),
  ];
};

/**
 * A Worker's `domain` configuration is invalid — a hostname appears in more
 * than one role (name/aliases/redirects), or a redirect targets itself.
 */
export class WorkerDomainConfigError extends Data.TaggedError("WorkerDomainConfigError")<{
  message: string;
}> {}

/**
 * The resolved shape of `WorkerProps.workersDev`: `enabled` drives the
 * stable `<name>.<account>.workers.dev` URL, `previewsEnabled` the
 * per-version preview URLs. The two toggles are independent on the
 * Cloudflare API.
 *
 * @internal exported for unit testing.
 */
export interface ResolvedWorkersDev {
  enabled: boolean;
  previewsEnabled: boolean;
}

/**
 * Resolve the `workersDev` prop to its full shape. `true` / omitted means
 * "default workers.dev behavior" (stable URL + version previews), `false`
 * disables both, and the object form fills unset toggles with `true`.
 *
 * @internal exported for unit testing.
 */
export const resolveWorkersDev = (workersDev: WorkerProps["workersDev"]): ResolvedWorkersDev => {
  if (workersDev === undefined || workersDev === true) {
    return { enabled: true, previewsEnabled: true };
  }
  if (workersDev === false) {
    return { enabled: false, previewsEnabled: false };
  }
  return {
    enabled: workersDev.enabled ?? true,
    previewsEnabled: workersDev.previewsEnabled ?? true,
  };
};

/**
 * The resolved shape of `WorkerProps.domain`: the canonical hostname plus
 * alias and redirect hostname lists, all punycode-normalized and
 * de-duplicated.
 *
 * @internal exported for unit testing.
 */
export interface ResolvedWorkerDomain {
  name: string;
  aliases: string[];
  redirects: string[];
  /** Pinned zone from props, when the caller set zoneId / zone / zoneName. */
  zone?: ZoneReference;
  /** Serve Worker Previews on this custom domain. */
  previews?: boolean;
}

const isZoneReference = (value: unknown): value is ZoneReference => {
  if (typeof value === "string") return true;
  if (typeof value !== "object" || value === null) return false;
  const candidate = value as { zoneId?: unknown; name?: unknown };
  return (
    typeof candidate.zoneId === "string" &&
    (candidate.name === undefined || typeof candidate.name === "string")
  );
};

/** Collapse Worker.domain zone pin fields to one {@link ZoneReference}. */
export const resolveWorkerDomainZone = (
  config:
    | { readonly zoneId?: unknown; readonly zoneName?: unknown; readonly zone?: unknown }
    | undefined,
): ZoneReference | undefined => {
  if (config === undefined) return undefined;
  if (typeof config.zoneId === "string") return config.zoneId;
  if (isZoneReference(config.zone)) return config.zone;
  if (typeof config.zoneName === "string") return config.zoneName;
  return undefined;
};

/** Whether an existing attachment must move to satisfy an explicit zone pin. */
export const shouldRecreateWorkerDomainAttachment = (
  liveZoneId: string,
  desiredZoneId: string | undefined,
): boolean => desiredZoneId !== undefined && liveZoneId !== desiredZoneId;

// After deleting a custom-domain attachment, Cloudflare can briefly retain
// ownership of the hostname and reject the replacement with code 100116.
const workerDomainConflictSchedule = Schedule.max([
  Schedule.spaced("2 seconds"),
  Schedule.recurs(8),
]);

// Convert non-ASCII hostnames (emoji, IDN, etc.) to punycode so the
// Cloudflare API receives the form it stores domains in. `new URL(...)`
// does IDNA via WHATWG URL parsing — `📦.alchemy.run` → `xn--5z8h.alchemy.run`.
const toPunycode = (hostname: string): string => {
  try {
    return new URL(`https://${hostname}`).hostname;
  } catch {
    return hostname;
  }
};

/**
 * Resolve the `domain` prop to its full shape — a bare string is shorthand
 * for `{ name }`. Hostnames are punycode-normalized and de-duplicated;
 * a hostname may only play one role, so aliases/redirects that repeat the
 * canonical name (or each other) fail with a typed error.
 *
 * @internal exported for unit testing.
 */
export const resolveWorkerDomain = (
  // `string[]` is the pre-redesign prop shape — it can still reach us from
  // persisted `olds` written by older providers (read's classification).
  domain: WorkerProps["domain"] | string[],
): Effect.Effect<ResolvedWorkerDomain | undefined, WorkerDomainConfigError> =>
  Effect.gen(function* () {
    if (domain === undefined || domain === null) return undefined;
    // Legacy array form: the first hostname was the primary custom domain
    // (`url = domains[0]` back then), the rest map to aliases. A legacy
    // empty array was the explicit detach-all — no domain.
    const config =
      typeof domain === "string"
        ? { name: domain }
        : Array.isArray(domain)
          ? domain.length > 0
            ? { name: domain[0], aliases: domain.slice(1) }
            : undefined
          : domain;
    if (config === undefined) return undefined;
    const name = toPunycode(config.name);
    const aliases = Array.from(new Set((config.aliases ?? []).map(toPunycode)));
    const redirects = Array.from(new Set((config.redirects ?? []).map(toPunycode)));
    const overlap = [
      ...aliases.filter((h) => h === name),
      ...redirects.filter((h) => h === name || aliases.includes(h)),
    ];
    if (overlap.length > 0) {
      return yield* new WorkerDomainConfigError({
        message: `Each hostname may play only one role in a Worker's domain config; ${[...new Set(overlap)].map((h) => `'${h}'`).join(", ")} appears in more than one of name/aliases/redirects.`,
      });
    }
    const zone = resolveWorkerDomainZone(config);
    const previews = "previews" in config && config.previews === true ? true : undefined;
    return {
      name,
      aliases,
      redirects,
      ...(zone === undefined ? {} : { zone }),
      ...(previews === undefined ? {} : { previews }),
    };
  });

/**
 * Preserve the resolved domain metadata only while the declared canonical
 * hostname is attached. Alias, redirect, and unknown-hostname classification
 * is supplied by `read`; zone and previews retain reconcile's persisted shape.
 */
const resolveObservedWorkerDomain = (
  serving: readonly string[],
  redirects: string[],
  declared: ResolvedWorkerDomain | undefined,
): ResolvedWorkerDomain | undefined =>
  serving.length > 0
    ? {
        ...(declared?.name === serving[0] ? declared : {}),
        name: serving[0],
        aliases: serving.slice(1),
        redirects,
      }
    : undefined;

const isWorkersDevHostname = (hostname: string) => hostname.endsWith(".workers.dev");

// Hostnames that only appear in local-dev state (the dev server's
// localhost/LAN URLs), never as attachable custom domains.
const isLocalDevHostname = (hostname: string) =>
  hostname === "localhost" || hostname === "::1" || /^\d+\.\d+\.\d+\.\d+$/.test(hostname);

const urlHostname = (url: string): string => {
  try {
    return new URL(url).hostname;
  } catch {
    return url;
  }
};

/** The `rules` payload shape of a zone phase-entrypoint PUT. */
type PutZoneRedirectRules = rulesets.PutPhasForZoneRequest["rules"];
/** A rule as a zone phase entrypoint read returns it. */
type PhaseRule = NonNullable<rulesets.GetPhasResponse["rules"]>[number];

/**
 * The *custom domain* hostnames recorded in a Worker's persisted legacy
 * `domains` state — minus the workers.dev (stable or preview) and local-dev
 * entries that shared the list in older formats.
 *
 * @internal exported for unit testing.
 */
export const stateCustomDomains = (domains: readonly unknown[] | undefined): string[] =>
  normalizeStateDomains(domains).filter(
    (hostname) => !isWorkersDevHostname(hostname) && !isLocalDevHostname(hostname),
  );

/**
 * The Worker's persisted domain configuration: the `domain` attribute for
 * state written by the current format, else re-derived from the legacy
 * `domains` list (first custom hostname = canonical name, rest = aliases;
 * legacy state had no redirects).
 *
 * @internal exported for unit testing.
 */
export const stateWorkerDomain = (output: object | undefined): ResolvedWorkerDomain | undefined => {
  const state = output as
    | {
        domain?: {
          name?: unknown;
          aliases?: unknown[];
          redirects?: unknown[];
          zone?: ZoneReference;
          zoneId?: unknown;
          zoneName?: unknown;
          previews?: unknown;
        } | null;
        domains?: unknown[];
      }
    | undefined;
  const domain = state?.domain;
  if (domain && typeof domain.name === "string") {
    const zone = resolveWorkerDomainZone(domain);
    return {
      name: domain.name,
      aliases: (domain.aliases ?? []).filter((h): h is string => typeof h === "string"),
      redirects: (domain.redirects ?? []).filter((h): h is string => typeof h === "string"),
      ...(zone === undefined ? {} : { zone }),
      ...(domain.previews === true ? { previews: true } : {}),
    };
  }
  const legacy = stateCustomDomains(state?.domains);
  return legacy.length > 0
    ? { name: legacy[0], aliases: legacy.slice(1), redirects: [] }
    : undefined;
};

// Workers for Platforms "user workers" live inside a dispatch namespace and
// use a parallel family of script endpoints (`/workers/dispatch/namespaces/
// :namespace/scripts/...`). The request/response shapes are identical to the
// account-level Workers API for everything the provider touches, so these
// helpers route by `dispatchNamespace` and the call sites stay agnostic.

/**
 * Read a script's combined settings, routing to the dispatch-namespace
 * endpoint when `dispatchNamespace` is set. The two response shapes are
 * structurally identical for the fields the provider consumes (`bindings`,
 * `tags`, `logpush`), so the WFP response is surfaced as the workers shape.
 *
 * @internal
 */
const getScriptSettings = (
  accountId: string,
  scriptName: string,
  dispatchNamespace: string | undefined,
) =>
  // `Effect.gen` (rather than a ternary) so the two branches unify into a
  // single `Effect<Settings, WorkersErr | WfpErr>` instead of a *union* of
  // Effects, which `.pipe`/`catchTag` at the call sites can't consume.
  Effect.gen(function* () {
    if (dispatchNamespace) {
      const settings = yield* wfp.getDispatchNamespaceScriptSetting({
        accountId,
        dispatchNamespace,
        scriptName,
      });
      // The dispatch-namespace settings response is structurally identical to
      // the account-level one for the fields the provider reads.
      return settings as unknown as workers.GetScriptScriptAndVersionSettingResponse;
    }
    return yield* workers.getScriptScriptAndVersionSetting({ accountId, scriptName });
  });

/**
 * Look up a dispatch-namespace script, or `undefined` when it or its
 * namespace does not exist. The settings endpoint answers a missing
 * namespace with an untyped 500, so check existence here first.
 */
const findDispatchNamespaceScript = (
  accountId: string,
  dispatchNamespace: string,
  scriptName: string,
) =>
  wfp
    .getDispatchNamespaceScript({ accountId, dispatchNamespace, scriptName })
    .pipe(
      Effect.catchTag(
        ["DispatchNamespaceNotFound", "DispatchNamespaceScriptNotFound"],
        () => Effect.undefined,
      ),
    );

/**
 * Deploy-time binding validation rejects an upload whose bindings
 * reference a resource Cloudflare can't see (each resource type has
 * its own typed not-found error, verified against the live API).
 * Every bound resource is provisioned before the Worker deploys —
 * dependency order for KV/R2/D1/queues/etc., a pre-created stub
 * (which exports the Durable Object classes) for circular
 * Worker↔Worker references — so a not-found here is either
 * propagation lag on a just-created resource (a Secrets Store secret
 * still `pending`, a stub script not yet in the registry) that
 * retrying converges, or a genuine misconfiguration that keeps
 * failing and surfaces as the typed error once the bounded budget is
 * exhausted.
 */
const isBindingTargetNotFound = (
  e:
    | Effect.Error<ReturnType<typeof workers.putScript>>
    | Effect.Error<ReturnType<typeof wfp.putDispatchNamespaceScript>>
    | Effect.Error<ReturnType<typeof workers.createScriptVersion>>,
): boolean =>
  e._tag === "SecretsStoreBindingNotFound" ||
  e._tag === "KVNamespaceNotFound" ||
  e._tag === "R2BucketNotFound" ||
  e._tag === "D1DatabaseNotFound" ||
  e._tag === "QueueNotFound" ||
  e._tag === "ServiceBindingNotFound" ||
  e._tag === "DurableObjectClassNotFound" ||
  e._tag === "HyperdriveConfigNotFound" ||
  e._tag === "VectorizeIndexNotFound" ||
  e._tag === "DispatchNamespaceNotFound" ||
  e._tag === "MtlsCertificateNotFound";

const bindingTargetNotFoundRetrySchedule = () =>
  Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]);

/**
 * Script PUT is an idempotent upsert, so a pure transport failure (the
 * request died before any response — e.g. Cloudflare closing a keep-alive
 * socket that idled while slow upstream resources provisioned earlier in the
 * deploy) is safe to replay. Errors that carry a response are real API
 * verdicts and are NOT retried here.
 */
const isScriptPutTransportError = (e: { _tag?: string }): boolean =>
  isHttpClientError(e) && e.reason._tag === "TransportError";

const retryableScriptPut = (e: Parameters<typeof isBindingTargetNotFound>[0]): boolean =>
  isBindingTargetNotFound(e) || isScriptPutTransportError(e);

/**
 * Upsert a Worker script, routing to the dispatch-namespace endpoint when
 * `dispatchNamespace` is set. The metadata/files contract is identical, and
 * both endpoints run the same binding validation (see
 * {@link isBindingTargetNotFound}), so both get the same bounded retry.
 *
 * @internal
 */
/**
 * A cached `workerId` attribute usable as the immutable script ID — rules
 * out the legacy shape (older releases persisted the script *name*), the
 * `dev:`-marked local identity, and the precreate stub's provisional `""`.
 */
const cachedWorkerId = (value: string | undefined, scriptName: string): string | undefined =>
  value !== undefined && value !== "" && value !== scriptName && !value.startsWith("dev:")
    ? value
    : undefined;

/**
 * Whether `output` is a precreate stub that uploaded nothing: a version,
 * preview, or dispatch-namespace worker's provisional row (`workerId: ""`).
 * Its `workerName` names no script this resource wrote. Without a recorded
 * namespace it can't even say which endpoint the attempt targeted — a
 * dispatch stub's namespace may still have been unresolved — so the
 * account-level script of that name proves nothing (#2533).
 */
const isUnscopedStub = (output: Worker["Attributes"]): boolean =>
  output.workerId === "" && !output.namespace;

export class WorkerIdNotFound extends Data.TaggedError("WorkerIdNotFound")<{
  scriptName: string;
  message: string;
}> {}

/**
 * Resolve a script's immutable Worker ID (carried as `tag` on Cloudflare's
 * wire) by script name. Neither the settings endpoints nor GET /content
 * expose it, so scan the account's script listing lazily and stop at the
 * first match. The listing is eventually consistent, so a missing entry is
 * retried briefly before failing.
 */
const findWorkerId = (accountId: string, scriptName: string) =>
  workers.listScripts.items({ accountId }).pipe(
    Stream.filter((script) => script.id === scriptName),
    Stream.runHead,
    Effect.map(Option.getOrUndefined),
    Effect.flatMap((script) =>
      script?.tag != null
        ? Effect.succeed(script.tag)
        : Effect.fail(
            new WorkerIdNotFound({
              scriptName,
              message: `Cloudflare Worker: could not resolve the immutable ID of script '${scriptName}' from the account listing`,
            }),
          ),
    ),
    Effect.retry({
      while: (e) => e._tag === "WorkerIdNotFound",
      schedule: Schedule.max([Schedule.spaced(2000), Schedule.recurs(3)]),
    }),
  );

export class WorkerCodeUpdateStrategyError extends Data.TaggedError(
  "WorkerCodeUpdateStrategyError",
)<{
  message: string;
}> {}

/**
 * Lower `codeUpdateStrategy` to its wire shape: `max_delay` is seconds with
 * millisecond precision, between 0 and 24 hours, and only `deferred` accepts
 * it (Cloudflare rejects `max_delay` alongside `immediate`).
 */
const resolveCodeUpdateStrategy = Effect.fn(function* (
  strategy: WorkerProps["codeUpdateStrategy"],
) {
  if (strategy === undefined) return undefined;
  if (strategy.mode === "immediate") {
    return { mode: "immediate" } satisfies workers.CodeUpdateStrategy;
  }
  if (strategy.maxDelay === undefined) {
    return { mode: "deferred" } satisfies workers.CodeUpdateStrategy;
  }
  const maxDelay = Duration.fromInput(strategy.maxDelay).pipe(
    Option.map((d) => Math.round(Duration.toMillis(d)) / 1000),
    Option.filter((seconds) => seconds >= 0 && seconds <= 86_400),
  );
  if (Option.isNone(maxDelay)) {
    return yield* new WorkerCodeUpdateStrategyError({
      message: `codeUpdateStrategy.maxDelay must be a duration between 0 and 24 hours, got ${JSON.stringify(strategy.maxDelay)}.`,
    });
  }
  return { mode: "deferred", maxDelay: maxDelay.value } satisfies workers.CodeUpdateStrategy;
});

export const putWorkerScript = (params: {
  accountId: string;
  scriptName: string;
  dispatchNamespace: string | undefined;
  metadata: workers.PutScriptRequest["metadata"];
  files: workers.PutScriptRequest["files"];
}) =>
  Effect.gen(function* () {
    if (params.dispatchNamespace) {
      return yield* wfp
        .putDispatchNamespaceScript({
          accountId: params.accountId,
          dispatchNamespace: params.dispatchNamespace,
          scriptName: params.scriptName,
          metadata: params.metadata,
          files: params.files,
        })
        .pipe(
          Effect.retry({
            while: retryableScriptPut,
            schedule: bindingTargetNotFoundRetrySchedule(),
          }),
        );
    }
    return yield* workers
      .putScript({
        accountId: params.accountId,
        scriptName: params.scriptName,
        metadata: params.metadata,
        files: params.files,
      })
      .pipe(
        Effect.retry({ while: retryableScriptPut, schedule: bindingTargetNotFoundRetrySchedule() }),
      );
  });

/**
 * Delete a Worker script, routing to the dispatch-namespace endpoint when
 * `dispatchNamespace` is set.
 *
 * @internal
 */
const deleteWorkerScript = (
  accountId: string,
  scriptName: string,
  dispatchNamespace: string | undefined,
) =>
  Effect.gen(function* () {
    if (dispatchNamespace) {
      return yield* wfp.deleteDispatchNamespaceScript({
        accountId,
        dispatchNamespace,
        scriptName,
        force: true,
      });
    }
    return yield* workers.deleteScript({ accountId, scriptName, force: true }).pipe(
      // The script is still registered as a queue consumer (even with
      // `force`). Normally the sibling Consumer resource detaches first,
      // but state loss (e.g. a consumer row rewritten by a pre-stamping
      // dev run) can strand a live consumer pointing at this script with
      // nothing left to delete it. The script is going away, so any
      // consumer wiring pointing at it is dead — detach and retry.
      Effect.catchTag("QueueConsumerConflict", () =>
        detachQueueConsumersOfScript(accountId, scriptName).pipe(
          Effect.andThen(workers.deleteScript({ accountId, scriptName, force: true })),
        ),
      ),
    );
  });

/**
 * Normalize a Worker's persisted *legacy* `domains` state to bare
 * hostnames. Alchemy <= beta.44 stored each custom domain as a
 * `{ id, hostname, zoneId }` object; beta.45+ stored `https://<hostname>`
 * URL strings (with the workers.dev URL mixed in); current state stores the
 * `domain` config object instead of a `domains` list. All legacy
 * generations coerce to hostnames so the diff never throws on older state
 * (#546). Entries that fit no generation are dropped rather than turned
 * into a bogus hostname that would skew the diff.
 *
 * @internal exported for unit testing.
 */
export const normalizeStateDomains = (domains: readonly unknown[] | undefined): string[] =>
  (domains ?? []).flatMap((u) => {
    if (typeof u === "string") {
      if (u.includes("://")) {
        try {
          return [new URL(u).hostname];
        } catch {
          return [];
        }
      }
      return u.length > 0 ? [u] : [];
    }
    const hostname = (u as { hostname?: unknown } | null)?.hostname;
    return typeof hostname === "string" ? [hostname] : [];
  });

/**
 * Custom domains Alchemy is responsible for on this Worker — either declared
 * on props (`domain`) or already persisted as non-`workers.dev` URLs in state.
 * Used by `read` to skip `listDomains` when the surface is unmanaged (#926).
 *
 * @internal exported for unit testing.
 */
export const shouldObserveWorkerDomains = (
  olds: Pick<WorkerProps, "domain"> | undefined,
  output: object | undefined,
): boolean => olds?.domain !== undefined || stateWorkerDomain(output) !== undefined;

/**
 * Zone routes Alchemy is responsible for on this Worker. Used by `read` to
 * skip account-wide zone/route fan-out when the surface is unmanaged (#926).
 *
 * @internal exported for unit testing.
 */
export const shouldObserveWorkerRoutes = (
  olds: Pick<WorkerProps, "routes"> | undefined,
  output: Pick<Worker["Attributes"], "routes"> | undefined,
): boolean => olds?.routes !== undefined || (output?.routes?.length ?? 0) > 0;

const routeKey = (route: { pattern: string; zoneId: string }) => `${route.zoneId}:${route.pattern}`;

/**
 * Order observed zone routes the way state records them. `listRoutes`
 * returns routes in Cloudflare's order while `reconcile` records them in
 * declared order, and drift compares attributes positionally, so the same
 * routes in another order would read as drift. Routes missing from state
 * keep their listing order after the known ones.
 *
 * @internal exported for unit testing.
 */
export const orderObservedWorkerRoutes = <Route extends { pattern: string; zoneId: string }>(
  observed: readonly Route[],
  known: readonly { pattern: string; zoneId: string }[] | undefined,
): Route[] => {
  const position = new Map((known ?? []).map((route, index) => [routeKey(route), index]));
  const rank = (route: Route) => position.get(routeKey(route)) ?? position.size;
  return [...observed].sort((a, b) => rank(a) - rank(b));
};

/**
 * Cron triggers Alchemy is responsible for on this Worker. Used by `read` to
 * skip `getScriptSchedule` when the surface is unmanaged (#926). Effect-native
 * `cron()` bindings persist into `output.crons` after the first reconcile, so
 * subsequent reads still observe them.
 *
 * @internal exported for unit testing.
 */
export const shouldObserveWorkerCrons = (
  olds: Pick<WorkerProps, "crons"> | undefined,
  output: Pick<Worker["Attributes"], "crons"> | undefined,
): boolean => olds?.crons !== undefined || (output?.crons?.length ?? 0) > 0;

/**
 * Optional override for the account's stable `workers.dev` subdomain
 * (`<subdomain>` in `https://<script>.<subdomain>.workers.dev`). When set,
 * Worker URL construction skips `GET /accounts/{id}/workers/subdomain`.
 */
const CLOUDFLARE_WORKERS_SUBDOMAIN = Config.String("CLOUDFLARE_WORKERS_SUBDOMAIN").pipe(
  Config.map((value) => value.trim()),
  Config.option,
);

const WORKERS_SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;

/**
 * Max concurrent `GET /zones/{id}/workers/routes` calls when observing the
 * routes attached to a Worker. Route listing is per-zone, so this fans out
 * with the number of zones the Worker has routes in; unbounded fan-out here
 * is what trips Cloudflare account-level 429 / code 971 throttling (#926).
 */
const WORKER_ROUTE_LIST_CONCURRENCY = 8;

type MetadataHashValue =
  | string
  | number
  | boolean
  | null
  | undefined
  | readonly MetadataHashValue[]
  | { readonly [key: string]: MetadataHashValue };

/**
 * Deeply materialize an arbitrary value into a JSON-stable shape for hashing:
 * unwrap `Redacted` secrets by value, ISO-stringify `Date`s, keep plain
 * objects/arrays/primitives, and drop Effects, functions, `undefined`, and
 * class instances (which don't round-trip through `JSON.stringify`). Redacted
 * values contribute by value, not by reference identity, so two
 * independently-constructed secrets with the same contents hash identically.
 *
 * Effects are dropped, never executed: evaluating one here may require
 * plan-phase context that is not available inside lifecycle operations.
 */
const resolveMetadataHashValue = (value: unknown): Effect.Effect<MetadataHashValue> =>
  Effect.gen(function* () {
    if (Effect.isEffect(value)) {
      return undefined;
    }
    const resolved = Redacted.isRedacted(value) ? Redacted.value(value) : value;

    if (
      resolved === null ||
      Predicate.isString(resolved) ||
      Predicate.isNumber(resolved) ||
      Predicate.isBoolean(resolved)
    ) {
      return resolved;
    }
    if (resolved === undefined || Predicate.isFunction(resolved)) {
      return undefined;
    }
    if (Predicate.isDate(resolved)) {
      return resolved.toISOString();
    }
    if (Array.isArray(resolved)) {
      return yield* Effect.forEach(resolved, (item) => resolveMetadataHashValue(item), {
        concurrency: "unbounded",
      });
    }
    if (Predicate.isObject(resolved)) {
      // Only plain objects round-trip predictably. A class instance would
      // serialize to `{}` (or throw), so drop it rather than hash a lie.
      const prototype = Object.getPrototypeOf(resolved);
      if (prototype !== Object.prototype && prototype !== null) {
        return undefined;
      }
      const entries = yield* Effect.forEach(
        Object.entries(resolved),
        ([key, nested]) =>
          resolveMetadataHashValue(nested).pipe(
            Effect.map((materializedNested) => [key, materializedNested] as const),
          ),
        { concurrency: "unbounded" },
      );
      return Object.fromEntries(entries.filter(([, nested]) => nested !== undefined));
    }
    return undefined;
  });

/**
 * The deploy-time metadata surface of a Worker whose changes must trigger an
 * update but that never touch the bundle/vite/asset-content hashes:
 * compatibility, env/bindings, asset routing config, cache, limits, logpush,
 * observability, placement, subdomain, and tags. See #745.
 */
interface WorkerMetadataHashInput {
  readonly props: WorkerProps;
  readonly bindings: readonly ResourceBinding<Worker["Binding"]>[];
  readonly accountId: string;
  readonly stack: { readonly name: string; readonly stage: string };
  /**
   * The resolved URL a `Worker.URL` (`self_url`) binding lowers into.
   * Included in the hash so external URL changes (an account-subdomain
   * rename, a custom-domain reorder) redeploy the Worker with the fresh
   * value even though props and binding data are unchanged.
   */
  readonly selfUrl?: string;
}

// The asset router config the resource declares (htmlHandling,
// notFoundHandling, ...), minus the local `directory` path (machine-specific,
// would break hash stability across machines) and the precomputed `hash`
// (already compared via `output.hash.assets`). A bare string `assets` is just
// a directory path, so it contributes nothing here.
const workerAssetConfigForHash = (assets: WorkerProps["assets"]) => {
  if (!assets || typeof assets === "string") {
    return undefined;
  }
  const { directory: _directory, ...config } = assets;
  if (Predicate.hasProperty(config, "hash")) {
    const { hash: _hash, ...configWithoutHash } = config;
    return configWithoutHash;
  }
  return config;
};

/**
 * Hash a Worker's deploy-time metadata surface so metadata-only edits are
 * detected by the diff (#745). Previously the update decision compared only
 * the bundle/vite/asset-content hashes, so a change to e.g. a compatibility
 * flag or observability config planned as a noop and silently never deployed.
 */
const resolveWorkerMetadataHash = ({
  props,
  bindings,
  accountId,
  stack,
  selfUrl,
}: WorkerMetadataHashInput): Effect.Effect<string> =>
  resolveMetadataHashValue({
    accountId,
    selfUrl,
    stack: { name: stack.name, stage: stack.stage },
    compatibility: getCompatibility(props),
    // Every `env` entry is lowered into binding data by
    // `bindWorkerAsyncBindings`, including literals and VITE_ values. Hash only
    // that canonical wire representation. Resource-backed env values can be
    // materialized as different attribute projections between reconcile and a
    // later plan; hashing props.env as well would turn those irrelevant shape
    // differences into perpetual updates.
    bindings: bindings.map((binding) => ({ sid: binding.sid, data: binding.data })),
    assets: workerAssetConfigForHash(props.assets),
    cache: props.cache,
    entrypoints: props.entrypoints,
    limits: props.limits,
    logpush: props.logpush,
    observability: props.observability,
    placement: props.placement,
    // The source descriptor is plain JSON data; hashing it means
    // switching providers (or changing provider options) triggers an
    // update even when no hash slot the new source computes differs.
    source: props.source,
    tags: props.tags,
    // Reduce each consumer to its script name: a referenced Worker's other
    // attributes (hash, url, ...) change on every consumer deploy, which
    // would spuriously re-deploy this producer.
    tailConsumers: resolveTailConsumers(props.tailConsumers),
    streamingTailConsumers: resolveTailConsumers(props.streamingTailConsumers),
    workersDev: resolveWorkersDev(props.workersDev),
    // Reduce `version.parent` to the parent's script name: the resolved
    // parent is a full attributes object whose *other* fields (hash, url,
    // ...) change on every parent deploy, which would spuriously re-version
    // this Worker even though nothing about the version itself changed.
    version: props.version
      ? {
          parent: resolveVersionParentName(props.version),
          traffic: props.version.traffic,
          alias: props.version.alias,
          affinity: props.version.affinity,
          message: props.version.message,
          tag: props.version.tag,
        }
      : undefined,
    preview: props.preview
      ? {
          of: resolvePreviewParentName(props.preview),
          name: props.preview.name,
          message: props.preview.message,
          tag: props.preview.tag,
        }
      : undefined,
  }).pipe(Effect.flatMap((metadata) => sha256Object({ metadata })));

export const WorkerProvider = () =>
  ProviderLayer.dual(Worker, {
    live: () => LiveWorkerProvider(),
    // The local runtime deps (workerd, WorkerProxy, LocalRuntimeState)
    // compose INTO the local variant so a live deploy only constructs them
    // if the local provider is actually demanded (e.g. deleting a local
    // dev worker's state row). See ProviderLayer.dual.
    local: () => LocalWorkerProvider().pipe(Layer.provide(localRuntimeServices())),
  });

export const LiveWorkerProvider = () =>
  Provider.effect(
    Worker,
    Effect.gen(function* () {
      const stack = yield* Stack;
      const dotAlchemy = yield* dotAlchemyDirectory;

      // const createScriptSubdomain = yield* workers.createScriptSubdomain;
      // const deleteScript = yield* workers.deleteScript;
      // const getScriptSubdomain = yield* workers.getScriptSubdomain;
      // const getScriptSchedule = yield* workers.getScriptSchedule;
      // const getScriptSettings = yield* workers.getScriptScriptAndVersionSetting;
      // const getSubdomain = yield* workers.getSubdomain;
      // const putScript = yield* workers.putScript;
      // const putScriptSchedule = yield* workers.putScriptSchedule;
      // const putDomain = yield* workers.putDomain;
      // const listDomains = yield* workers.listDomains;
      // const deleteDomain = yield* workers.deleteDomain;
      // const listZones = yield* zones.listZones;
      const telemetry = yield* CloudflareLogs;

      // Account subdomain is invariant for the life of a provider layer —
      // memoize so N Workers (or repeated plan/deploy reads) don't each hit
      // GET /accounts/{id}/workers/subdomain and trip Cloudflare's 429/971
      // throttle (#926). `CLOUDFLARE_WORKERS_SUBDOMAIN` bypasses the lookup
      // entirely when the operator already knows the value.
      const getAccountSubdomain = yield* cachedFunction((accountId: string) =>
        Effect.gen(function* () {
          const configured = yield* CLOUDFLARE_WORKERS_SUBDOMAIN;
          if (Option.isSome(configured) && configured.value !== "") {
            if (!WORKERS_SUBDOMAIN_PATTERN.test(configured.value)) {
              return yield* Effect.die(
                new Error(
                  `Invalid CLOUDFLARE_WORKERS_SUBDOMAIN "${configured.value}": ` +
                    "expected a workers.dev subdomain label (lowercase letters, digits, hyphens)",
                ),
              );
            }
            return configured.value;
          }
          const result = yield* workers.getSubdomain({ accountId });
          return result.subdomain;
        }),
      );

      // Converge the script's workers.dev settings via `POST /subdomain`.
      // The two toggles are independent on the Cloudflare API: `enabled`
      // drives the stable `<name>.<account>.workers.dev` URL and
      // `previews_enabled` the per-version preview URLs.
      const setWorkerSubdomain = Effect.fn(function* (name: string, desired: ResolvedWorkersDev) {
        const { accountId } = yield* yield* CloudflareEnvironment;
        return yield* workers.createScriptSubdomain({
          accountId,
          scriptName: name,
          enabled: desired.enabled,
          previewsEnabled: desired.previewsEnabled,
        });
      });

      const normalizeCrons = (crons: string[] | undefined): string[] =>
        Array.from(new Set(crons ?? []));

      const hasSelfUrlBinding = (bindings: readonly ResourceBinding<Worker["Binding"]>[]) =>
        bindings.some((b) => (b.data.bindings ?? []).some((item) => item.type === "self_url"));

      // Resolve the URL this Worker will be served at — the same formula that
      // produces the `url` attribute (first custom domain in user order, else
      // the workers.dev URL) — usable BEFORE the script upload, so `Worker.URL`
      // bindings can be lowered into plain_text bindings and VITE_*-prefixed
      // env entries can be inlined into the client bundle at build time.
      const resolveSelfUrl = Effect.fn(function* (
        name: string,
        props: WorkerProps,
        accountId: string,
      ) {
        const domain = yield* resolveWorkerDomain(props.domain);
        if (domain) {
          return `https://${domain.name}`;
        }
        if (!resolveWorkersDev(props.workersDev).enabled) {
          return yield* Effect.die(
            `Worker "${name}" binds its own URL (Worker.URL) but has none: the stable workers.dev URL is disabled (workersDev) and no custom domain is configured.`,
          );
        }
        return `https://${name}.${yield* getAccountSubdomain(accountId)}.workers.dev`;
      });

      const getWorkerCrons = Effect.fn(function* (scriptName: string) {
        const { accountId } = yield* yield* CloudflareEnvironment;
        return yield* workers.getScriptSchedule({ accountId, scriptName }).pipe(
          Effect.map((response) =>
            normalizeCrons(response.schedules.map((schedule) => schedule.cron)),
          ),
          Effect.catchTag("WorkerNotFound", () => Effect.succeed([])),
        );
      });

      const reconcileCrons = (
        scriptName: string,
        desired: string[],
        previous: string[],
        session: ScopedPlanStatusSession,
      ) =>
        Effect.gen(function* () {
          const { accountId } = yield* yield* CloudflareEnvironment;
          const live = yield* getWorkerCrons(scriptName);
          const desiredSorted = [...desired].sort();
          const liveSorted = [...live].sort();
          const changed =
            desiredSorted.length !== liveSorted.length ||
            desiredSorted.some((cron, index) => cron !== liveSorted[index]);

          if (!changed) return live;

          if (desired.length > 0 || previous.length > 0 || live.length > 0) {
            yield* session.note(`Reconciling Cron Triggers (${desired.length}) ...`, {
              kind: "status",
            });
          }

          const result = yield* workers
            .putScriptSchedule({ accountId, scriptName, body: desired.map((cron) => ({ cron })) })
            .pipe(
              Effect.retry({
                while: (error) => error._tag === "WorkerNotFound",
                schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
              }),
            );
          return normalizeCrons(result.schedules.map((schedule) => schedule.cron));
        });

      /**
       * Resolve a hostname to a Cloudflare zone id. An explicit pin
       * (`zoneId` / zone name / `{ zoneId }`) wins. Otherwise look the
       * hostname up with {@link resolveZoneId} (`GET /zones?name=` per
       * parent label) — never by listing the account's first page of zones.
       */
      const inferZoneIdForHostname = (
        hostname: string,
        zoneCache: Map<string, string>,
        zone?: ZoneReference,
      ) =>
        Effect.gen(function* () {
          const cacheKey =
            zone === undefined
              ? hostname
              : `${hostname}:${typeof zone === "string" ? zone : zone.zoneId}`;
          const cached = zoneCache.get(cacheKey);
          if (cached) return cached;
          const { accountId } = yield* yield* CloudflareEnvironment;
          const zoneId = yield* resolveZoneId({ accountId, zone, hostname });
          zoneCache.set(cacheKey, zoneId);
          return zoneId;
        });

      const reconcileDomains = (
        scriptName: string,
        desired: string[],
        zone?: ZoneReference,
        previewsEnabled?: boolean,
      ) =>
        Effect.gen(function* () {
          const { accountId } = yield* yield* CloudflareEnvironment;
          // Always query the live state of domains attached to *this*
          // Worker rather than trusting `_previous` from local state.
          // State may have been wiped, populated by another machine, or
          // simply be out of date. Without this we PUT domains that are
          // already registered to this same Worker and Cloudflare
          // returns a confusing "hostname already in use" error.
          const liveAll = yield* workers.listDomains({ accountId, service: scriptName }).pipe(
            Effect.map((r) =>
              (r.result ?? []).flatMap((d) =>
                d.id && d.hostname && d.zoneId
                  ? [
                      {
                        id: d.id,
                        hostname: d.hostname,
                        zoneId: d.zoneId,
                        service: d.service ?? undefined,
                        previewsEnabled: d.previewsEnabled === true,
                      },
                    ]
                  : [],
              ),
            ),
            Effect.orElseSucceed(() => []),
          );

          const desiredSet = new Set(desired);
          const liveByHostname = new Map(liveAll.map((d) => [d.hostname, d]));

          // Detach what's no longer wanted. Use the live list so we
          // don't try to delete domains we no longer track.
          const toRemove = liveAll.filter((d) => !desiredSet.has(d.hostname));
          yield* Effect.forEach(
            toRemove,
            (d) =>
              workers
                .deleteDomain({ accountId, domainId: d.id })
                .pipe(Effect.catchTag("DomainNotFound", () => Effect.void)),
            { concurrency: "unbounded" },
          );

          if (desired.length === 0) return [];

          const zoneCache = new Map<string, string>();

          // Attach `hostname` to this Worker. Skip the PUT entirely if
          // the hostname is already attached to *this* Worker — that's a
          // no-op for Cloudflare and avoids the "already in use" 409.
          // If it's attached to a *different* Worker, refuse with a
          // clear message rather than silently re-routing traffic.
          const attachDomain = Effect.fn(function* (hostname: string) {
            const live = liveByHostname.get(hostname);
            const desiredZoneId =
              zone === undefined
                ? undefined
                : yield* inferZoneIdForHostname(hostname, zoneCache, zone);
            if (
              live &&
              !shouldRecreateWorkerDomainAttachment(live.zoneId, desiredZoneId) &&
              live.previewsEnabled === (previewsEnabled === true)
            ) {
              return { hostname: live.hostname, id: live.id, zoneId: live.zoneId };
            }

            if (live) {
              // Cloudflare cannot change the zone of an existing custom
              // domain in place. Delete only this still-desired attachment,
              // then recreate it below with the explicitly requested zone.
              yield* workers
                .deleteDomain({ accountId, domainId: live.id })
                .pipe(Effect.catchTag("DomainNotFound", () => Effect.void));
            }

            // Not attached to this Worker — but it could still belong
            // to another Worker. Check before we try to PUT so we can
            // emit a helpful error instead of the raw 409.
            const otherOwner = yield* workers.listDomains({ accountId, hostname }).pipe(
              Effect.map((r) =>
                (r.result ?? []).find((d) => d.hostname === hostname && d.service !== scriptName),
              ),
              Effect.orElseSucceed(() => undefined),
            );
            if (otherOwner?.id) {
              return yield* Effect.die(
                new Error(
                  `Cannot attach hostname '${hostname}' to Worker '${scriptName}': ` +
                    `it is already attached to Worker '${otherOwner.service ?? "<unknown>"}'. ` +
                    `Detach it from that Worker first, or pick a different hostname.`,
                ),
              );
            }

            const zoneId = desiredZoneId ?? (yield* inferZoneIdForHostname(hostname, zoneCache));
            // Same eventual-consistency window as `setWorkerSubdomain`:
            // PUT /accounts/.../workers/domains right after `putScript`
            // can return `WorkerNotFound` until Cloudflare's script
            // registry has propagated. Retry on that specific tag.
            const res = yield* workers
              .putDomain({
                accountId,
                hostname,
                service: scriptName,
                zoneId,
                // Private-beta field — only send it when the user opted
                // into custom-domain Previews. Omitting it keeps the
                // public PUT /workers/domains body unchanged for everyone
                // else.
                ...(previewsEnabled === true ? { previewsEnabled: true } : {}),
              })
              .pipe(
                Effect.retry({
                  while: (error) => error._tag === "WorkerNotFound",
                  schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
                }),
                Effect.retry({
                  while: (error) => error._tag === "HostnameAlreadyInUse",
                  schedule: workerDomainConflictSchedule,
                }),
              );
            return { hostname, id: res.id ?? "", zoneId: res.zoneId ?? zoneId };
          });

          const applied = yield* Effect.forEach(desired, attachDomain, {
            concurrency: "unbounded",
          });
          return applied;
        });

      // The preview URL of the Worker's *current* version:
      // `https://<version-prefix>-<name>.<subdomain>.workers.dev`, where the
      // prefix is the first 8 characters of the version id (read from the
      // latest deployment's majority version). Resolves to `undefined` when
      // no deployment is visible yet — callers treat the preview URL as
      // best-effort. Only consulted in previews-only mode
      // (`workersDev: { enabled: false, previewsEnabled: true }`), where it
      // is the Worker's only workers.dev surface.
      const getPreviewUrl = Effect.fn(function* (scriptName: string, accountSubdomain: string) {
        const { accountId } = yield* yield* CloudflareEnvironment;
        const deployments = yield* workers.listScriptDeployments({ accountId, scriptName }).pipe(
          Effect.map((response) => response.deployments ?? []),
          Effect.orElseSucceed(() => []),
        );
        const latest = [...deployments].sort((a, b) => b.createdOn.localeCompare(a.createdOn))[0];
        const version = latest?.versions?.reduce(
          (max, candidate) =>
            max === undefined || candidate.percentage > max.percentage ? candidate : max,
          undefined as { percentage: number; versionId: string } | undefined,
        );
        if (!version?.versionId) return undefined;
        return `https://${version.versionId.slice(0, 8)}-${scriptName}.${accountSubdomain}.workers.dev`;
      });

      const computeStableWorkerUrls = Effect.fn(function* (params: {
        scriptName: string;
        workersDev: ResolvedWorkersDev;
        domain: ResolvedWorkerDomain | undefined;
      }) {
        const { workersDev, domain, scriptName } = params;
        const urls: string[] = [];
        if (domain) {
          urls.push(
            `https://${domain.name}`,
            ...domain.aliases.map((hostname) => `https://${hostname}`),
          );
        }
        if (workersDev.enabled) {
          const { accountId } = yield* yield* CloudflareEnvironment;
          const accountSubdomain = yield* getAccountSubdomain(accountId);
          urls.push(`https://${scriptName}.${accountSubdomain}.workers.dev`);
        }
        return urls;
      });

      /**
       * Assemble every URL a deployed, script-owning Worker serves at, most
       * significant first — the first entry becomes the `url` attribute:
       *
       * 1. `https://<domain.name>` — the canonical custom domain
       * 2. aliases, in declared order
       * 3. the stable workers.dev URL (`workersDev.enabled`)
       * 4. preview URLs of the version this deploy uploaded (gradual
       *    rollouts), or — in previews-only mode — the current version's
       *    preview URL, which is then the only workers.dev surface
       *
       * Redirect hostnames never appear: they don't serve the Worker.
       * (Version workers don't use this — their `urls` are their preview
       * URLs, assembled in `putWorkerVersion`.)
       */
      const computeWorkerUrls = Effect.fn(function* (params: {
        scriptName: string;
        workersDev: ResolvedWorkersDev;
        domain: ResolvedWorkerDomain | undefined;
        /** the version uploaded by this deploy (self-rollout), if any */
        uploadedVersionId?: string;
        /** user-provided `version.alias` attached to the uploaded version */
        uploadedVersionAlias?: string;
      }) {
        const { workersDev, scriptName } = params;