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

main
ts 244 lines 9.46 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import { AuthProviders, AuthProvidersLive } from "alchemy/Auth/AuthProvider";
3 import { CredentialsStoreLive } from "alchemy/Auth/Credentials";
4 import { ProfileStore, ProfileStoreLive } from "alchemy/Auth/Profile";
5 import * as Command from "alchemy/Command";
6 import * as Provider from "alchemy/Provider";
7 import { PlatformServices } from "alchemy/Util/PlatformServices";
8 import { proxyChain } from "alchemy/Util/proxy-chain";
9 import { Server, ServerProvider } from "alchemy/Website/Server";
10 import * as Context from "effect/Context";
11 import * as Effect from "effect/Effect";
12 import * as FetchHttpClient from "effect/http/FetchHttpClient";
13 import * as Layer from "effect/Layer";
14 import { App, AppProvider } from "./App.ts";
15 import { PrismaAuth } from "./AuthProvider.ts";
16 import { Branch, BranchProvider } from "./Branch.ts";
17 import { Bucket, BucketProvider } from "./Bucket.ts";
18 import { BucketAccessKey, BucketAccessKeyProvider } from "./BucketAccessKey.ts";
19 import { PrismaClient, PrismaClientLive, type PrismaManagementClient } from "./Client.ts";
20 import { Compute, ComputeProvider } from "./Compute.ts";
21 import { Connection, ConnectionProvider } from "./Connection.ts";
22 import { CustomDomain, CustomDomainProvider } from "./CustomDomain.ts";
23 import { Database, DatabaseProvider } from "./Database.ts";
24 import { Deployment, DeploymentProvider } from "./Deployment.ts";
25 import { EnvironmentVariable, EnvironmentVariableProvider } from "./EnvironmentVariable.ts";
26 import * as Credentials from "./internal/Credentials.ts";
27 import { PrismaHttpClientLive, PrismaUploadClientLive } from "./internal/HttpClient.ts";
28 import { Contract, ContractProvider } from "./ORM/Contract.ts";
29 import { Migrate, MigrateProvider } from "./ORM/Migrate.ts";
30 import { fromProfile } from "./PrismaEnvironment.ts";
31 import { Project, ProjectProvider } from "./Project.ts";
32 import { SourceRepository, SourceRepositoryProvider } from "./SourceRepository.ts";
33 import { WebsiteArtifact, WebsiteArtifactProvider } from "./Website/Artifact.ts";
34
35 export { PrismaEnvironment } from "./PrismaEnvironment.ts";
36
37 export class Providers extends Provider.ProviderCollection<Providers>()("Prisma") {}
38
39 export type ProviderRequirements = Layer.Services<ReturnType<typeof providers>>;
40
41 /**
42 * Standalone operation helpers own a private auth registry because they run
43 * outside a Stack. Credential resolution stays eager here so constructing
44 * `managementApi()` preserves its existing fail-fast behavior — which also
45 * lets the distilled `Credentials` service read the already-resolved
46 * {@link PrismaEnvironment} rather than building its own.
47 */
48 const standaloneManagementApiLayer = () =>
49 PrismaClientLive.pipe(
50 Layer.provideMerge(
51 Layer.mergeAll(Credentials.fromEnvironment(), Layer.succeed(Retry.Retry, Retry.makeDefault)),
52 ),
53 Layer.provideMerge(fromProfile()),
54 Layer.provideMerge(PrismaAuth),
55 Layer.provideMerge(
56 Layer.mergeAll(
57 AuthProvidersLive,
58 // The Prisma-scoped upload client (node transport) rides the
59 // providers' output so artifact uploads can reach it at op time.
60 PrismaUploadClientLive,
61 Layer.provide(ProfileStoreLive, PlatformServices),
62 Layer.provide(CredentialsStoreLive, PlatformServices),
63 ),
64 ),
65 // Provide (NOT provideMerge) the node transport privately: it must serve
66 // only the Prisma management client. Exposing it from `providers()` would
67 // override the ambient HttpClient for every other provider in the stack —
68 // Cloudflare Worker script uploads then go out via node:http, which
69 // streams multipart bodies as `Transfer-Encoding: chunked`, and
70 // api.cloudflare.com never answers chunked uploads.
71 Layer.provide(PrismaHttpClientLive),
72 );
73
74 /**
75 * Stack provider discovery must register auth without requiring credentials.
76 * The management client is resolved on its first API operation, after
77 * `alchemy profile edit` has had a chance to configure the registered Prisma
78 * auth provider. The nested client layer shares the provider layer's lifetime.
79 */
80 const stackManagementApiLayer = () =>
81 Layer.effect(
82 PrismaClient,
83 Effect.gen(function* () {
84 const scope = yield* Effect.scope;
85 const authProviders = yield* AuthProviders;
86 const profileStore = yield* ProfileStore;
87 const client = Layer.buildWithScope(
88 PrismaClientLive.pipe(
89 Layer.provideMerge(
90 fromProfile().pipe(
91 Layer.provide(
92 Layer.mergeAll(
93 Layer.succeed(AuthProviders, authProviders),
94 Layer.succeed(ProfileStore, profileStore),
95 ),
96 ),
97 ),
98 ),
99 Layer.provide(PrismaHttpClientLive),
100 ),
101 scope,
102 ).pipe(Effect.map((context) => Context.get(context, PrismaClient)));
103 const cached = yield* Effect.cached(client);
104 return proxyChain(cached) as PrismaManagementClient;
105 }),
106 ).pipe(
107 Layer.provideMerge(
108 Layer.mergeAll(Credentials.fromAuthProvider(), Layer.succeed(Retry.Retry, Retry.makeDefault)),
109 ),
110 Layer.provideMerge(PrismaAuth),
111 Layer.provideMerge(
112 Layer.mergeAll(
113 // The Prisma-scoped upload client (node transport) rides the
114 // providers' output so artifact uploads can reach it at op time.
115 PrismaUploadClientLive,
116 Layer.provide(ProfileStoreLive, PlatformServices),
117 Layer.provide(CredentialsStoreLive, PlatformServices),
118 ),
119 ),
120 );
121
122 /**
123 * Build a layer for Prisma Management API operation helpers.
124 *
125 * Use this when calling helpers like `Prisma.listProjects()` outside an
126 * Alchemy stack or test. Inside a stack (or a `test.provider` body) deployed
127 * with `Prisma.providers()`, the management client is already in context, so
128 * operation helpers work without providing this layer.
129 *
130 * @example
131 * ```typescript
132 * const projects = yield* Prisma.listProjects().pipe(
133 * Effect.provide(Prisma.managementApi()),
134 * );
135 * ```
136 *
137 * This layer covers the operation helpers. The lifecycle helpers
138 * (`destroyApp`, `destroyDeployment`, `destroyProjectApps`,
139 * `waitForDeploymentStatus`, `syncComputeEnvironment`) also need an
140 * `HttpClient` from the caller, because the Prisma-scoped node transport is
141 * `Layer.provide`d privately here — see the comment on the private provide
142 * above for why it must not reach the surrounding stack. Add one, e.g.:
143 *
144 * ```typescript
145 * yield* Prisma.destroyApp(appId).pipe(
146 * Effect.provide(Prisma.managementApi()),
147 * Effect.provide(FetchHttpClient.layer),
148 * );
149 * ```
150 */
151 export const managementApi = () =>
152 standaloneManagementApiLayer().pipe(Layer.provide(FetchHttpClient.layer), Layer.orDie);
153
154 /**
155 * Build a layer that registers all Prisma resource providers, the Prisma
156 * auth provider, resolved credentials, and an HTTP client.
157 *
158 * Every resource is registered with {@link ../Local/ProviderLayer.ts
159 * ProviderLayer.dual}: a **live** implementation backed by the Prisma
160 * Management API and a **local** implementation used by `alchemy dev`
161 * (fabricated `dev:` identifiers; `Prisma.Database` boots a local
162 * `@prisma/dev` server). The engine picks the variant per run and per
163 * resource:
164 *
165 * - `alchemy deploy` resolves the live variant; `alchemy dev` resolves the
166 * local variant automatically.
167 * - Wrap a resource in `Alchemy.remote(...)` to keep it live even during
168 * `alchemy dev`.
169 * - To replace implementations wholesale, construct your own layer instead
170 * of this one: register the {@link Providers} collection and provide your
171 * own per-resource provider layers (compose the exported per-resource
172 * factories like {@link ProjectProvider} with your replacements, and
173 * {@link managementApi} when live operations are needed).
174 *
175 * @example
176 * ```typescript
177 * import * as Alchemy from "alchemy";
178 * import * as Prisma from "@alchemy.run/prisma";
179 * import * as Effect from "effect/Effect";
180 *
181 * export default Alchemy.Stack(
182 * "MyStack",
183 * { providers: Prisma.providers(), state: Alchemy.localState() },
184 * Effect.gen(function* () {
185 * const project = yield* Prisma.Project("app", {
186 * name: "app",
187 * region: "us-east-1",
188 * });
189 * return { projectId: project.projectId };
190 * }),
191 * );
192 * ```
193 */
194 export const providers = () =>
195 Layer.effect(
196 Providers,
197 Provider.collection([
198 Project,
199 Database,
200 Connection,
201 Branch,
202 Bucket,
203 BucketAccessKey,
204 Compute,
205 App,
206 Deployment,
207 CustomDomain,
208 EnvironmentVariable,
209 SourceRepository,
210 Contract,
211 Migrate,
212 Server,
213 WebsiteArtifact,
214 ]),
215 ).pipe(
216 Layer.provideMerge(
217 Layer.mergeAll(
218 ProjectProvider(),
219 DatabaseProvider(),
220 ConnectionProvider(),
221 BranchProvider(),
222 BucketProvider(),
223 BucketAccessKeyProvider(),
224 ComputeProvider(),
225 AppProvider(),
226 DeploymentProvider(),
227 CustomDomainProvider(),
228 EnvironmentVariableProvider(),
229 SourceRepositoryProvider(),
230 ContractProvider(),
231 MigrateProvider(),
232 ServerProvider(),
233 WebsiteArtifactProvider(),
234 ),
235 ),
236 // The management client layer is shared by every live variant. It is
237 // built in both modes but stays inert until the first API operation:
238 // auth registers without resolving credentials, so `alchemy dev` never
239 // needs a Prisma token.
240 Layer.provideMerge(stackManagementApiLayer()),
241 Layer.provideMerge(Command.providers()),
242 Layer.provide(FetchHttpClient.layer),
243 Layer.orDie,
244 );