@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,151 lines 43.1 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Data from "effect/Data";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as HttpClient from "effect/http/HttpClient";
6 import * as HttpClientError from "effect/http/HttpClientError";
7 import * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import * as Layer from "effect/Layer";
9 import * as Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { type ObservedConnection, secretValue } from "./internal/Observed.ts";
13 import { PrismaEnvironment } from "./PrismaEnvironment.ts";
14 import type {
15 App,
16 AccelerateRegion,
17 AppCreateInput,
18 AppDeploymentTarget,
19 AppUpdateInput,
20 BackupListResponse,
21 Branch,
22 BranchCreateInput,
23 BranchUpdateInput,
24 Bucket,
25 BucketCreateInput,
26 BucketKey,
27 BucketKeyCreateInput,
28 BucketKeyWithSecret,
29 BuildLogsQuery,
30 BuildLogsRequest,
31 ConnectionCreateInput,
32 CurrentPrincipal,
33 CustomDomain,
34 CustomDomainCreateInput,
35 CustomDomainCreateResult,
36 DataResponse,
37 Database,
38 DatabaseConnection,
39 DatabaseConnectionCreateInput,
40 DatabaseConnectionWithOptionalSecrets,
41 DatabaseConnectionWithSecrets,
42 DatabaseCreateInput,
43 DatabaseUpdateInput,
44 DatabaseUsage,
45 Deployment,
46 DeploymentCreateInput,
47 DeploymentCreateResult,
48 DeploymentListItem,
49 DeploymentLogsQuery,
50 DeploymentLogsRequest,
51 EnvironmentVariable,
52 EnvironmentVariableCreateInput,
53 EnvironmentVariableUpdateInput,
54 Integration,
55 ListResponse,
56 PrismaBranchIdFilter,
57 PrismaSecretConnection,
58 Project,
59 ProjectCreateInput,
60 ProjectDatabaseCreateInput,
61 ProjectTransferInput,
62 ProjectUpdateInput,
63 PostgresRegion,
64 PromoteAppResult,
65 RollbackAppResult,
66 Region,
67 RestoreDatabaseInput,
68 RestoredDatabase,
69 ScmInstallIntent,
70 ScmInstallIntentCreateInput,
71 ScmInstallation,
72 ScmRepository,
73 SourceRepository,
74 SourceRepositoryCreateInput,
75 StartDeploymentResult,
76 Workspace,
77 } from "./Types.ts";
78
79 type Method = "GET" | "POST" | "PATCH" | "DELETE";
80
81 export class PrismaApiError extends Data.TaggedError("PrismaApiError")<{
82 method: Method;
83 path: string;
84 status: number;
85 message: string;
86 /** Raw response bodies may contain credentials and are always redacted. */
87 body?: Redacted.Redacted<string>;
88 }> {}
89
90 export class PrismaApiDecodeError extends Data.TaggedError("PrismaApiDecodeError")<{
91 method: Method;
92 path: string;
93 /** Byte length is retained for diagnostics without retaining response data. */
94 bodyLength: number;
95 message: string;
96 }> {}
97
98 interface RequestOptions {
99 query?: object;
100 body?: unknown;
101 headers?: Record<string, string>;
102 timeout?: Duration.Input;
103 onSuccessfulBodyLength?: (bodyLength: number) => Effect.Effect<void, PrismaApiDecodeError>;
104 }
105
106 export interface PrismaManagementClient {
107 listWorkspaces(
108 query?: PaginationQuery,
109 ): Effect.Effect<Workspace[], PrismaApiError | PrismaApiDecodeError>;
110 getWorkspace(id: string): Effect.Effect<Workspace, PrismaApiError | PrismaApiDecodeError>;
111 getCurrentPrincipal(): Effect.Effect<CurrentPrincipal, PrismaApiError | PrismaApiDecodeError>;
112 listRegions(
113 query?: RegionListQuery,
114 ): Effect.Effect<Region[], PrismaApiError | PrismaApiDecodeError>;
115 listPostgresRegions(): Effect.Effect<PostgresRegion[], PrismaApiError | PrismaApiDecodeError>;
116 listAccelerateRegions(): Effect.Effect<AccelerateRegion[], PrismaApiError | PrismaApiDecodeError>;
117 listProjects(
118 query?: PaginationQuery,
119 ): Effect.Effect<Project[], PrismaApiError | PrismaApiDecodeError>;
120 getProject(id: string): Effect.Effect<Project, PrismaApiError | PrismaApiDecodeError>;
121 createProject(
122 input: ProjectCreateInput,
123 ): Effect.Effect<ProjectCreateResult, PrismaApiError | PrismaApiDecodeError>;
124 updateProject(
125 id: string,
126 input: ProjectUpdateInput,
127 ): Effect.Effect<Project, PrismaApiError | PrismaApiDecodeError>;
128 deleteProject(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
129 transferProject(
130 id: string,
131 input: ProjectTransferInput,
132 ): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
133 listDatabases(
134 query?: DatabaseListQuery,
135 ): Effect.Effect<Database[], PrismaApiError | PrismaApiDecodeError>;
136 listProjectDatabases(
137 projectId: string,
138 query?: PaginationQuery,
139 ): Effect.Effect<Database[], PrismaApiError | PrismaApiDecodeError>;
140 getDatabase(id: string): Effect.Effect<Database, PrismaApiError | PrismaApiDecodeError>;
141 createDatabase(
142 input: DatabaseCreateInput,
143 ): Effect.Effect<DatabaseCreateResult, PrismaApiError | PrismaApiDecodeError>;
144 createProjectDatabase(
145 projectId: string,
146 input: ProjectDatabaseCreateInput,
147 ): Effect.Effect<ProjectDatabaseCreateResult, PrismaApiError | PrismaApiDecodeError>;
148 updateDatabase(
149 id: string,
150 input: DatabaseUpdateInput,
151 ): Effect.Effect<Database, PrismaApiError | PrismaApiDecodeError>;
152 deleteDatabase(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
153 listBackups(
154 databaseId: string,
155 query?: BackupListQuery,
156 ): Effect.Effect<BackupListResponse, PrismaApiError | PrismaApiDecodeError>;
157 restoreDatabase(
158 targetDatabaseId: string,
159 input: RestoreDatabaseInput,
160 ): Effect.Effect<RestoredDatabase, PrismaApiError | PrismaApiDecodeError>;
161 getDatabaseUsage(
162 databaseId: string,
163 query?: DatabaseUsageQuery,
164 ): Effect.Effect<DatabaseUsage, PrismaApiError | PrismaApiDecodeError>;
165 listConnections(
166 query?: ConnectionListQuery,
167 ): Effect.Effect<DatabaseConnection[], PrismaApiError | PrismaApiDecodeError>;
168 listDatabaseConnections(
169 databaseId: string,
170 query?: PaginationQuery,
171 ): Effect.Effect<DatabaseConnection[], PrismaApiError | PrismaApiDecodeError>;
172 getConnection(
173 id: string,
174 ): Effect.Effect<DatabaseConnection, PrismaApiError | PrismaApiDecodeError>;
175 createConnection(
176 input: ConnectionCreateInput,
177 ): Effect.Effect<DatabaseConnectionWithSecrets, PrismaApiError | PrismaApiDecodeError>;
178 createDatabaseConnection(
179 databaseId: string,
180 input: DatabaseConnectionCreateInput,
181 ): Effect.Effect<DatabaseConnectionWithSecrets, PrismaApiError | PrismaApiDecodeError>;
182 deleteConnection(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
183 rotateConnection(
184 id: string,
185 ): Effect.Effect<DatabaseConnectionWithSecrets, PrismaApiError | PrismaApiDecodeError>;
186 listBranches(
187 projectId: string,
188 query?: BranchListQuery,
189 ): Effect.Effect<Branch[], PrismaApiError | PrismaApiDecodeError>;
190 getBranch(id: string): Effect.Effect<Branch, PrismaApiError | PrismaApiDecodeError>;
191 createBranch(
192 projectId: string,
193 input: BranchCreateInput,
194 ): Effect.Effect<Branch, PrismaApiError | PrismaApiDecodeError>;
195 updateBranch(
196 id: string,
197 input: BranchUpdateInput,
198 ): Effect.Effect<Branch, PrismaApiError | PrismaApiDecodeError>;
199 deleteBranch(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
200 listBuckets(
201 query?: BucketListQuery,
202 ): Effect.Effect<Bucket[], PrismaApiError | PrismaApiDecodeError>;
203 getBucket(id: string): Effect.Effect<Bucket, PrismaApiError | PrismaApiDecodeError>;
204 createBucket(
205 input: BucketCreateInput,
206 ): Effect.Effect<Bucket, PrismaApiError | PrismaApiDecodeError>;
207 deleteBucket(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
208 listBucketKeys(
209 bucketId: string,
210 query?: PaginationQuery,
211 ): Effect.Effect<BucketKey[], PrismaApiError | PrismaApiDecodeError>;
212 createBucketKey(
213 bucketId: string,
214 input: BucketKeyCreateInput,
215 ): Effect.Effect<BucketKeyWithSecret, PrismaApiError | PrismaApiDecodeError>;
216 deleteBucketKey(
217 bucketId: string,
218 keyId: string,
219 ): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
220 getCustomDomain(id: string): Effect.Effect<CustomDomain, PrismaApiError | PrismaApiDecodeError>;
221 deleteCustomDomain(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
222 retryCustomDomain(id: string): Effect.Effect<CustomDomain, PrismaApiError | PrismaApiDecodeError>;
223 listApps(query?: AppListQuery): Effect.Effect<App[], PrismaApiError | PrismaApiDecodeError>;
224 getApp(id: string): Effect.Effect<App, PrismaApiError | PrismaApiDecodeError>;
225 createApp(input: AppCreateInput): Effect.Effect<App, PrismaApiError | PrismaApiDecodeError>;
226 updateApp(
227 id: string,
228 input: AppUpdateInput,
229 ): Effect.Effect<App, PrismaApiError | PrismaApiDecodeError>;
230 deleteApp(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
231 promoteApp(
232 id: string,
233 target: AppDeploymentTarget,
234 ): Effect.Effect<PromoteAppResult, PrismaApiError | PrismaApiDecodeError>;
235 rollbackApp(
236 id: string,
237 target: AppDeploymentTarget,
238 ): Effect.Effect<RollbackAppResult, PrismaApiError | PrismaApiDecodeError>;
239 listAppDomains(
240 appId: string,
241 ): Effect.Effect<CustomDomain[], PrismaApiError | PrismaApiDecodeError>;
242 createAppDomain(
243 appId: string,
244 input: CustomDomainCreateInput,
245 ): Effect.Effect<CustomDomainCreateResult, PrismaApiError | PrismaApiDecodeError>;
246 listAppDeployments(
247 appId: string,
248 query?: PaginationQuery,
249 ): Effect.Effect<DeploymentListItem[], PrismaApiError | PrismaApiDecodeError>;
250 createAppDeployment(
251 appId: string,
252 input?: DeploymentCreateInput,
253 ): Effect.Effect<DeploymentCreateResult, PrismaApiError | PrismaApiDecodeError>;
254 getDeployment(id: string): Effect.Effect<Deployment, PrismaApiError | PrismaApiDecodeError>;
255 deleteDeployment(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
256 startDeployment(
257 id: string,
258 ): Effect.Effect<StartDeploymentResult, PrismaApiError | PrismaApiDecodeError>;
259 stopDeployment(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
260 getDeploymentLogsRequest(
261 id: string,
262 query?: DeploymentLogsQuery,
263 ): Effect.Effect<DeploymentLogsRequest, PrismaApiError>;
264 getBuildLogsRequest(
265 buildId: string,
266 query?: BuildLogsQuery,
267 ): Effect.Effect<BuildLogsRequest, PrismaApiError>;
268 listEnvironmentVariables(
269 query?: EnvironmentVariableListQuery,
270 ): Effect.Effect<EnvironmentVariable[], PrismaApiError | PrismaApiDecodeError>;
271 getEnvironmentVariable(
272 id: string,
273 ): Effect.Effect<EnvironmentVariable, PrismaApiError | PrismaApiDecodeError>;
274 createEnvironmentVariable(
275 input: EnvironmentVariableCreateInput,
276 ): Effect.Effect<EnvironmentVariable, PrismaApiError | PrismaApiDecodeError>;
277 updateEnvironmentVariable(
278 id: string,
279 input: EnvironmentVariableUpdateInput,
280 ): Effect.Effect<EnvironmentVariable, PrismaApiError | PrismaApiDecodeError>;
281 deleteEnvironmentVariable(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
282 listIntegrations(
283 query: IntegrationListQuery,
284 ): Effect.Effect<Integration[], PrismaApiError | PrismaApiDecodeError>;
285 listWorkspaceIntegrations(
286 workspaceId: string,
287 query?: PaginationQuery,
288 ): Effect.Effect<Integration[], PrismaApiError | PrismaApiDecodeError>;
289 getIntegration(id: string): Effect.Effect<Integration, PrismaApiError | PrismaApiDecodeError>;
290 deleteIntegration(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
291 revokeWorkspaceIntegration(
292 workspaceId: string,
293 clientId: string,
294 ): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
295 listScmInstallations(query: {
296 workspaceId: string;
297 cursor?: string | null;
298 limit?: number;
299 }): Effect.Effect<ScmInstallation[], PrismaApiError | PrismaApiDecodeError>;
300 createScmInstallIntent(
301 input: ScmInstallIntentCreateInput,
302 ): Effect.Effect<ScmInstallIntent, PrismaApiError | PrismaApiDecodeError>;
303 listScmInstallationRepositories(
304 installationId: string,
305 query?: PaginationQuery,
306 ): Effect.Effect<ScmRepository[], PrismaApiError | PrismaApiDecodeError>;
307 listSourceRepositories(
308 query: SourceRepositoryListQuery,
309 ): Effect.Effect<SourceRepository[], PrismaApiError | PrismaApiDecodeError>;
310 getSourceRepository(
311 id: string,
312 ): Effect.Effect<SourceRepository, PrismaApiError | PrismaApiDecodeError>;
313 createSourceRepository(
314 input: SourceRepositoryCreateInput,
315 ): Effect.Effect<SourceRepository, PrismaApiError | PrismaApiDecodeError>;
316 deleteSourceRepository(id: string): Effect.Effect<void, PrismaApiError | PrismaApiDecodeError>;
317 }
318
319 export class PrismaClient extends Context.Service<PrismaClient, PrismaManagementClient>()(
320 "Prisma::PrismaClient",
321 ) {}
322
323 export interface PaginationQuery {
324 cursor?: string | null;
325 limit?: number;
326 }
327
328 export interface BackupListQuery {
329 limit?: number;
330 }
331
332 export interface DatabaseUsageQuery {
333 startDate?: string;
334 endDate?: string;
335 }
336
337 export interface RegionListQuery {
338 product?: "postgres" | "accelerate";
339 }
340
341 export interface DatabaseListQuery extends PaginationQuery {
342 projectId?: string;
343 branchId?: PrismaBranchIdFilter;
344 branchGitName?: string;
345 }
346
347 export interface ConnectionListQuery extends PaginationQuery {
348 databaseId?: string;
349 }
350
351 export interface BranchListQuery extends PaginationQuery {
352 gitName?: string;
353 gitNameContains?: string;
354 }
355
356 export interface BucketListQuery extends PaginationQuery {
357 projectId?: string;
358 branchId?: PrismaBranchIdFilter;
359 branchGitName?: string;
360 }
361
362 export interface AppListQuery extends PaginationQuery {
363 projectId?: string;
364 branchId?: PrismaBranchIdFilter;
365 branchGitName?: string;
366 }
367
368 export type { BuildLogsQuery, BuildLogsRequest, DeploymentLogsQuery, DeploymentLogsRequest };
369
370 export interface EnvironmentVariableListQuery extends PaginationQuery {
371 projectId?: string;
372 class?: "production" | "preview";
373 key?: string;
374 branchId?: string;
375 }
376
377 export interface IntegrationListQuery extends PaginationQuery {
378 workspaceId: string;
379 }
380
381 export interface SourceRepositoryListQuery extends PaginationQuery {
382 projectId: string;
383 }
384
385 /** Response from the flat `POST /v1/databases` operation. */
386 export interface DatabaseCreateResult extends Omit<Database, "connections"> {
387 connections: DatabaseConnectionWithOptionalSecrets[];
388 }
389
390 /** Response from `POST /v1/projects/{projectId}/databases`. */
391 export interface ProjectDatabaseCreateResult extends Omit<
392 DatabaseCreateResult,
393 "region" | "status"
394 > {
395 status: "provisioning" | "ready";
396 region: { id: string; name: string };
397 }
398
399 export interface ProjectCreateDatabaseResult extends Omit<ProjectDatabaseCreateResult, "project"> {}
400
401 export interface ProjectCreateResult extends Project {
402 database: ProjectCreateDatabaseResult | null;
403 }
404
405 export const isNotFound = (error: unknown): boolean =>
406 error instanceof PrismaApiError && error.status === 404;
407
408 export const isConflict = (error: unknown): boolean =>
409 error instanceof PrismaApiError && error.status === 409;
410
411 const redactedString = (value: unknown): Redacted.Redacted<string> | undefined =>
412 typeof value === "string" ? Redacted.make(value) : undefined;
413
414 const decodeUrlComponent = (value: string) => {
415 try {
416 return decodeURIComponent(value);
417 } catch {
418 return value;
419 }
420 };
421
422 export const extractConnectionSecrets = (
423 connection: ObservedConnection | undefined | null,
424 ): PrismaSecretConnection => {
425 if (!connection) return {};
426 const direct = secretValue(connection.endpoints?.direct?.connectionString);
427 const pooled = secretValue(connection.endpoints?.pooled?.connectionString);
428 const accelerate = secretValue(connection.endpoints?.accelerate?.connectionString);
429 const directUrl = (() => {
430 if (!direct) return undefined;
431 try {
432 return new URL(direct);
433 } catch {
434 return undefined;
435 }
436 })();
437 return {
438 directConnectionString: redactedString(direct),
439 pooledConnectionString: redactedString(pooled),
440 accelerateConnectionString: redactedString(accelerate),
441 host: directUrl?.hostname ?? connection.endpoints?.direct?.host ?? null,
442 user: directUrl?.username ? decodeUrlComponent(directUrl.username) : null,
443 password: directUrl?.password
444 ? redactedString(decodeUrlComponent(directUrl.password))
445 : undefined,
446 };
447 };
448
449 export const requestBody = <T>(response: DataResponse<T>): T => response.data;
450
451 const isRetryableStatus = (status: number) =>
452 status === 0 || status === 408 || status === 429 || status >= 500;
453
454 const REQUEST_AND_BODY_TIMEOUT = "10 seconds" as const;
455 const MAX_SUCCESS_BODY_BYTES = 4 * 1024 * 1024;
456 const MAX_ERROR_BODY_BYTES = 64 * 1024;
457 const MAX_PAGINATION_PAGES = 1_000;
458 const MAX_PAGINATION_ITEMS = 100_000;
459 const MAX_PAGINATION_BODY_BYTES = 64 * 1024 * 1024;
460 const PAGINATION_TIMEOUT = "2 minutes" as const;
461 const ROLLBACK_REQUEST_TIMEOUT = "30 seconds" as const;
462 const PROVISIONING_REQUEST_TIMEOUT = "2 minutes" as const;
463 const INVALID_PATH_SEGMENT = "__alchemy_invalid_prisma_path_segment__";
464
465 const pathSegment = (value: string): string => {
466 if (
467 value.length === 0 ||
468 value === "." ||
469 value === ".." ||
470 value === INVALID_PATH_SEGMENT ||
471 /[\\/?#%]/.test(value) ||
472 value.includes("\0")
473 ) {
474 return INVALID_PATH_SEGMENT;
475 }
476 try {
477 return encodeURIComponent(value);
478 } catch {
479 return INVALID_PATH_SEGMENT;
480 }
481 };
482
483 const isRetryablePost = (path: string) =>
484 path.endsWith("/start") ||
485 path.endsWith("/stop") ||
486 path.endsWith("/promote") ||
487 path.endsWith("/rollback");
488
489 const isRetryableRequest = (method: Method, path: string) =>
490 method === "GET" ||
491 method === "DELETE" ||
492 method === "PATCH" ||
493 (method === "POST" && isRetryablePost(path));
494
495 const retryTransient = <A, E, R>(method: Method, path: string, effect: Effect.Effect<A, E, R>) =>
496 effect.pipe(
497 Effect.retry({
498 while: (e) =>
499 e instanceof PrismaApiError &&
500 isRetryableRequest(method, path) &&
501 isRetryableStatus(e.status),
502 schedule: Schedule.max([Schedule.exponential("100 millis"), Schedule.recurs(4)]),
503 }),
504 );
505
506 function makePrismaClient(): Effect.Effect<
507 PrismaManagementClient,
508 never,
509 PrismaEnvironment | HttpClient.HttpClient
510 > {
511 return Effect.gen(function* () {
512 const env = yield* PrismaEnvironment;
513 const http = yield* HttpClient.HttpClient;
514
515 function isValidApiPath(path: string): boolean {
516 if (
517 (path !== "/v1" && !path.startsWith("/v1/")) ||
518 path.startsWith("//") ||
519 path.includes("\\") ||
520 path.includes("?") ||
521 path.includes("#") ||
522 path.includes(INVALID_PATH_SEGMENT)
523 ) {
524 return false;
525 }
526 try {
527 const base = new URL(env.baseUrl);
528 const resolved = new URL(path, base);
529 return (
530 resolved.origin === base.origin &&
531 (resolved.pathname === "/v1" || resolved.pathname.startsWith("/v1/"))
532 );
533 } catch {
534 return false;
535 }
536 }
537
538 const buildUrl = (path: string, query?: object): Effect.Effect<string, PrismaApiError> => {
539 if (!isValidApiPath(path)) {
540 return Effect.fail(
541 new PrismaApiError({
542 method: "GET",
543 path,
544 status: 0,
545 message: "Refused an invalid Prisma Management API path parameter",
546 }),
547 );
548 }
549 return Effect.sync(() => {
550 const url = new URL(path, env.baseUrl);
551 for (const [key, value] of Object.entries(query ?? {})) {
552 if (value === undefined || value === null) continue;
553 if (Array.isArray(value)) {
554 for (const item of value) {
555 url.searchParams.append(key, String(item));
556 }
557 } else {
558 url.searchParams.set(key, String(value));
559 }
560 }
561 return url.toString();
562 });
563 };
564
565 const buildWebSocketUrl = (path: string, query?: object) =>
566 buildUrl(path, query).pipe(
567 Effect.map((value) => {
568 const url = new URL(value);
569 if (url.protocol === "https:") url.protocol = "wss:";
570 if (url.protocol === "http:") url.protocol = "ws:";
571 return url.toString();
572 }),
573 );
574
575 const logsQuery = (
576 query: DeploymentLogsQuery | undefined,
577 ): Record<string, unknown> | undefined => {
578 if (!query) return undefined;
579 const { fromStart, ...rest } = query;
580 return {
581 ...rest,
582 from_start: fromStart === undefined ? undefined : String(fromStart),
583 };
584 };
585
586 const makeRequest = (method: Method, url: string, options: RequestOptions | undefined) => {
587 const init =
588 method === "GET"
589 ? HttpClientRequest.get(url)
590 : method === "POST"
591 ? HttpClientRequest.post(url)
592 : method === "PATCH"
593 ? HttpClientRequest.patch(url)
594 : HttpClientRequest.delete(url);
595 const request = init.pipe(
596 HttpClientRequest.bearerToken(Redacted.value(env.serviceToken)),
597 HttpClientRequest.setHeaders({
598 Accept: "application/json",
599 "User-Agent": "alchemy-prisma/1.0",
600 ...options?.headers,
601 }),
602 );
603 return options?.body === undefined
604 ? request
605 : request.pipe(HttpClientRequest.bodyJsonUnsafe(options.body));
606 };
607
608 const requestWithStatus = <T>(
609 method: Method,
610 path: string,
611 options?: RequestOptions,
612 ): Effect.Effect<{ status: number; body: T }, PrismaApiError | PrismaApiDecodeError> => {
613 if (!isValidApiPath(path)) {
614 return Effect.fail(
615 new PrismaApiError({
616 method,
617 path,
618 status: 0,
619 message:
620 "Refused an invalid Prisma Management API path or path parameter outside the configured /v1 origin",
621 }),
622 );
623 }
624 return retryTransient(
625 method,
626 path,
627 Effect.gen(function* () {
628 const url = yield* buildUrl(path, options?.query);
629 const req = makeRequest(method, url, options);
630 const response = Effect.gen(function* () {
631 const res = yield* http.execute(req).pipe(
632 Effect.mapError(
633 (e) =>
634 new PrismaApiError({
635 method,
636 path,
637 status: 0,
638 message: e instanceof Error ? e.message : String(e),
639 }),
640 ),
641 );
642
643 const maxBodyBytes =
644 res.status >= 200 && res.status < 300 ? MAX_SUCCESS_BODY_BYTES : MAX_ERROR_BODY_BYTES;
645 const bodyTooLarge = (bodyLength: number) =>
646 res.status >= 200 && res.status < 300
647 ? new PrismaApiDecodeError({
648 method,
649 path,
650 bodyLength,
651 message: `Prisma Management API response exceeded the ${maxBodyBytes} byte safety limit`,
652 })
653 : new PrismaApiError({
654 method,
655 path,
656 status: res.status,
657 message: `Prisma Management API error response exceeded the ${maxBodyBytes} byte safety limit`,
658 });
659 const declaredLength = Number(res.headers["content-length"]);
660 if (Number.isSafeInteger(declaredLength) && declaredLength > maxBodyBytes) {
661 return yield* bodyTooLarge(declaredLength);
662 }
663
664 const collected = yield* Stream.runFoldEffect(
665 res.stream,
666 () => ({ chunks: [] as Uint8Array[], bytes: 0 }),
667 (state, chunk) => {
668 const bytes = state.bytes + chunk.byteLength;
669 if (bytes > maxBodyBytes) {
670 return Effect.fail(bodyTooLarge(bytes));
671 }
672 state.chunks.push(chunk);
673 state.bytes = bytes;
674 return Effect.succeed(state);
675 },
676 ).pipe(
677 Effect.catch((error) => {
678 if (error instanceof PrismaApiError || error instanceof PrismaApiDecodeError) {
679 return Effect.fail(error);
680 }
681 if (
682 HttpClientError.isHttpClientError(error) &&
683 error.reason._tag === "EmptyBodyError"
684 ) {
685 return Effect.succeed({
686 chunks: [] as Uint8Array[],
687 bytes: 0,
688 });
689 }
690 return Effect.fail(
691 new PrismaApiError({
692 method,
693 path,
694 status: 0,
695 message: `Failed to read Prisma Management API response: ${
696 error instanceof Error ? error.message : String(error)
697 }`,
698 }),
699 );
700 }),
701 );
702 const bytes = new Uint8Array(collected.bytes);
703 let offset = 0;
704 for (const chunk of collected.chunks) {
705 bytes.set(chunk, offset);
706 offset += chunk.byteLength;
707 }
708 const text = new TextDecoder().decode(bytes);
709 return { status: res.status, text, bodyLength: collected.bytes };
710 });
711 const { status, text, bodyLength } = yield* response;
712 if (status < 200 || status >= 300) {
713 return yield* new PrismaApiError({
714 method,
715 path,
716 status,
717 message: formatErrorMessage(status, text),
718 body: text.length === 0 ? undefined : Redacted.make(text),
719 });
720 }
721 if (options?.onSuccessfulBodyLength !== undefined) {
722 yield* options.onSuccessfulBodyLength(bodyLength);
723 }
724 if (status === 204 || text.length === 0) {
725 return { status, body: undefined as T };
726 }
727 const body = yield* Effect.try({
728 try: () => JSON.parse(text) as T,
729 catch: () =>
730 new PrismaApiDecodeError({
731 method,
732 path,
733 bodyLength: new TextEncoder().encode(text).byteLength,
734 message: "Prisma Management API returned invalid JSON",
735 }),
736 });
737 return { status, body };
738 }),
739 ).pipe(
740 // The deadline covers the complete operation, including transient
741 // retries and streaming the response body. A per-attempt timeout would
742 // multiply the advertised deadline and can leave a hung peer tying up
743 // a deployment for every retry slot.
744 Effect.timeoutOrElse({
745 duration: options?.timeout ?? REQUEST_AND_BODY_TIMEOUT,
746 orElse: () =>
747 Effect.fail(
748 new PrismaApiError({
749 method,
750 path,
751 status: 0,
752 message:
753 options?.timeout === undefined
754 ? `Prisma Management API request timed out after ${REQUEST_AND_BODY_TIMEOUT}`
755 : "Prisma Management API request timed out at the operation-specific deadline",
756 }),
757 ),
758 }),
759 );
760 };
761
762 const request = <T>(
763 method: Method,
764 path: string,
765 options?: RequestOptions,
766 ): Effect.Effect<T, PrismaApiError | PrismaApiDecodeError> =>
767 requestWithStatus<T>(method, path, options).pipe(Effect.map(({ body }) => body));
768
769 const dataWithStatus = <T>(method: Method, path: string, options?: RequestOptions) =>
770 requestWithStatus<unknown>(method, path, options).pipe(
771 Effect.flatMap(({ status, body: response }) =>
772 response !== null && typeof response === "object" && Object.hasOwn(response, "data")
773 ? Effect.succeed({
774 status,
775 data: requestBody(response as DataResponse<T>),
776 })
777 : Effect.fail(
778 new PrismaApiDecodeError({
779 method,
780 path,
781 bodyLength: 0,
782 message: "Prisma Management API response did not contain a data envelope",
783 }),
784 ),
785 ),
786 );
787
788 const data = <T>(method: Method, path: string, options?: RequestOptions) =>
789 dataWithStatus<T>(method, path, options).pipe(Effect.map(({ data }) => data));
790
791 const list = <T>(
792 path: string,
793 query?: object,
794 onSuccessfulBodyLength?: RequestOptions["onSuccessfulBodyLength"],
795 ) =>
796 request<ListResponse<T>>("GET", path, {
797 query,
798 onSuccessfulBodyLength,
799 });
800
801 const paginate = <T>(path: string, query?: object) =>
802 Effect.suspend(() => {
803 let observedPages = 0;
804 let observedItems = 0;
805 let observedBodyBytes = 0;
806 let observedCursor = false;
807 return Effect.gen(function* () {
808 const items: T[] = [];
809 const queryRecord = query as { cursor?: unknown } | undefined;
810 let cursor = typeof queryRecord?.cursor === "string" ? queryRecord.cursor : undefined;
811 const seenCursors = new Set<string>();
812 if (cursor !== undefined) seenCursors.add(cursor);
813 observedCursor = cursor !== undefined;
814
815 const protocolError = (message: string) =>
816 new PrismaApiDecodeError({
817 method: "GET",
818 path,
819 bodyLength: 0,
820 message: `Invalid Prisma Management API pagination response: ${message}`,
821 });
822 const accountForBody = (bodyLength: number) => {
823 const aggregateBodyLength = observedBodyBytes + bodyLength;
824 if (aggregateBodyLength > MAX_PAGINATION_BODY_BYTES) {
825 return Effect.fail(
826 new PrismaApiDecodeError({
827 method: "GET",
828 path,
829 bodyLength: aggregateBodyLength,
830 message: `Invalid Prisma Management API pagination response: exceeded the ${MAX_PAGINATION_BODY_BYTES} aggregate response byte safety limit`,
831 }),
832 );
833 }
834 observedBodyBytes = aggregateBodyLength;
835 return Effect.void;
836 };
837
838 while (true) {
839 if (observedPages >= MAX_PAGINATION_PAGES) {
840 return yield* protocolError(`exceeded the ${MAX_PAGINATION_PAGES} page safety limit`);
841 }
842 const page = yield* list<T>(path, { ...query, cursor }, accountForBody);
843 observedPages += 1;
844
845 if (
846 page === null ||
847 typeof page !== "object" ||
848 !Array.isArray(page.data) ||
849 page.pagination === null ||
850 typeof page.pagination !== "object" ||
851 typeof page.pagination.hasMore !== "boolean"
852 ) {
853 return yield* protocolError("expected data[] and pagination.hasMore");
854 }
855 if (page.data.length > MAX_PAGINATION_ITEMS - items.length) {
856 return yield* protocolError(`exceeded the ${MAX_PAGINATION_ITEMS} item safety limit`);
857 }
858 items.push(...page.data);
859 observedItems = items.length;
860
861 if (!page.pagination.hasMore) return items;
862 const nextCursor = page.pagination.nextCursor;
863 if (typeof nextCursor !== "string" || nextCursor.length === 0) {
864 return yield* protocolError("hasMore was true without a non-empty nextCursor");
865 }
866 if (seenCursors.has(nextCursor)) {
867 return yield* protocolError("nextCursor repeated");
868 }
869 seenCursors.add(nextCursor);
870 cursor = nextCursor;
871 observedCursor = true;
872 }
873 }).pipe(
874 Effect.timeoutOrElse({
875 duration: PAGINATION_TIMEOUT,
876 orElse: () =>
877 Effect.fail(
878 new PrismaApiError({
879 method: "GET",
880 path,
881 status: 0,
882 message: `Prisma Management API pagination timed out after ${PAGINATION_TIMEOUT} (${observedPages} pages, ${observedItems} items, ${observedBodyBytes} response bytes, cursor ${observedCursor ? "present" : "absent"})`,
883 }),
884 ),
885 }),
886 );
887 });
888
889 const service = {
890 listWorkspaces: (query) => paginate<Workspace>("/v1/workspaces", query),
891 getWorkspace: (id) => data<Workspace>("GET", `/v1/workspaces/${pathSegment(id)}`),
892 getCurrentPrincipal: () => data<CurrentPrincipal>("GET", "/v1/me"),
893 listRegions: (query) => data<Region[]>("GET", "/v1/regions", { query }),
894 listPostgresRegions: () => data<PostgresRegion[]>("GET", "/v1/regions/postgres"),
895 listAccelerateRegions: () => data<AccelerateRegion[]>("GET", "/v1/regions/accelerate"),
896
897 listProjects: (query) => paginate<Project>("/v1/projects", query),
898 getProject: (id) => data<Project>("GET", `/v1/projects/${pathSegment(id)}`),
899 createProject: (input) =>
900 data<ProjectCreateResult>("POST", "/v1/projects", {
901 body: input,
902 timeout: PROVISIONING_REQUEST_TIMEOUT,
903 }),
904 updateProject: (id, input) =>
905 data<Project>("PATCH", `/v1/projects/${pathSegment(id)}`, {
906 body: input,
907 }),
908 deleteProject: (id) =>
909 request<void>("DELETE", `/v1/projects/${pathSegment(id)}`, {
910 timeout: PROVISIONING_REQUEST_TIMEOUT,
911 }),
912 transferProject: (id, input) =>
913 request<void>("POST", `/v1/projects/${pathSegment(id)}/transfer`, {
914 body: input,
915 }),
916
917 listDatabases: (query) => paginate<Database>("/v1/databases", query),
918 listProjectDatabases: (projectId, query) =>
919 paginate<Database>(`/v1/projects/${pathSegment(projectId)}/databases`, query),
920 getDatabase: (id) => data<Database>("GET", `/v1/databases/${pathSegment(id)}`),
921 createDatabase: (input) =>
922 data<DatabaseCreateResult>("POST", "/v1/databases", {
923 body: input,
924 timeout: PROVISIONING_REQUEST_TIMEOUT,
925 }),
926 createProjectDatabase: (projectId, input) =>
927 data<ProjectDatabaseCreateResult>(
928 "POST",
929 `/v1/projects/${pathSegment(projectId)}/databases`,
930 { body: input, timeout: PROVISIONING_REQUEST_TIMEOUT },
931 ),
932 updateDatabase: (id, input) =>
933 data<Database>("PATCH", `/v1/databases/${pathSegment(id)}`, {
934 body: input,
935 }),
936 deleteDatabase: (id) =>
937 request<void>("DELETE", `/v1/databases/${pathSegment(id)}`, {
938 timeout: PROVISIONING_REQUEST_TIMEOUT,
939 }),
940 listBackups: (databaseId, query) =>
941 request<BackupListResponse>("GET", `/v1/databases/${pathSegment(databaseId)}/backups`, {
942 query,
943 }),
944 restoreDatabase: (targetDatabaseId, input) =>
945 data<RestoredDatabase>("POST", `/v1/databases/${pathSegment(targetDatabaseId)}/restore`, {
946 body: input,
947 timeout: PROVISIONING_REQUEST_TIMEOUT,
948 }),
949 getDatabaseUsage: (databaseId, query) =>
950 request<DatabaseUsage>("GET", `/v1/databases/${pathSegment(databaseId)}/usage`, { query }),
951
952 listConnections: (query) => paginate<DatabaseConnection>("/v1/connections", query),
953 listDatabaseConnections: (databaseId, query) =>
954 paginate<DatabaseConnection>(`/v1/databases/${pathSegment(databaseId)}/connections`, query),
955 getConnection: (id) => data<DatabaseConnection>("GET", `/v1/connections/${pathSegment(id)}`),
956 createConnection: (input) =>
957 data<DatabaseConnectionWithSecrets>("POST", "/v1/connections", {
958 body: input,
959 }),
960 createDatabaseConnection: (databaseId, input) =>
961 data<DatabaseConnectionWithSecrets>(
962 "POST",
963 `/v1/databases/${pathSegment(databaseId)}/connections`,
964 { body: input },
965 ),
966 deleteConnection: (id) => request<void>("DELETE", `/v1/connections/${pathSegment(id)}`),
967 rotateConnection: (id) =>
968 data<DatabaseConnectionWithSecrets>("POST", `/v1/connections/${pathSegment(id)}/rotate`),
969
970 listBranches: (projectId, query) =>
971 paginate<Branch>(`/v1/projects/${pathSegment(projectId)}/branches`, query),
972 getBranch: (id) => data<Branch>("GET", `/v1/branches/${pathSegment(id)}`),
973 createBranch: (projectId, input) =>
974 data<Branch>("POST", `/v1/projects/${pathSegment(projectId)}/branches`, {
975 body: input,
976 }),
977 updateBranch: (id, input) =>
978 data<Branch>("PATCH", `/v1/branches/${pathSegment(id)}`, {
979 body: input,
980 }),
981 deleteBranch: (id) => request<void>("DELETE", `/v1/branches/${pathSegment(id)}`),
982
983 listBuckets: (query) => paginate<Bucket>("/v1/buckets", query),
984 getBucket: (id) => data<Bucket>("GET", `/v1/buckets/${pathSegment(id)}`),
985 createBucket: (input) => data<Bucket>("POST", "/v1/buckets", { body: input }),
986 deleteBucket: (id) => request<void>("DELETE", `/v1/buckets/${pathSegment(id)}`),
987 listBucketKeys: (bucketId, query) =>
988 paginate<BucketKey>(`/v1/buckets/${pathSegment(bucketId)}/keys`, query),
989 createBucketKey: (bucketId, input) =>
990 data<BucketKeyWithSecret>("POST", `/v1/buckets/${pathSegment(bucketId)}/keys`, {
991 body: input,
992 }),
993 deleteBucketKey: (bucketId, keyId) =>
994 request<void>("DELETE", `/v1/buckets/${pathSegment(bucketId)}/keys/${pathSegment(keyId)}`),
995
996 getCustomDomain: (id) => data<CustomDomain>("GET", `/v1/domains/${pathSegment(id)}`),
997 deleteCustomDomain: (id) => request<void>("DELETE", `/v1/domains/${pathSegment(id)}`),
998 retryCustomDomain: (id) => data<CustomDomain>("POST", `/v1/domains/${pathSegment(id)}/retry`),
999
1000 listApps: (query) => paginate<App>("/v1/apps", query),
1001 getApp: (id) => data<App>("GET", `/v1/apps/${pathSegment(id)}`),
1002 createApp: (input) =>
1003 data<App>("POST", "/v1/apps", {
1004 body: input,
1005 timeout: PROVISIONING_REQUEST_TIMEOUT,
1006 }),
1007 updateApp: (id, input) => data<App>("PATCH", `/v1/apps/${pathSegment(id)}`, { body: input }),
1008 deleteApp: (id) =>
1009 request<void>("DELETE", `/v1/apps/${pathSegment(id)}`, {
1010 timeout: PROVISIONING_REQUEST_TIMEOUT,
1011 }),
1012 promoteApp: (id, target) =>
1013 data<PromoteAppResult>("POST", `/v1/apps/${pathSegment(id)}/promote`, {
1014 body: target,
1015 }),
1016 rollbackApp: (id, target) =>
1017 data<RollbackAppResult>("POST", `/v1/apps/${pathSegment(id)}/rollback`, {
1018 body: target,
1019 timeout: ROLLBACK_REQUEST_TIMEOUT,
1020 }),
1021 listAppDomains: (appId) => paginate<CustomDomain>(`/v1/apps/${pathSegment(appId)}/domains`),
1022 createAppDomain: (appId, input) => {
1023 const path = `/v1/apps/${pathSegment(appId)}/domains`;
1024 return dataWithStatus<CustomDomain>("POST", path, {
1025 body: input,
1026 }).pipe(
1027 Effect.flatMap(({ status, data: domain }) =>
1028 status === 200 || status === 201
1029 ? Effect.succeed({ status, domain })
1030 : Effect.fail(
1031 new PrismaApiDecodeError({
1032 method: "POST",
1033 path,
1034 bodyLength: 0,
1035 message: `Prisma Management API returned unexpected HTTP ${status} for custom-domain creation`,
1036 }),
1037 ),
1038 ),
1039 );
1040 },
1041 listAppDeployments: (appId, query) =>
1042 paginate<DeploymentListItem>(`/v1/apps/${pathSegment(appId)}/deployments`, query),
1043 createAppDeployment: (appId, input) =>
1044 data<DeploymentCreateResult>(
1045 "POST",
1046 `/v1/apps/${pathSegment(appId)}/deployments`,
1047 input === undefined ? undefined : { body: input },
1048 ),
1049 getDeployment: (id) => data<Deployment>("GET", `/v1/deployments/${pathSegment(id)}`),
1050 deleteDeployment: (id) => request<void>("DELETE", `/v1/deployments/${pathSegment(id)}`),
1051 startDeployment: (id) =>
1052 data<StartDeploymentResult>("POST", `/v1/deployments/${pathSegment(id)}/start`),
1053 stopDeployment: (id) => request<void>("POST", `/v1/deployments/${pathSegment(id)}/stop`),
1054 getDeploymentLogsRequest: (id, query) =>
1055 buildWebSocketUrl(`/v1/deployments/${pathSegment(id)}/logs`, logsQuery(query)).pipe(
1056 Effect.map((url): DeploymentLogsRequest => ({
1057 url,
1058 headers: {
1059 Authorization: Redacted.make(`Bearer ${Redacted.value(env.serviceToken)}`),
1060 },
1061 })),
1062 ),
1063 getBuildLogsRequest: (buildId, query) =>
1064 buildUrl(`/v1/builds/${pathSegment(buildId)}/logs`, query).pipe(
1065 Effect.map((url): BuildLogsRequest => ({
1066 url,
1067 headers: {
1068 Authorization: Redacted.make(`Bearer ${Redacted.value(env.serviceToken)}`),
1069 Accept: "application/x-ndjson",
1070 },
1071 })),
1072 ),
1073
1074 listEnvironmentVariables: (query) =>
1075 paginate<EnvironmentVariable>("/v1/environment-variables", query),
1076 getEnvironmentVariable: (id) =>
1077 data<EnvironmentVariable>("GET", `/v1/environment-variables/${pathSegment(id)}`),
1078 createEnvironmentVariable: (input) =>
1079 data<EnvironmentVariable>("POST", "/v1/environment-variables", {
1080 body: input,
1081 }),
1082 updateEnvironmentVariable: (id, input) =>
1083 data<EnvironmentVariable>("PATCH", `/v1/environment-variables/${pathSegment(id)}`, {
1084 body: input,
1085 }),
1086 deleteEnvironmentVariable: (id) =>
1087 request<void>("DELETE", `/v1/environment-variables/${pathSegment(id)}`),
1088
1089 listIntegrations: (query) => paginate<Integration>("/v1/integrations", query),
1090 listWorkspaceIntegrations: (workspaceId, query) =>
1091 paginate<Integration>(`/v1/workspaces/${pathSegment(workspaceId)}/integrations`, query),
1092 getIntegration: (id) => data<Integration>("GET", `/v1/integrations/${pathSegment(id)}`),
1093 deleteIntegration: (id) => request<void>("DELETE", `/v1/integrations/${pathSegment(id)}`),
1094 revokeWorkspaceIntegration: (workspaceId, clientId) =>
1095 request<void>(
1096 "DELETE",
1097 `/v1/workspaces/${pathSegment(workspaceId)}/integrations/${pathSegment(clientId)}`,
1098 ),
1099
1100 listScmInstallations: (query) => paginate<ScmInstallation>("/v1/scm-installations", query),
1101 createScmInstallIntent: (input) =>
1102 data<ScmInstallIntent>("POST", "/v1/scm-installations/install-intents", {
1103 body: input,
1104 }),
1105 listScmInstallationRepositories: (installationId, query) =>
1106 paginate<ScmRepository>(
1107 `/v1/scm-installations/${pathSegment(installationId)}/repositories`,
1108 query,
1109 ),
1110
1111 listSourceRepositories: (query) =>
1112 paginate<SourceRepository>("/v1/source-repositories", query),
1113 getSourceRepository: (id) =>
1114 data<SourceRepository>("GET", `/v1/source-repositories/${pathSegment(id)}`),
1115 createSourceRepository: (input) =>
1116 data<SourceRepository>("POST", "/v1/source-repositories", {
1117 body: input,
1118 }),
1119 deleteSourceRepository: (id) =>
1120 request<void>("DELETE", `/v1/source-repositories/${pathSegment(id)}`),
1121 } satisfies PrismaManagementClient;
1122 return service;
1123 });
1124 }
1125
1126 const SAFE_ERROR_CODE = /^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,127}$/;
1127
1128 const parseErrorCode = (body: string): string | undefined => {
1129 if (body.length === 0) return undefined;
1130 try {
1131 const json = JSON.parse(body) as {
1132 code?: unknown;
1133 error?: unknown;
1134 };
1135 const nested =
1136 json.error !== null && typeof json.error === "object"
1137 ? (json.error as { code?: unknown }).code
1138 : undefined;
1139 const code = json.code ?? nested;
1140 return typeof code === "string" && SAFE_ERROR_CODE.test(code) ? code : undefined;
1141 } catch {
1142 return undefined;
1143 }
1144 };
1145
1146 const formatErrorMessage = (status: number, body: string): string => {
1147 const code = parseErrorCode(body);
1148 return code === undefined ? `HTTP ${status}` : `Prisma Management API request failed (${code})`;
1149 };
1150
1151 export const PrismaClientLive = Layer.effect(PrismaClient, makePrismaClient());