sailfork / t3code-github / .repos/ alchemy-effect/ packages/ prisma/ src/ Compute.ts

import { Retry } from "@distilled.cloud/prisma";
import {
  type GetServicesResponse,
  type GetEnvironmentVariablesResponse,
  type GetProjectBranchesResponse,
  deleteEnvironmentVariable,
  getServices,
  getService,
  getBranch,
  getEnvironmentVariables,
  getProjectBranches,
  updateService,
  updateEnvironmentVariable,
  createService,
  createServiceDeployment,
  createServiceRollback,
  createEnvironmentVariable,
} from "@distilled.cloud/prisma/management";
import { Unowned } from "alchemy/AdoptPolicy";
import { AlchemyContext } from "alchemy/AlchemyContext";
import * as Bundle from "alchemy/Bundle/Bundle";
import { findCwdForBundle } from "alchemy/Bundle/TempRoot";
import { isResolved } from "alchemy/Diff";
import { HttpServer, type HttpEffect } from "alchemy/Http";
import type { InputProps } from "alchemy/Input";
import * as ProviderLayer from "alchemy/Local/ProviderLayer";
import * as Output from "alchemy/Output";
import { createPhysicalName } from "alchemy/PhysicalName";
import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
import * as Provider from "alchemy/Provider";
import { Resource, type ResourceBinding } from "alchemy/Resource";
import type { ProcessContext, ProcessServices } from "alchemy/Runtime/Process";
import { RuntimeContext } from "alchemy/RuntimeContext";
import { Stack } from "alchemy/Stack";
import { logChildLine } from "alchemy/Util/LogRecord";
import { sha256Object } from "alchemy/Util/sha256";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import type { HttpClientResponse } from "effect/http/HttpClientResponse";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as ChildProcess from "effect/process/ChildProcess";
import type { ChildProcessHandle } from "effect/process/ChildProcessSpawner";
import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import type * as rolldown from "rolldown";
import { createComputeArchive, normalizeEntrypoint } from "./ComputeArchive.ts";
import {
  runBuildCommand,
  runComputeAutoBuild,
  runComputeStaticBuild,
  type ComputeAutoBuildFramework,
} from "./ComputeBuild.ts";
import {
  destroyApp,
  destroyDeployment,
  toDeploymentUrl,
  waitForDeploymentStatus,
} from "./ComputeLifecycle.ts";
import { readUploadArtifact, uploadArtifact } from "./Deployment.ts";
import { ensureAppImmutableIdentity } from "./internal/AppIdentity.ts";
import { promoteAppObserved, waitForAppDeploymentTarget } from "./internal/AppPromotion.ts";
import { normalizeBundleFilePath } from "./internal/BundlePaths.ts";
import { aggregateCleanupFailure } from "./internal/CleanupFailure.ts";
import {
  startDeploymentIdempotent,
  stopDeploymentIdempotent,
} from "./internal/DeploymentActions.ts";
import { ensureDeploymentMembership } from "./internal/DeploymentIdentity.ts";
import { observeDeployment } from "./internal/DeploymentObserve.ts";
import type {
  ObservedApp,
  ObservedDeployment,
  ObservedEnvironmentVariable,
} from "./internal/Observed.ts";
import { PrismaPaginationError } from "./internal/Pagination.ts";
import {
  concreteIdsChanged,
  isInputObject,
  isPrismaDevId,
  resolveProjectId,
  unresolvedProjectIdOf,
} from "./internal/Refs.ts";
import { tailDeploymentLogs } from "./PrismaLogs.ts";
import type { Project } from "./Project.ts";
import type { Providers } from "./Providers.ts";
import type { PrismaRegionId } from "./Types.ts";

export class ComputeConflict extends Data.TaggedError("ComputeConflict")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

export class ComputeInvalidProps extends Data.TaggedError("ComputeInvalidProps")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

export class ComputeNotReady extends Data.TaggedError("ComputeNotReady")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

export class ComputeOperationFailed extends Data.TaggedError("ComputeOperationFailed")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

export class ComputeUnexpectedResponse extends Data.TaggedError("ComputeUnexpectedResponse")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

const ComputeTypeId = "Prisma.Compute" as const;
type ComputeTypeId = typeof ComputeTypeId;

export interface ComputeCommandBuild {
  /**
   * Shell command that creates the deployable output directory.
   */
  command: string;
  /**
   * Working directory for the build command.
   *
   * @default path
   */
  cwd?: string;
  /**
   * Build output directory, relative to `cwd`.
   */
  outdir: string;
  /**
   * Entrypoint inside `outdir`.
   */
  entrypoint?: string;
  /**
   * Environment variables supplied to the build command.
   * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
   * inherited; include one here explicitly only when the application build
   * genuinely needs Prisma Management API access.
   *
   * Plain strings are persisted in Alchemy state. Wrap secrets with
   * `Redacted.make(secret)`; Prisma-side encryption does not protect a value
   * already stored in Alchemy state.
   *
   * ```typescript
   * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
   * ```
   */
  env?: Record<string, string | Redacted.Redacted<string> | undefined>;
  /**
   * Maximum bytes retained from each build output stream.
   *
   * @default 1048576 (1 MiB)
   */
  outputLimitBytes?: number;
  /**
   * Maximum wall-clock time for the build command.
   *
   * @default 900 (15 minutes)
   */
  timeoutSeconds?: number;
}

export interface ComputeAutoBuild {
  /**
   * Auto-detect a Prisma Compute build strategy, or force one framework.
   */
  type: "auto";
  /**
   * Framework build strategy.
   *
   * @default "auto"
   */
  framework?: ComputeAutoBuildFramework;
  /**
   * Environment variables supplied to the build command.
   * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
   * inherited; include one here explicitly only when the application build
   * genuinely needs Prisma Management API access.
   *
   * Plain strings are persisted in Alchemy state. Wrap secrets with
   * `Redacted.make(secret)`.
   *
   * ```typescript
   * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
   * ```
   */
  env?: Record<string, string | Redacted.Redacted<string> | undefined>;
  /**
   * Maximum bytes retained from each framework build output stream.
   *
   * @default 1048576 (1 MiB)
   */
  outputLimitBytes?: number;
  /**
   * Maximum wall-clock time for the framework build command.
   *
   * @default 900 (15 minutes)
   */
  timeoutSeconds?: number;
}

export interface ComputeStaticBuild {
  /**
   * Build a static site and package it with a production HTTP server.
   */
  type: "static";
  /**
   * Static output directory, relative to `cwd`.
   */
  outdir: string;
  /**
   * Optional shell command that creates the static output directory. Omit it
   * when `outdir` already contains the files to deploy.
   */
  command?: string;
  /**
   * Working directory for the build command and `outdir`.
   *
   * @default path
   */
  cwd?: string;
  /**
   * HTML file served at the root and for SPA fallbacks.
   *
   * @default "index.html"
   */
  indexPage?: string;
  /**
   * Serve the index page when no static file matches the request.
   *
   * @default false
   */
  spa?: boolean;
  /**
   * Environment variables supplied to the build command.
   * Ambient `PRISMA_SERVICE_TOKEN` and `PRISMA_API_TOKEN` credentials are not
   * inherited; include one here explicitly only when the application build
   * genuinely needs Prisma Management API access.
   *
   * Plain strings are persisted in Alchemy state. Wrap secrets with
   * `Redacted.make(secret)`.
   *
   * ```typescript
   * env: { NPM_TOKEN: Redacted.make(process.env.NPM_TOKEN!) }
   * ```
   */
  env?: Record<string, string | Redacted.Redacted<string> | undefined>;
  /**
   * Maximum bytes retained from each build output stream.
   *
   * @default 1048576 (1 MiB)
   */
  outputLimitBytes?: number;
  /**
   * Maximum wall-clock time for the build command.
   *
   * @default 900 (15 minutes)
   */
  timeoutSeconds?: number;
}

export type ComputeBuild = ComputeCommandBuild | ComputeAutoBuild | ComputeStaticBuild;

export interface ComputeBundleOptions {
  /**
   * Rolldown input options for effect-native Compute bundles.
   */
  input?: Partial<rolldown.InputOptions>;
  /**
   * Rolldown output options for effect-native Compute bundles.
   */
  output?: Partial<rolldown.OutputOptions>;
  /**
   * Additional Alchemy bundle options for effect-native Compute bundles.
   */
  extra?: Bundle.BundleExtraOptions;
}

export interface ComputeDev {
  /**
   * Local command to run during `alchemy dev`.
   */
  command?: string;
  /**
   * Working directory for the dev command.
   *
   * @default path
   */
  cwd?: string;
  /**
   * Local development port.
   */
  port?: number;
  /**
   * Explicit local URL to expose in the resource output.
   */
  url?: string;
  /**
   * Extra environment variables for the dev command.
   * Plain strings are persisted in Alchemy state. Wrap secrets with
   * `Redacted.make(secret)`.
   */
  env?: Record<string, string | Redacted.Redacted<string> | undefined>;
}

export interface ComputeHealthCheck {
  /**
   * Absolute application path to probe after the deployment starts and after
   * promotion.
   *
   * @example "/api/health"
   */
  path: string;
  /**
   * Exact HTTP status codes that indicate readiness. When omitted, any 2xx
   * response is healthy.
   *
   * @default Any status from 200 through 299
   */
  statusCodes?: readonly number[];
}

export interface ComputeProps extends PlatformProps {
  /**
   * Project ID or `project.projectId` output that owns the App.
   */
  project: string | Project;
  /**
   * App display name. If omitted, Alchemy generates a stable physical name.
   */
  appName?: string;
  /**
   * Region where the App is placed.
   *
   * @default The project's default region, falling back to "us-east-1"
   */
  regionId?: PrismaRegionId;
  /**
   * Branch ID to attach the App to. Mutually exclusive with branchGitName.
   * If both branch fields are omitted, Alchemy attaches to the project's
   * current default branch.
   */
  branchId?: string;
  /**
   * Branch git name to attach the App to. Mutually exclusive with branchId.
   *
   * @default The project's current default branch
   */
  branchGitName?: string;
  /**
   * Application directory used for pre-built artifacts and build commands.
   *
   * @default "."
   */
  path?: string;
  /**
   * Additional files or directories to exclude from path deployments. Static
   * build patterns are relative to the configured output directory; other
   * patterns are artifact-relative. `*` and `**` wildcards are supported;
   * absolute paths, parent segments, and negated patterns are rejected.
   * `.env*`, `.git`, and `.alchemy` are always excluded. Static index pages
   * must remain present after exclusions.
   */
  archiveIgnore?: readonly string[];
  /**
   * Entrypoint relative to the deployed artifact directory.
   * If omitted, Alchemy reads `package.json#main`.
   */
  entrypoint?: string;
  /**
   * Entry module for an effect-native Compute app.
   *
   * This is required when you pass an inline Effect implementation to
   * `Prisma.Compute`, and ignored for external path deployments.
   */
  main?: string;
  /**
   * Exported symbol inside `main` for effect-native Compute apps.
   *
   * @default "default"
   */
  handler?: string;
  /**
   * Bundler options for effect-native Compute apps.
   */
  bundle?: ComputeBundleOptions;
  /**
   * Effect-native runtime exports populated by the Platform constructor.
   *
   * @internal
   */
  exports?: string[] | Record<string, unknown>;
  /**
   * Build command and output directory. Set to `"auto"` or `{ type: "auto" }`
   * to use Prisma Compute-style framework detection for Next.js, Nuxt, Astro,
   * TanStack Start, Vite, or Bun. Set to `false` to upload `path` as a
   * pre-built artifact.
   */
  build?: ComputeBuild | false | "auto";
  /**
   * Path to a pre-created `tar.gz` artifact file. When supplied, Alchemy reads
   * and uploads it directly.
   */
  artifactPath?: string;
  /**
   * HTTP port exposed by the application.
   *
   * @default 8080
   */
  port?: number;
  /**
   * Runtime environment variables to sync through Prisma's environment
   * variable API before creating a new deployment. Set a value to `null`
   * to delete that variable.
   *
   * Plain strings are persisted in Alchemy state. For secrets, use
   * `Redacted.make(secret)`; encryption in the Prisma Management API does not
   * protect a plain value already recorded in Alchemy state.
   *
   * The Management API exposes neither an idempotency key nor ownership
   * metadata for environment variables, and reads return redacted values. If
   * a process crashes after Prisma commits a create but before Alchemy saves
   * its returned ID, the next deploy safely refuses to claim that natural-key
   * match. Use standalone `Prisma.EnvironmentVariable` resources for critical
   * keys that need independent lifecycle management and explicit adoption.
   *
   * ```typescript
   * env: {
   *   LOG_LEVEL: "info",
   *   API_TOKEN: Redacted.make(process.env.API_TOKEN!),
   * }
   * ```
   */
  env?: Record<string, string | Redacted.Redacted<string> | null | undefined>;
  /**
   * Prisma environment variable class used by the `env` convenience property.
   *
   * @default "production"
   */
  envClass?: "production" | "preview";
  /**
   * Create the next deployment by reusing the previous code artifact.
   *
   * @default false
   */
  skipCodeUpload?: boolean;
  /**
   * Start the created/reused deployment.
   * Set `skipPromote: true` when disabling start.
   *
   * @default true
   */
  start?: boolean;
  /**
   * Do not promote the deployment to the stable App endpoint.
   *
   * @default false
   */
  skipPromote?: boolean;
  /**
   * Delete the previously promoted deployment after the new one is promoted.
   *
   * @default false
   */
  destroyOldDeployment?: boolean;
  /**
   * Poll timeout while waiting for start/stop.
   *
   * @default 120
   */
  timeoutSeconds?: number;
  /**
   * Poll interval while waiting for start/stop.
   *
   * @default 1000
   */
  pollIntervalMs?: number;
  /**
   * Verify that Prisma's public preview/App URL has reached the edge after
   * the Management API reports the deployment as running.
   *
   * @default true
   */
  verifyUrl?: boolean;
  /**
   * Optional application-level health check. Without this option, URL
   * verification only waits for Prisma edge routing to stop returning its
   * platform-level service-not-found response. With this option, Alchemy also
   * sends a public GET to the preview URL before promotion and to the stable
   * App URL afterward. Redirects are not followed. Each probe phase gets the
   * full `urlReadinessTimeoutSeconds` budget.
   *
   * Health checks run only during cloud deployment, not `alchemy dev`, and
   * cannot be combined with `verifyUrl: false` or `start: false`.
   */
  healthCheck?: ComputeHealthCheck;
  /**
   * Maximum time to wait for Prisma's public URL to stop returning the
   * platform-level "Service not found" page.
   *
   * @default 60
   */
  urlReadinessTimeoutSeconds?: number;
  /**
   * Local development behavior for `alchemy dev`.
   */
  dev?: ComputeDev;
}

export interface Compute extends Resource<
  ComputeTypeId,
  ComputeProps,
  {
    /**
     * Prisma App ID.
     */
    appId: string;
    /**
     * Prisma deployment ID created for the current deployment.
     */
    deploymentId: string | undefined;
    /**
     * Project ID that owns the app.
     */
    projectId: string;
    /**
     * App display name.
     */
    appName: string;
    /**
     * Region ID where the App is placed.
     */
    regionId: string;
    /**
     * Preview endpoint domain for the deployment.
     */
    deploymentEndpointDomain: string | undefined;
    /**
     * HTTPS URL for the deployment endpoint.
     */
    deploymentUrl: string | undefined;
    /**
     * Stable App endpoint domain after promotion.
     */
    appEndpointDomain: string | undefined;
    /**
     * Preferred URL for the app, local in dev or stable/preview in deploys.
     */
    url: string | undefined;
    /**
     * Whether the current deployment was promoted to the stable endpoint.
     */
    promoted: boolean;
    /**
     * Previously promoted deployment ID observed before deploy.
     */
    previousDeploymentId: string | null | undefined;
    /**
     * Action taken for the previous deployment.
     */
    previousDeploymentAction: "stopped" | "destroyed" | "still-active" | null | undefined;
    /** Stable App endpoint readiness observed after promotion. */
    readinessStatus?: "ready" | "pending" | "skipped";
    /** Old deployment cleanup that will be retried before another generation. */
    pendingDeploymentCleanup?: {
      deploymentId: string;
      action: "stop" | "destroy";
    };
    /**
     * Environment variable keys managed by this Compute resource.
     *
     * This includes explicit `env` props and env vars added by bindings.
     */
    environmentKeys?: string[];
    /**
     * Environment variable IDs created by this Compute resource, keyed by
     * variable name. IDs are the ownership boundary for shared branch/project
     * environment-variable namespaces.
     */
    environmentVariableIds?: Record<string, string>;
    /**
     * Prisma environment class used for the managed environment variable keys.
     */
    environmentClass?: "production" | "preview";
    /**
     * Branch ID used for managed preview branch environment overrides, or null
     * for project-level environment templates.
     */
    environmentBranchId?: string | null;
    /**
     * Fingerprint of the uploaded artifact/reused artifact inputs and the
     * branch attachment that Prisma resolves environment variables from.
     */
    artifactHash: Redacted.Redacted<string> | undefined;
    /**
     * Whether the app output represents a local dev process.
     */
    local: boolean;
  },
  {
    env?: Record<string, string | Redacted.Redacted<string> | null | undefined>;
  },
  Providers
> {}

export type ComputeRuntimeServices = ProcessServices;

export type ComputeShape = Main<ComputeRuntimeServices>;

export interface ComputeRuntimeContext extends ProcessContext {
  readonly Type: ComputeTypeId;
}

export const isCompute = (value: unknown): value is Compute =>
  typeof value === "object" && value !== null && "Type" in value && value.Type === ComputeTypeId;

const hasEffectNativeComputeInput = (props: ComputeProps) =>
  props.isExternal !== true && (props.main !== undefined || props.exports !== undefined);

const isEffectNativeCompute = (props: ComputeProps) => hasEffectNativeComputeInput(props);

/**
 * Build and deploy an application to Prisma Compute.
 *
 * Prisma's create-deployment API exposes neither an idempotency key nor a
 * caller-defined recovery key. If the API commits a deployment but its create
 * response is lost before Alchemy persists the returned ID, that deployment
 * can remain orphaned and a later deploy may create another one. Alchemy does
 * not guess that the App's latest deployment is owned, because it could belong
 * to another actor. Use a durable, locked state backend and inspect the App's
 * deployment history after an interrupted create.
 *
 * ### Deploying an App
 * **Example:** Deploy a directory with an entrypoint
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project: project.projectId,
 *   path: "./apps/api",
 *   entrypoint: "server.ts",
 *   port: 3000,
 * });
 * ```
 *
 * **Example:** Deploy an Effect-native HTTP app
 * ```typescript
 * export default Prisma.Compute(
 *   "api",
 *   {
 *     project,
 *     appName: "api",
 *     main: import.meta.filename,
 *     port: 8080,
 *   },
 *   Effect.gen(function* () {
 *     return {
 *       fetch: Effect.succeed(HttpServerResponse.text("ok")),
 *     };
 *   }),
 * );
 * ```
 *
 * ### Bundling & Tree-shaking
 * `main` is bundled with rolldown at deploy time. Unused code is
 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
 * pure so unused parts prune more aggressively. Your app is not
 * marked pure.
 *
 * **Example:** Mark additional packages as pure
 * Only list packages with no top-level side effects.
 * ```typescript
 * {
 *   main: "./src/app.ts",
 *   bundle: {
 *     extra: { pure: { packages: ["my-lib", "@my-scope/*"] } },
 *   },
 * }
 * ```
 *
 * **Example:** Turn it off
 * ```typescript
 * {
 *   main: "./src/app.ts",
 *   bundle: { extra: { pure: false } },
 * }
 * ```
 *
 * ### Runtime Bindings
 * **Example:** Bind a Prisma Connection
 * ```typescript
 * export default Prisma.Compute(
 *   "api",
 *   {
 *     project,
 *     appName: "api",
 *     main: import.meta.filename,
 *   },
 *   Effect.gen(function* () {
 *     const db = yield* Prisma.Connect(connection);
 *     const sql = yield* SQL.Postgres({ url: db.databaseUrl });
 *
 *     return {
 *       fetch: Effect.gen(function* () {
 *         const users = yield* sql`SELECT * FROM users`;
 *         return yield* HttpServerResponse.json(users);
 *       }),
 *     };
 *   }).pipe(Effect.provide(Prisma.ConnectBinding)),
 * );
 * ```
 *
 * **Example:** Build before upload and replace old versions
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project: project.projectId,
 *   path: "./apps/api",
 *   build: {
 *     command: "bun build src/server.ts --target bun --outdir dist",
 *     outdir: "dist",
 *     entrypoint: "server.js",
 *   },
 *   port: 8080,
 *   env: {
 *     // Use this for a standalone Connection. A project's default database
 *     // is injected by Prisma without an explicit DATABASE_URL entry.
 *     DATABASE_URL: connection.databaseUrl,
 *   },
 *   destroyOldDeployment: true,
 * });
 * ```
 *
 * **Example:** Auto-build a framework app
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project: project.projectId,
 *   path: "./apps/web",
 *   build: "auto",
 *   destroyOldDeployment: true,
 * });
 * ```
 *
 * **Example:** Deploy a static site
 * ```typescript
 * const web = yield* Prisma.Compute("web", {
 *   project,
 *   path: "./site",
 *   build: {
 *     type: "static",
 *     outdir: ".",
 *   },
 * });
 * ```
 *
 * **Example:** Deploy a prebuilt tar.gz artifact
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project: project.projectId,
 *   artifactPath: "./dist/app.tar.gz",
 *   port: 8080,
 * });
 * ```
 *
 * ### Deployment Health
 * **Example:** Require application readiness before promotion
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project,
 *   path: "./apps/api",
 *   entrypoint: "server.ts",
 *   healthCheck: {
 *     path: "/api/health",
 *     // Defaults to any 2xx response when omitted.
 *     statusCodes: [200, 204],
 *   },
 * });
 * ```
 *
 * ### Local Development
 * **Example:** Run locally during alchemy dev
 * ```typescript
 * const app = yield* Prisma.Compute("api", {
 *   project: project.projectId,
 *   path: "./apps/api",
 *   entrypoint: "server.ts",
 *   dev: {
 *     command: "bun run dev",
 *     port: 3000,
 *   },
 * });
 * ```
 *
 * @resource
 * @product Compute
 */
export const Compute: Platform<
  Compute,
  ComputeRuntimeServices,
  ComputeShape,
  ComputeRuntimeContext
> & {
  <PropsReq = never>(
    id: string,
    props: InputProps<ComputeProps> | Effect.Effect<InputProps<ComputeProps>, never, PropsReq>,
  ): Effect.Effect<Compute, never, Providers | PropsReq>;
} = Platform(ComputeTypeId, {
  createRuntimeContext: (id): ComputeRuntimeContext => {
    const runners: Effect.Effect<void, never, unknown>[] = [];
    const env: Record<string, unknown> = {};
    let runtimeContext: ComputeRuntimeContext;
    const run: ProcessContext["run"] = (effect) =>
      Effect.sync(() => {
        runners.push(effect);
      });

    const serve = <Req = never>(handler: HttpEffect<Req>) =>
      Effect.sync(() => {
        runners.push(
          Effect.gen(function* () {
            const httpServer = yield* Effect.serviceOption(HttpServer).pipe(
              Effect.map(Option.getOrUndefined),
            );
            if (httpServer) {
              yield* httpServer.serve(
                handler.pipe(Effect.provideService(RuntimeContext, runtimeContext)),
              );
              return yield* Effect.never;
            }
          }),
        );
      });

    runtimeContext = {
      Type: ComputeTypeId,
      id,
      env,
      set: (bindingId: string, output: Output.Output) =>
        Effect.sync(() => {
          // Prisma env keys are validated to the uppercase POSIX shape
          // ([A-Z_][A-Z0-9_]*), so the storage key is uppercased here. The
          // runtime `get` receives the key this returns, so both halves
          // agree without a second mapping.
          const key = bindingId.replaceAll(/[^a-zA-Z0-9]/g, "_").toUpperCase();
          env[key] = output.pipe(
            Output.map((value) =>
              Redacted.isRedacted(value)
                ? Redacted.make(
                    JSON.stringify({
                      _tag: "Redacted",
                      value: Redacted.value(value),
                    }),
                  )
                : JSON.stringify(value),
            ),
          );
          return key;
        }),
      get: <T>(key: string) =>
        // Runtime ConfigProvider lookups call back into RuntimeContext.get.
        // Read the process env directly here to avoid re-entering that path.
        Effect.sync(() => {
          const value = process.env[key];
          if (value === undefined) {
            return undefined;
          }
          try {
            const parsed = JSON.parse(value);
            if (
              parsed !== null &&
              typeof parsed === "object" &&
              (parsed as { _tag?: unknown })._tag === "Redacted" &&
              "value" in (parsed as object)
            ) {
              return Redacted.make((parsed as { value: string }).value) as T;
            }
            return parsed as T;
          } catch {
            return value as T;
          }
        }),
      run,
      serve,
      exports: Effect.sync(() => ({
        default: Effect.forEach(
          [...runners],
          (effect) =>
            Effect.forever(
              effect.pipe(
                Effect.tapError((error) => Effect.logError(error)),
                Effect.ignore,
              ),
            ),
          { concurrency: "unbounded" },
        ),
      })),
    };
    return runtimeContext;
  },
});

const devProcesses = new Map<string, ChildProcessHandle>();

const stopTrackedDevProcess = Effect.fn(function* (processKey: string) {
  const existing = devProcesses.get(processKey);
  if (!existing) return;

  const running = yield* existing.isRunning;
  if (running) {
    // Keep the handle tracked when termination fails so a later reconcile or
    // destroy can retry instead of losing the only reference to the process.
    yield* existing.kill();
  }
  devProcesses.delete(processKey);
});

const projectConsistencySchedule = Schedule.max([
  Schedule.exponential(Duration.millis(500)),
  Schedule.recurs(6),
]);

// Only project/branch/app reads and the app create flow through the
// provisioning-consistency retries, so a NotFound there is exactly the
// post-create lag the schedule exists to absorb.
// The retried effects mix distilled's tagged operation errors with plain
// `Error` failures of their own (an unresolvable branch, a foreign App), so
// narrow before reading the tag.
const isAppProvisioningNotFound = (error: Error | { readonly _tag: string }) =>
  "_tag" in error && error._tag === "NotFound";

// Distilled emits the cursor-paginated list operations as plain ops, so
// callers walk `pagination` themselves (see `src/Neon/Project.ts`).
const listBranches = (projectId: string, gitName?: string) =>
  Effect.gen(function* () {
    const branches: GetProjectBranchesResponse["data"][number][] = [];
    let cursor: string | undefined;
    while (true) {
      const page = yield* getProjectBranches({
        projectId,
        limit: 100,
        ...(gitName === undefined ? {} : { gitName }),
        ...(cursor === undefined ? {} : { cursor }),
      });
      branches.push(...page.data);
      const nextCursor = page.pagination.nextCursor;
      if (!page.pagination.hasMore) break;
      if (nextCursor === null) {
        return yield* new PrismaPaginationError({
          message:
            "Invalid Prisma Management API pagination response from getProjectBranches: hasMore was true without a non-empty nextCursor",
        });
      }
      cursor = nextCursor;
    }
    return branches;
  });

const listApps = (projectId: string) =>
  Effect.gen(function* () {
    const apps: GetServicesResponse["data"][number][] = [];
    let cursor: string | undefined;
    while (true) {
      const page = yield* getServices(
        cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor },
      );
      apps.push(...page.data);
      const nextCursor = page.pagination.nextCursor;
      if (!page.pagination.hasMore) break;
      if (nextCursor === null) {
        return yield* new PrismaPaginationError({
          message:
            "Invalid Prisma Management API pagination response from getServices: hasMore was true without a non-empty nextCursor",
        });
      }
      cursor = nextCursor;
    }
    return apps;
  });

const desiredComputeBranchId = Effect.fn(function* (
  projectId: string,
  props: Pick<ComputeProps, "branchId" | "branchGitName">,
) {
  if (props.branchId !== undefined && !isPrismaDevId(props.branchId)) {
    return { resolved: true as const, id: props.branchId };
  }
  const branches = yield* listBranches(projectId, props.branchGitName);
  const matchingBranches =
    props.branchGitName === undefined ? branches.filter((branch) => branch.isDefault) : branches;
  if (matchingBranches.length > 1) {
    return yield* new ComputeConflict({
      message:
        props.branchGitName === undefined
          ? `Prisma returned multiple default branches for project '${projectId}'; refusing an ambiguous Compute App match.`
          : `Prisma returned multiple branches named '${props.branchGitName}' in project '${projectId}'; refusing an ambiguous Compute App match.`,
    });
  }
  const branch = matchingBranches[0];
  return branch ? { resolved: true as const, id: branch.id } : { resolved: false as const };
});

const createAppName = (id: string, appName: string | undefined) =>
  appName === undefined ? createPhysicalName({ id }) : Effect.succeed(appName);

const findApp = Effect.fn(function* (
  projectId: string,
  appName: string,
  props: Pick<ComputeProps, "branchId" | "branchGitName">,
) {
  const candidates = (yield* listApps(projectId)).filter((app) => app.name === appName);
  if (candidates.length === 0) return undefined;
  const branch = yield* desiredComputeBranchId(projectId, props);
  if (!branch.resolved) return undefined;
  const matches = candidates.filter((app) => app.branchId === branch.id);
  if (matches.length > 1) {
    return yield* new ComputeConflict({
      message: `Prisma returned multiple Apps named '${appName}' on branch '${branch.id}' in project '${projectId}'; refusing an ambiguous ownership match.`,
    });
  }
  return matches[0];
});

const createApp = (
  projectId: string,
  props: ComputeProps & { appName: string },
  branchId: string,
) =>
  createService({
    projectId,
    displayName: props.appName,
    branchId,
    ...(props.regionId === undefined ? {} : { regionId: props.regionId }),
  }).pipe(
    // A replayed create would make a second App; the retry policy cannot
    // see the request, so opt out explicitly.
    Retry.none,
    Effect.map((response) => response.data),
  );

const plainEnv = (
  env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
) =>
  Object.fromEntries(
    Object.entries(env).flatMap(([key, value]) =>
      value === undefined
        ? []
        : [[key, Redacted.isRedacted(value) ? Redacted.value(value) : value]],
    ),
  ) as Record<string, string | null>;

const persistedArtifactHashValue = (value: Redacted.Redacted<string> | string | undefined) =>
  Redacted.isRedacted(value) ? Redacted.value(value) : value;

const managedEnvKeys = (
  env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
) =>
  Object.entries(plainEnv(env))
    .flatMap(([key, value]) => (value === null ? [] : [key]))
    .sort();

const ENV_KEY_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
const ENV_VALUE_MAX_BYTES = 8 * 1024;
const EXPORT_IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;

const computeEnvValue = (value: string | Redacted.Redacted<string>) =>
  Redacted.isRedacted(value) ? Redacted.value(value) : value;

const validateComputeEnvironmentKey = (key: string) =>
  Effect.gen(function* () {
    if (key.length < 1 || key.length > 256 || !ENV_KEY_PATTERN.test(key)) {
      return yield* new ComputeInvalidProps({
        message: `Prisma environment variable key '${key}' must match POSIX env-var key shape: [A-Z_][A-Z0-9_]* and be at most 256 characters.`,
      });
    }
  });

const validateComputeEnvironmentWrite = (key: string, value: string | Redacted.Redacted<string>) =>
  Effect.gen(function* () {
    yield* validateComputeEnvironmentKey(key);
    const raw = computeEnvValue(value);
    if (raw.length === 0) {
      return yield* new ComputeInvalidProps({
        message: `Prisma environment variable '${key}' value must be non-empty.`,
      });
    }
    const byteLength = yield* Effect.sync(() => new TextEncoder().encode(raw).byteLength);
    if (byteLength > ENV_VALUE_MAX_BYTES) {
      return yield* new ComputeInvalidProps({
        message: `Prisma environment variable '${key}' value exceeds ${ENV_VALUE_MAX_BYTES} bytes.`,
      });
    }
  });

const validateComputeHealthCheck = (healthCheck: ComputeHealthCheck | undefined) =>
  Effect.gen(function* () {
    if (healthCheck === undefined) return;
    if (
      !healthCheck.path.startsWith("/") ||
      healthCheck.path.startsWith("//") ||
      healthCheck.path.includes("\\") ||
      /\s/.test(healthCheck.path)
    ) {
      return yield* new ComputeInvalidProps({
        message: "healthCheck.path must be an absolute application path beginning with one '/'.",
      });
    }
    if (healthCheck.statusCodes !== undefined && healthCheck.statusCodes.length === 0) {
      return yield* new ComputeInvalidProps({
        message: "healthCheck.statusCodes must contain at least one status.",
      });
    }
    for (const status of healthCheck.statusCodes ?? []) {
      if (!Number.isInteger(status) || status < 100 || status > 599) {
        return yield* new ComputeInvalidProps({
          message:
            "healthCheck.statusCodes must contain HTTP status integers from 100 through 599.",
        });
      }
    }
  });

const validateComputeProps = (props: ComputeProps) =>
  Effect.gen(function* () {
    yield* validateComputeHealthCheck(props.healthCheck);
    if (props.healthCheck !== undefined && props.verifyUrl === false) {
      return yield* new ComputeInvalidProps({
        message: "healthCheck cannot be combined with verifyUrl: false.",
      });
    }
    if (props.healthCheck !== undefined && props.start === false) {
      return yield* new ComputeInvalidProps({
        message: "healthCheck requires start to be enabled.",
      });
    }
    for (const [name, value] of [
      ["timeoutSeconds", props.timeoutSeconds],
      ["pollIntervalMs", props.pollIntervalMs],
      ["urlReadinessTimeoutSeconds", props.urlReadinessTimeoutSeconds],
    ] as const) {
      if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {
        return yield* new ComputeInvalidProps({
          message: `${name} must be a positive finite number.`,
        });
      }
    }
    for (const [name, value] of [
      ["port", props.port],
      ["dev.port", props.dev?.port],
    ] as const) {
      if (value !== undefined && (!Number.isInteger(value) || value < 1 || value > 65_535)) {
        return yield* new ComputeInvalidProps({
          message: `${name} must be an integer between 1 and 65535.`,
        });
      }
    }
    for (const [key, value] of Object.entries(props.env ?? {})) {
      if (value === undefined) continue;
      if (value === null) {
        yield* validateComputeEnvironmentKey(key);
      } else {
        yield* validateComputeEnvironmentWrite(key, value);
      }
    }
    if ((props.skipPromote ?? false) && (props.destroyOldDeployment ?? false)) {
      return yield* new ComputeInvalidProps({
        message:
          "destroyOldDeployment cannot be combined with skipPromote because the previous deployment stays active when promotion is skipped.",
      });
    }
    if (props.start === false && !(props.skipPromote ?? false)) {
      return yield* new ComputeInvalidProps({
        message:
          "start: false requires skipPromote: true because Prisma Compute promotion requires a running deployment.",
      });
    }
    if (props.branchId !== undefined && props.branchGitName !== undefined) {
      return yield* new ComputeInvalidProps({
        message: "branchId and branchGitName are mutually exclusive.",
      });
    }
    if (props.branchId === null || props.branchGitName === null) {
      return yield* new ComputeInvalidProps({
        message:
          "Prisma.Compute requires an attached branch because deployment creation resolves environment variables from the App branch. Omit branchGitName to use the project's default branch, or set branchId/branchGitName.",
      });
    }
    if ((props.skipCodeUpload ?? false) && props.artifactPath !== undefined) {
      return yield* new ComputeInvalidProps({
        message: "skipCodeUpload cannot be combined with artifactPath.",
      });
    }
    if ((props.skipCodeUpload ?? false) && props.build !== undefined) {
      return yield* new ComputeInvalidProps({
        message: "skipCodeUpload cannot be combined with build.",
      });
    }
    if (hasEffectNativeComputeInput(props)) {
      const handler = props.handler ?? "default";
      if (handler !== "default" && !EXPORT_IDENTIFIER_PATTERN.test(handler)) {
        return yield* new ComputeInvalidProps({
          message:
            "Effect-native Prisma Compute handler must be `default` or a valid JavaScript export identifier.",
        });
      }
      if (props.main === undefined) {
        return yield* new ComputeInvalidProps({
          message:
            "Effect-native Prisma Compute apps require `main`. Set `main: import.meta.filename`.",
        });
      }
      if (props.artifactPath !== undefined) {
        return yield* new ComputeInvalidProps({
          message: "Effect-native Prisma Compute apps cannot use artifactPath.",
        });
      }
      if (props.build !== undefined) {
        return yield* new ComputeInvalidProps({
          message: "Effect-native Prisma Compute apps cannot use build.",
        });
      }
      if (props.skipCodeUpload) {
        return yield* new ComputeInvalidProps({
          message: "Effect-native Prisma Compute apps cannot skip code upload.",
        });
      }
    }
  });

const processEnv = (
  env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
) =>
  Object.fromEntries(
    Object.entries(env).flatMap(([key, value]) =>
      value === undefined || value === null
        ? []
        : [[key, Redacted.isRedacted(value) ? Redacted.value(value) : value]],
    ),
  ) as Record<string, string>;

const isPrismaEdgeServiceNotFound = (status: number, body: string) =>
  status === 404 &&
  (body.includes("There is no service on this URL") ||
    body.includes("<title>Service not found</title>"));

const URL_READINESS_BODY_PREFIX_BYTES = 64 * 1024;

const readResponseBodyPrefix = (response: HttpClientResponse) =>
  Effect.gen(function* () {
    const chunks: Uint8Array[] = [];
    let bytes = 0;
    yield* Stream.runForEachWhile(response.stream, (chunk) =>
      Effect.sync(() => {
        const remaining = URL_READINESS_BODY_PREFIX_BYTES - bytes;
        if (remaining <= 0) return false;
        const kept = chunk.byteLength > remaining ? chunk.slice(0, remaining) : chunk;
        chunks.push(kept);
        bytes += kept.byteLength;
        return bytes < URL_READINESS_BODY_PREFIX_BYTES;
      }),
    );
    const prefix = new Uint8Array(bytes);
    let offset = 0;
    for (const chunk of chunks) {
      prefix.set(chunk, offset);
      offset += chunk.byteLength;
    }
    return new TextDecoder().decode(prefix);
  });

export const waitForDeploymentUrl = Effect.fn(function* (
  url: string | undefined,
  props: ComputeProps,
) {
  yield* validateComputeHealthCheck(props.healthCheck);
  if (props.healthCheck !== undefined && props.verifyUrl === false) {
    return yield* new ComputeInvalidProps({
      message: "healthCheck cannot be combined with verifyUrl: false.",
    });
  }
  if (props.verifyUrl === false) return;
  if (!url) {
    return yield* new ComputeUnexpectedResponse({
      message:
        props.healthCheck === undefined
          ? "Prisma Compute did not return a public URL for readiness verification."
          : "Prisma Compute did not return a public URL for the configured healthCheck.",
    });
  }
  const httpOption = yield* Effect.serviceOption(HttpClient.HttpClient);
  if (Option.isNone(httpOption)) {
    return props.healthCheck === undefined
      ? undefined
      : yield* new ComputeOperationFailed({
          message: "Prisma Compute healthCheck requires an HTTP client service.",
        });
  }

  const http = httpOption.value;
  const probeUrl =
    props.healthCheck === undefined ? url : new URL(props.healthCheck.path, url).toString();
  const acceptsStatus = (status: number) =>
    props.healthCheck === undefined ||
    (props.healthCheck.statusCodes === undefined
      ? status >= 200 && status <= 299
      : props.healthCheck.statusCodes.includes(status));
  const timeoutSeconds = props.urlReadinessTimeoutSeconds ?? 60;
  const intervalMs = props.pollIntervalMs ?? 1_000;
  if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
    return yield* new ComputeInvalidProps({
      message: "urlReadinessTimeoutSeconds must be a positive finite number.",
    });
  }
  if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
    return yield* new ComputeInvalidProps({
      message: "pollIntervalMs must be a positive finite number.",
    });
  }
  const timeoutMs = timeoutSeconds * 1_000;
  const startedAt = yield* Effect.sync(() => Date.now());
  let lastStatus: number | undefined;
  let lastBody = "";

  while (true) {
    const beforeRequest = yield* Effect.sync(() => Date.now());
    const remainingBeforeRequest = timeoutMs - (beforeRequest - startedAt);
    if (remainingBeforeRequest <= 0) {
      return yield* Effect.fail(deploymentUrlTimeoutError(probeUrl, lastStatus, lastBody));
    }
    const requestTimeoutMs = Math.min(5_000, remainingBeforeRequest);
    const response = yield* http.execute(HttpClientRequest.get(probeUrl)).pipe(
      Effect.provideService(FetchHttpClient.RequestInit, {
        redirect: "manual",
      }),
      Effect.timeoutOption(Duration.millis(requestTimeoutMs)),
      Effect.map(Option.getOrUndefined),
      Effect.orElseSucceed(() => undefined),
    );
    if (response) {
      lastStatus = response.status;
      // Without an application health check, any non-404 response proves that
      // edge routing is live. A configured health check must also match its
      // status contract. Do not consume non-404 bodies: application responses
      // may intentionally stream.
      if (response.status !== 404 && acceptsStatus(response.status)) {
        return;
      }
      const beforeBody = yield* Effect.sync(() => Date.now());
      const remainingBeforeBody = timeoutMs - (beforeBody - startedAt);
      if (remainingBeforeBody > 0) {
        const bodyPrefix = yield* readResponseBodyPrefix(response).pipe(
          Effect.timeoutOption(Duration.millis(Math.min(2_000, remainingBeforeBody))),
          Effect.orElseSucceed(() => Option.none<string>()),
        );
        if (Option.isSome(bodyPrefix)) {
          lastBody = bodyPrefix.value;
          if (
            !isPrismaEdgeServiceNotFound(response.status, lastBody) &&
            acceptsStatus(response.status)
          ) {
            return;
          }
        }
      }
    }

    const elapsed = yield* Effect.sync(() => Date.now() - startedAt);
    if (elapsed >= timeoutMs) {
      return yield* Effect.fail(deploymentUrlTimeoutError(probeUrl, lastStatus, lastBody));
    }

    yield* Effect.sleep(Duration.millis(Math.min(intervalMs, timeoutMs - elapsed)));
  }
});

const deploymentUrlTimeoutError = (url: string, lastStatus: number | undefined, lastBody: string) =>
  new Error(
    [
      `Timed out waiting for Prisma Compute URL '${url}' to become reachable.`,
      lastStatus ? `Last response: HTTP ${lastStatus}.` : "No HTTP response was received.",
      lastBody.includes("There is no service on this URL")
        ? "The Prisma edge returned: There is no service on this URL."
        : undefined,
    ]
      .filter((line): line is string => line !== undefined)
      .join(" "),
  );

const isAutoBuild = (build: ComputeProps["build"]): build is "auto" | ComputeAutoBuild =>
  build === "auto" ||
  (typeof build === "object" && build !== null && "type" in build && build.type === "auto");

const isStaticBuild = (build: ComputeProps["build"]): build is ComputeStaticBuild =>
  typeof build === "object" && build !== null && "type" in build && build.type === "static";

export class ComputePackageJsonError extends Data.TaggedError("ComputePackageJsonError")<{
  readonly message: string;
  readonly cause?: unknown;
}> {}

const readPackageMain = Effect.fn(function* (directory: string) {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const text = yield* fs.readFileString(path.join(directory, "package.json")).pipe(
    Effect.catchIf(
      (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound",
      () => Effect.undefined,
    ),
  );
  if (!text) return undefined;
  return yield* Effect.try({
    try: () => {
      const parsed = JSON.parse(text) as { main?: unknown };
      return typeof parsed.main === "string" ? parsed.main : undefined;
    },
    catch: (cause) =>
      new ComputePackageJsonError({
        message: `Failed to parse package.json in ${directory}: ${cause instanceof Error ? cause.message : String(cause)}`,
        cause,
      }),
  });
});

const writeBundleDirectory = Effect.fn(function* (bundle: Bundle.BundleOutput) {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  if (bundle.files.length === 0) {
    return yield* new ComputeOperationFailed({
      message: "Effect-native Compute bundler produced no output files.",
    });
  }
  const normalizedFiles = yield* Effect.forEach(bundle.files, (file) =>
    normalizeBundleFilePath(file.path).pipe(
      Effect.map((normalizedPath) => ({ file, normalizedPath })),
    ),
  );
  const seen = new Set<string>();
  for (const { normalizedPath } of normalizedFiles) {
    if (seen.has(normalizedPath)) {
      return yield* new ComputeOperationFailed({
        message: `Effect-native Compute bundler produced duplicate output path '${normalizedPath}'.`,
      });
    }
    seen.add(normalizedPath);
  }
  const directory = yield* fs.makeTempDirectory({
    prefix: "alchemy-prisma-compute-",
  });

  return yield* Effect.gen(function* () {
    for (const { file, normalizedPath } of normalizedFiles) {
      const target = path.join(directory, normalizedPath);
      yield* fs.makeDirectory(path.dirname(target), { recursive: true });
      if (typeof file.content === "string") {
        yield* fs.writeFileString(target, file.content);
      } else {
        yield* fs.writeFile(target, file.content);
      }
    }

    return {
      directory,
      entrypoint: normalizedFiles[0].normalizedPath,
      cleanup: fs.remove(directory, { recursive: true }).pipe(Effect.ignore),
    };
  }).pipe(Effect.onError(() => fs.remove(directory, { recursive: true }).pipe(Effect.ignore)));
});

const bundleEffectCompute = Effect.fn(function* (props: ComputeProps) {
  if (!props.main) {
    return yield* new ComputeInvalidProps({
      message:
        "Effect-native Prisma Compute apps require `main`. Set `main: import.meta.filename`.",
    });
  }

  const fs = yield* FileSystem.FileSystem;
  const stack = yield* Effect.serviceOption(Stack).pipe(
    Effect.map(
      Option.getOrElse(() => ({
        name: "alchemy",
        stage: "dev",
        bindings: {},
        resources: {},
      })),
    ),
  );
  const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
  const realMain = yield* fs.realPath(props.main);
  const cwd = yield* findCwdForBundle(realMain);
  const handler = props.handler ?? "default";
  const defaultPort = props.port ?? 8080;

  const importEntrypoint =
    handler === "default" ? "import entrypoint" : `import { ${handler} as entrypoint }`;

  const bundle = yield* Bundle.build(
    {
      ...props.bundle?.input,
      input: realMain,
      cwd,
      platform: "node",
      // Prisma Compute runs the bundle on bun.
      resolve: {
        conditionNames: [...Bundle.BUN_CONDITION_NAMES],
        ...props.bundle?.input?.resolve,
      },
      plugins: [
        props.bundle?.input?.plugins,
        virtualEntryPlugin(
          (importPath) => `
import { bootstrap } from "@alchemy.run/prisma/Bootstrap";
${importEntrypoint} from ${JSON.stringify(importPath)};

await bootstrap(entrypoint, ${JSON.stringify({
            port: defaultPort,
            stack: { name: stack.name, stage: stack.stage },
          })});
`,
        ),
      ],
      checks: {
        unresolvedImport: false,
        ineffectiveDynamicImport: false,
      },
    },
    {
      ...props.bundle?.output,
      format: "esm",
      sourcemap: props.bundle?.output?.sourcemap ?? "hidden",
      minify: props.bundle?.output?.minify ?? true,
      entryFileNames: "index.js",
    },
    props.bundle?.extra,
  );

  const artifact = yield* writeBundleDirectory(bundle);
  const file = yield* createComputeArchive({
    directory: artifact.directory,
    entrypoint: artifact.entrypoint,
    ignore: props.archiveIgnore,
    output: "file",
  }).pipe(Effect.ensuring(artifact.cleanup));

  return {
    file,
    bundleHash: bundle.hash,
  };
});

const resolveArtifact = Effect.fn(function* (props: ComputeProps) {
  const env = plainEnv(props.env);
  const envClass = props.envClass ?? "production";
  const defaultPort = props.port ?? 8080;
  if (isEffectNativeCompute(props)) {
    if (props.artifactPath !== undefined) {
      return yield* new ComputeInvalidProps({
        message: "Effect-native Prisma Compute apps cannot use artifactPath.",
      });
    }
    if (props.skipCodeUpload) {
      return yield* new ComputeInvalidProps({
        message: "Effect-native Prisma Compute apps cannot skip code upload.",
      });
    }
    if (props.build !== undefined) {
      return yield* new ComputeInvalidProps({
        message: "Effect-native Prisma Compute apps cannot use build.",
      });
    }
    const artifact = yield* bundleEffectCompute(props);
    return {
      file: artifact.file,
      hash: yield* sha256Object({
        bundle: artifact.bundleHash,
        env,
        envClass,
        port: defaultPort,
      }),
      port: defaultPort,
    };
  }

  if (props.skipCodeUpload) {
    return {
      file: undefined,
      hash: yield* sha256Object({
        skipCodeUpload: true,
        env,
        envClass,
        port: defaultPort,
      }),
      port: defaultPort,
    };
  }

  if (props.artifactPath !== undefined) {
    const file = yield* readUploadArtifact({
      artifactPath: props.artifactPath,
      output: "file",
    });
    return {
      file: file!,
      hash: yield* sha256Object({
        artifact: file!.sha256,
        env,
        envClass,
        port: defaultPort,
      }),
      port: defaultPort,
    };
  }

  const path = yield* Path.Path;
  const appPath = path.resolve(props.path ?? ".");
  let directory = appPath;
  let entrypoint = props.entrypoint;
  let port = defaultPort;

  if (isAutoBuild(props.build)) {
    const auto = props.build === "auto" ? undefined : props.build;
    const artifact = yield* runComputeAutoBuild({
      appPath,
      entrypoint,
      framework: auto?.framework,
      env: auto?.env,
      outputLimitBytes: auto?.outputLimitBytes,
      timeoutSeconds: auto?.timeoutSeconds,
    });
    const file = yield* createComputeArchive({
      directory: artifact.directory,
      entrypoint: artifact.entrypoint,
      ignore: props.archiveIgnore,
      ignorePrefix: artifact.archiveIgnorePrefix,
      requiredFiles: artifact.requiredFiles,
      output: "file",
    }).pipe(Effect.ensuring(artifact.cleanup));
    port = props.port ?? artifact.defaultPort ?? 8080;
    return {
      file,
      hash: yield* sha256Object({
        artifact: file.sha256,
        env,
        envClass,
        port,
      }),
      port,
    };
  }

  if (isStaticBuild(props.build)) {
    const artifact = yield* runComputeStaticBuild({
      appPath,
      command: props.build.command,
      cwd: props.build.cwd,
      outdir: props.build.outdir,
      indexPage: props.build.indexPage,
      spa: props.build.spa,
      env: props.build.env,
      outputLimitBytes: props.build.outputLimitBytes,
      timeoutSeconds: props.build.timeoutSeconds,
    });
    const file = yield* createComputeArchive({
      directory: artifact.directory,
      entrypoint: artifact.entrypoint,
      ignore: props.archiveIgnore,
      ignorePrefix: artifact.archiveIgnorePrefix,
      requiredFiles: artifact.requiredFiles,
      output: "file",
    }).pipe(Effect.ensuring(artifact.cleanup));
    port = props.port ?? artifact.defaultPort ?? 8080;
    return {
      file,
      hash: yield* sha256Object({
        artifact: file.sha256,
        env,
        envClass,
        port,
      }),
      port,
    };
  }

  if (props.build) {
    const cwd = props.build.cwd ? path.resolve(props.build.cwd) : appPath;
    yield* runBuildCommand({
      command: props.build.command,
      cwd,
      env: processEnv(props.build.env),
      outputLimitBytes: props.build.outputLimitBytes,
      timeoutSeconds: props.build.timeoutSeconds,
    });
    directory = path.resolve(cwd, props.build.outdir);
    entrypoint = props.build.entrypoint ?? entrypoint;
  }

  entrypoint ??= yield* readPackageMain(directory);
  if (!entrypoint) {
    return yield* new ComputeInvalidProps({
      message:
        "Prisma Compute app entrypoint is required. Set `entrypoint` or package.json `main`.",
    });
  }

  const normalizedEntrypoint = yield* normalizeEntrypoint(entrypoint);
  const file = yield* createComputeArchive({
    directory,
    entrypoint: normalizedEntrypoint,
    ignore: props.archiveIgnore,
    output: "file",
  });
  return {
    file,
    hash: yield* sha256Object({
      artifact: file.sha256,
      env,
      envClass,
      port,
    }),
    port,
  };
});

const findExistingApp = Effect.fn(function* (output: Compute["Attributes"] | undefined) {
  const appId = output?.appId && !isPrismaDevId(output.appId) ? output.appId : undefined;
  return appId
    ? yield* getService({ serviceId: appId }).pipe(
        Effect.map((response) => response.data),
        Effect.catchTag("NotFound", () => Effect.undefined),
      )
    : undefined;
});

const ensureApp = Effect.fn(function* (
  projectId: string,
  props: ComputeProps & { appName: string },
  output: Compute["Attributes"] | undefined,
  observedApp?: ObservedApp,
) {
  let app: ObservedApp | undefined = observedApp ?? (yield* findExistingApp(output));
  const branch = yield* desiredComputeBranchId(projectId, props);
  if (!branch.resolved) {
    return yield* new ComputeOperationFailed({
      message:
        props.branchGitName === undefined
          ? `Prisma project '${projectId}' has no default branch to attach Compute App '${props.appName}'. Create or promote a default branch, or specify branchId/branchGitName.`
          : `Prisma project '${projectId}' has no branch named '${props.branchGitName}' to attach Compute App '${props.appName}'.`,
    });
  }

  let createdApp = false;
  if (!app) {
    const result = yield* createApp(projectId, props, branch.id).pipe(
      Effect.map((app) => ({ app, created: true })),
      Effect.catchTag("Conflict", (conflict) =>
        findApp(projectId, props.appName, props).pipe(
          Effect.flatMap((app) =>
            app && output?.appId !== undefined && app.id === output.appId
              ? Effect.succeed({ app, created: false })
              : Effect.fail(
                  new ComputeConflict({
                    message: `Prisma App '${props.appName}' already exists on the requested branch but is not owned by this Compute resource. Import it with explicit adoption or choose a different App name.`,
                    cause: conflict,
                  }),
                ),
          ),
        ),
      ),
    );
    app = result.app;
    createdApp = result.created;
  }

  yield* ensureAppImmutableIdentity(
    app,
    projectId,
    props.regionId ?? output?.regionId ?? app.region.id,
  );
  if (app.name !== props.appName || app.branchId !== branch.id) {
    app = yield* updateService({
      serviceId: app.id,
      displayName: props.appName,
      branchId: branch.id,
    }).pipe(Effect.map((response) => response.data));
  }

  return { app, created: createdApp };
});

const ensureSkipCodeUploadCanFork = (props: ComputeProps, app: ObservedApp | undefined) =>
  Effect.gen(function* () {
    if (!(props.skipCodeUpload ?? false)) return;
    if (app?.latestDeploymentId) return;
    return yield* new ComputeInvalidProps({
      message:
        "skipCodeUpload requires an existing Prisma deployment to fork from. Upload and start a deployment first, or remove skipCodeUpload.",
    });
  });

const findEnvironmentVariable = (
  projectId: string,
  cls: "production" | "preview",
  key: string,
  branchId?: string | null,
) =>
  Effect.gen(function* () {
    // Distilled emits the cursor-paginated list operations as plain ops, so
    // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
    const variables: GetEnvironmentVariablesResponse["data"][number][] = [];
    let cursor: string | undefined;
    while (true) {
      const page = yield* getEnvironmentVariables({
        projectId,
        class: cls,
        key,
        limit: 100,
        ...(branchId ? { branchId } : {}),
        ...(cursor === undefined ? {} : { cursor }),
      });
      variables.push(...page.data);
      const nextCursor = page.pagination.nextCursor;
      if (!page.pagination.hasMore) break;
      if (nextCursor === null) {
        return yield* new PrismaPaginationError({
          message:
            "Invalid Prisma Management API pagination response from getEnvironmentVariables: hasMore was true without a non-empty nextCursor",
        });
      }
      cursor = nextCursor;
    }
    return variables.find((variable) => variable.branchId === (branchId ?? null));
  });

const systemManagedEnvironmentVariableError = (key: string) =>
  new Error(
    `Prisma environment variable '${key}' is managed by Prisma and cannot be managed by Alchemy.`,
  );

const ensureUserManagedEnvironmentVariable = (variable: ObservedEnvironmentVariable) =>
  Effect.gen(function* () {
    if (variable.isManagedBySystem) {
      return yield* Effect.fail(systemManagedEnvironmentVariableError(variable.key));
    }
  });

const environmentVariableOwnershipError = (key: string, variableId: string) =>
  new Error(
    `Prisma environment variable '${key}' (${variableId}) already exists in this branch/class scope but is not owned by this Compute resource. It may be foreign or left by an interrupted prior Compute deploy; the Management API exposes no ownership marker or plaintext value that would make takeover safe. Use one standalone Prisma.EnvironmentVariable resource as the independently manageable owner, choose a different key, explicitly adopt that resource, or remove the existing variable before deploying.`,
  );

interface ComputeEnvironmentScope {
  class: "production" | "preview";
  branchId: string | null;
}

const environmentScope = (
  cls: "production" | "preview",
  branchId?: string | null,
): ComputeEnvironmentScope => ({
  class: cls,
  branchId: branchId ?? null,
});

const sameEnvironmentScope = (left: ComputeEnvironmentScope, right: ComputeEnvironmentScope) =>
  left.class === right.class && left.branchId === right.branchId;

const resolveComputeEnvironmentScope = Effect.fn(function* (app: ObservedApp, props: ComputeProps) {
  if (!app.branchId) {
    return yield* new ComputeConflict({
      message:
        "Prisma.Compute requires an attached branch because deployment creation resolves environment variables from the App branch.",
    });
  }

  const branch = yield* getBranch({
    branchId: app.branchId,
  }).pipe(Effect.map((response) => response.data));
  const inferredClass = branch.role;
  if (props.envClass !== undefined && props.envClass !== inferredClass) {
    return yield* new ComputeInvalidProps({
      message: `Prisma.Compute envClass '${props.envClass}' does not match attached branch role '${inferredClass}'. Omit envClass to let Alchemy infer the correct environment variable scope.`,
    });
  }

  return environmentScope(inferredClass, inferredClass === "preview" ? app.branchId : null);
});

interface ComputeEnvironmentPlan {
  key: string;
  value: string | null;
  variable: ObservedEnvironmentVariable | undefined;
}

const rollbackCreatedEnvironmentVariables = Effect.fn(function* (
  createdIds: ReadonlyArray<{ key: string; id: string }>,
  originalError: unknown,
) {
  if (createdIds.length === 0) {
    return yield* Effect.fail(originalError);
  }
  const cleanupErrors: unknown[] = [];
  for (const created of [...createdIds].reverse()) {
    const result = yield* Effect.result(
      deleteEnvironmentVariable({ envVarId: created.id }).pipe(
        Effect.catchTag("NotFound", () => Effect.void),
      ),
    );
    if (Result.isFailure(result)) {
      cleanupErrors.push(result.failure);
    }
  }
  if (cleanupErrors.length > 0) {
    return yield* Effect.fail(
      new AggregateError(
        [originalError, ...cleanupErrors],
        `Failed to roll back newly created Prisma environment variables after reconcile failed. Manual cleanup: ${createdIds.map(({ id }) => `DELETE /v1/environment-variables/${id}`).join(", ")}.`,
      ),
    );
  }
  return yield* Effect.fail(originalError);
});

const syncComputeEnvironmentInternal = Effect.fn(function* (
  projectId: string,
  cls: "production" | "preview",
  env: Record<string, string | Redacted.Redacted<string> | null | undefined> = {},
  branchId?: string | null,
  ownedIds: Readonly<Record<string, string>> = {},
) {
  const synced: string[] = [];
  const deleted: string[] = [];
  const nextOwnedIds: Record<string, string> = {};
  const createdIds: Array<{ key: string; id: string }> = [];
  const plans: ComputeEnvironmentPlan[] = [];

  // Observe and validate the entire scope before the first write. In
  // particular, a foreign/system-owned key discovered late in the input must
  // not leave earlier keys partially created.
  for (const [key, value] of Object.entries(plainEnv(env))) {
    if (value === null) {
      yield* validateComputeEnvironmentKey(key);
    } else {
      yield* validateComputeEnvironmentWrite(key, value);
    }
    const variable = yield* findEnvironmentVariable(projectId, cls, key, branchId);
    if (variable) {
      yield* ensureUserManagedEnvironmentVariable(variable);
      if (ownedIds[key] !== variable.id) {
        return yield* Effect.fail(environmentVariableOwnershipError(key, variable.id));
      }
    }
    plans.push({ key, value, variable });
  }

  const apply = Effect.gen(function* () {
    for (const { key, value, variable } of plans) {
      if (value === null) continue;
      if (variable) {
        yield* updateEnvironmentVariable({
          envVarId: variable.id,
          value,
        });
        nextOwnedIds[key] = variable.id;
      } else {
        const created = yield* createEnvironmentVariable({
          projectId,
          ...(branchId ? { branchId } : {}),
          class: cls,
          key,
          value,
        }).pipe(
          // A replayed create would make a second variable; the retry policy
          // cannot see the request, so opt out explicitly.