@prisma/composer-prisma-cloud 0.1.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +201 -0
  2. package/dist/control.d.mts +53 -0
  3. package/dist/control.mjs +2031 -0
  4. package/dist/control.mjs.map +1 -0
  5. package/dist/cron/index.d.mts +99 -0
  6. package/dist/cron/index.mjs +392 -0
  7. package/dist/cron/index.mjs.map +1 -0
  8. package/dist/cron/scheduler-entrypoint.mjs +7769 -0
  9. package/dist/cron/scheduler-entrypoint.mjs.map +1 -0
  10. package/dist/cron/scheduler-service.mjs +318 -0
  11. package/dist/cron/scheduler-service.mjs.map +1 -0
  12. package/dist/index.d.mts +205 -0
  13. package/dist/index.mjs +182 -0
  14. package/dist/index.mjs.map +1 -0
  15. package/dist/param-DB0B8m15-IvzNq9BM.mjs +92 -0
  16. package/dist/param-DB0B8m15-IvzNq9BM.mjs.map +1 -0
  17. package/dist/prisma-next-COrwlg3N.mjs +176 -0
  18. package/dist/prisma-next-COrwlg3N.mjs.map +1 -0
  19. package/dist/prisma-next.d.mts +71 -0
  20. package/dist/prisma-next.mjs +2 -0
  21. package/dist/serializer-DAEWRfnm-D3GW9dOZ.mjs +235 -0
  22. package/dist/serializer-DAEWRfnm-D3GW9dOZ.mjs.map +1 -0
  23. package/dist/storage/index.d.mts +55 -0
  24. package/dist/storage/index.mjs +411 -0
  25. package/dist/storage/index.mjs.map +1 -0
  26. package/dist/storage/storage-entrypoint.mjs +1173 -0
  27. package/dist/storage/storage-entrypoint.mjs.map +1 -0
  28. package/dist/storage/storage-service.mjs +377 -0
  29. package/dist/storage/storage-service.mjs.map +1 -0
  30. package/dist/storage/testing.d.mts +85 -0
  31. package/dist/storage/testing.mjs +531 -0
  32. package/dist/storage/testing.mjs.map +1 -0
  33. package/dist/streams/index.d.mts +47 -0
  34. package/dist/streams/index.mjs +450 -0
  35. package/dist/streams/index.mjs.map +1 -0
  36. package/dist/streams/streams-entrypoint.mjs +40575 -0
  37. package/dist/streams/streams-entrypoint.mjs.map +1 -0
  38. package/dist/streams/streams-service.mjs +424 -0
  39. package/dist/streams/streams-service.mjs.map +1 -0
  40. package/dist/streams/testing.d.mts +33 -0
  41. package/dist/streams/testing.mjs +31335 -0
  42. package/dist/streams/testing.mjs.map +1 -0
  43. package/dist/testing.d.mts +25 -0
  44. package/dist/testing.mjs +32 -0
  45. package/dist/testing.mjs.map +1 -0
  46. package/package.json +74 -0
@@ -0,0 +1,2031 @@
1
+ import { a as encodeParamPointer, c as secretName, i as encode, l as secretPointerRows, s as paramEntries, t as configKey } from "./serializer-DAEWRfnm-D3GW9dOZ.mjs";
2
+ import { a as serviceKeyEdges, i as paramName, n as isEnvParamSource, o as serviceKeyEnvName, r as paramBindingFor } from "./param-DB0B8m15-IvzNq9BM.mjs";
3
+ import { a as normalizeSslMode, n as isPnPostgresResourceNode, o as withConnectionRetry } from "./prisma-next-COrwlg3N.mjs";
4
+ import { isParamSource, paramManifest, provisionManifest } from "@prisma/composer";
5
+ import { blindCast } from "@prisma/composer/casts";
6
+ import { RPC_PEER_KEY } from "@prisma/composer/rpc";
7
+ import pg from "pg";
8
+ import * as Layer from "effect/Layer";
9
+ import { createManagementApiClient } from "@prisma/management-api-sdk";
10
+ import * as Context from "effect/Context";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Redacted from "effect/Redacted";
13
+ import * as Config$1 from "effect/Config";
14
+ import * as Data from "effect/Data";
15
+ import * as Provider from "alchemy/Provider";
16
+ import { Resource, Stack } from "alchemy";
17
+ import * as Schedule from "effect/Schedule";
18
+ import * as fs from "node:fs";
19
+ import * as crypto$1 from "node:crypto";
20
+ import * as os from "node:os";
21
+ import * as path from "node:path";
22
+ import * as zlib from "node:zlib";
23
+ import postgres from "postgres";
24
+ import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveStateRecursive } from "alchemy/State";
25
+ import * as Output from "alchemy/Output";
26
+ import { loadConfig } from "@prisma-next/config-loader";
27
+ import { resolve } from "pathe";
28
+ import { readRef } from "@prisma-next/migration-tools/refs";
29
+ import { APP_SPACE_ID, readContractSpaceHeadRef, spaceMigrationDirectory, spaceRefsDirectory } from "@prisma-next/migration-tools/spaces";
30
+ import { createPostgresControlClient } from "@prisma-next/postgres/control";
31
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/http-CxGdfSAP.mjs
32
+ /**
33
+ * The Prisma service token used to authenticate Management API calls. Kept
34
+ * as a Redacted value so it never lands in logs or error output.
35
+ */
36
+ var PrismaCredentials = class extends Context.Service()("PrismaCredentials") {};
37
+ /** Resolve the token from the `PRISMA_SERVICE_TOKEN` environment variable. */
38
+ const fromEnv = () => Layer.effect(PrismaCredentials, Effect.gen(function* () {
39
+ return { token: yield* Config$1.redacted("PRISMA_SERVICE_TOKEN") };
40
+ }));
41
+ /**
42
+ * The typed Prisma Management API client, built once from the resolved
43
+ * credentials. Providers yield this in their outer Effect and call it inside
44
+ * `reconcile` / `delete`.
45
+ */
46
+ var ManagementClient = class extends Context.Service()("PrismaManagementClient") {};
47
+ const layer = () => Layer.effect(ManagementClient, Effect.gen(function* () {
48
+ const { token } = yield* PrismaCredentials;
49
+ return createManagementApiClient({ token: Redacted.value(token) });
50
+ }));
51
+ /** A non-2xx response from the Management API (or a transport failure). */
52
+ var PrismaApiError = class extends Data.TaggedError("PrismaApiError") {};
53
+ const attempt$1 = (f) => Effect.tryPromise({
54
+ try: f,
55
+ catch: (cause) => new PrismaApiError({
56
+ status: 0,
57
+ message: String(cause)
58
+ })
59
+ });
60
+ const fail = (r) => Effect.fail(new PrismaApiError({
61
+ status: r.response.status,
62
+ message: JSON.stringify(r.error)
63
+ }));
64
+ /** Unwrap `data`, failing on any API error. Preserves the SDK's response type. */
65
+ const call = (f) => attempt$1(f).pipe(Effect.flatMap((r) => r.error !== void 0 || r.data === void 0 ? fail(r) : Effect.succeed(r.data)));
66
+ /** Unwrap `data`, mapping a 404 to `undefined` (resource gone / not found). */
67
+ const callOptional = (f) => attempt$1(f).pipe(Effect.flatMap((r) => r.response.status === 404 ? Effect.succeed(void 0) : r.error !== void 0 ? fail(r) : Effect.succeed(r.data)));
68
+ /** Fire-and-forget a call, tolerating a 404 (already deleted). */
69
+ const callVoid = (f) => attempt$1(f).pipe(Effect.flatMap((r) => r.response.status === 404 || r.error === void 0 ? Effect.void : fail(r)));
70
+ //#endregion
71
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/compute/index.mjs
72
+ /**
73
+ * Stopping a deployment before the app that owns it can be
74
+ * deleted is asynchronous on the platform's side: DELETE can 409 with this
75
+ * message while the deployment is still winding down. Retrying blindly on
76
+ * every API error would mask real failures (bad auth, a genuinely conflicting
77
+ * state, etc.), so this only matches the platform's specific "not delete-safe
78
+ * yet" wording — everything else fails immediately, as before.
79
+ */
80
+ const isDeleteNotSafeYet = (error) => error.message.includes("did not reach a delete-safe state");
81
+ /**
82
+ * Backs off exponentially from 2s, capped at 5 minutes total — long enough
83
+ * for the platform to finish stopping the deployment, short enough to still
84
+ * fail loudly (rather than hang forever) if it never does.
85
+ */
86
+ const deleteSafeRetrySchedule = Schedule.both(Schedule.exponential("2 seconds", 2), Schedule.during("5 minutes"));
87
+ /** Every region Prisma Compute serves — the runtime source of truth; `ComputeRegion` is derived from it so the two can never drift. */
88
+ const COMPUTE_REGIONS = [
89
+ "us-east-1",
90
+ "us-west-1",
91
+ "eu-west-3",
92
+ "eu-central-1",
93
+ "ap-northeast-1",
94
+ "ap-southeast-1"
95
+ ];
96
+ /** A Prisma **Compute service** — the stable app identity behind a project. */
97
+ const ComputeService = Resource("Prisma.ComputeService");
98
+ const ComputeServiceProvider = () => Provider.effect(ComputeService, Effect.gen(function* () {
99
+ const client = yield* ManagementClient;
100
+ return {
101
+ stables: ["id"],
102
+ list: () => Effect.succeed([]),
103
+ reconcile: Effect.fn(function* ({ news, output }) {
104
+ const observed = output?.id ? yield* callOptional(() => client.GET("/v1/apps/{appId}", { params: { path: { appId: output.id } } })) : void 0;
105
+ if (observed) return {
106
+ id: observed.data.id,
107
+ name: observed.data.name,
108
+ endpointDomain: observed.data.appEndpointDomain
109
+ };
110
+ const created = yield* call(() => client.POST("/v1/apps", { body: {
111
+ displayName: news.name,
112
+ projectId: news.projectId,
113
+ ...news.region && { regionId: news.region },
114
+ ...news.branchId !== void 0 && { branchId: news.branchId }
115
+ } }));
116
+ return {
117
+ id: created.data.id,
118
+ name: created.data.name,
119
+ endpointDomain: created.data.appEndpointDomain
120
+ };
121
+ }),
122
+ delete: Effect.fn(function* ({ output }) {
123
+ yield* callVoid(() => client.DELETE("/v1/apps/{appId}", { params: { path: { appId: output.id } } })).pipe(Effect.retry({
124
+ schedule: deleteSafeRetrySchedule,
125
+ while: isDeleteNotSafeYet
126
+ }));
127
+ }),
128
+ read: Effect.fn(function* ({ output }) {
129
+ if (!output?.id) return void 0;
130
+ const s = yield* callOptional(() => client.GET("/v1/apps/{appId}", { params: { path: { appId: output.id } } }));
131
+ return s ? {
132
+ id: s.data.id,
133
+ name: s.data.name,
134
+ endpointDomain: s.data.appEndpointDomain
135
+ } : void 0;
136
+ })
137
+ };
138
+ }));
139
+ /**
140
+ * A **deployment** of a Prisma app — creates a deployment, uploads
141
+ * its artifact, starts the VM, waits for it to run, then promotes it to the
142
+ * app's stable endpoint.
143
+ */
144
+ const Deployment = Resource("Prisma.Deployment");
145
+ const DeploymentProvider = () => Provider.effect(Deployment, Effect.gen(function* () {
146
+ const client = yield* ManagementClient;
147
+ const waitForRunning = (deploymentId) => call(() => client.GET("/v1/deployments/{deploymentId}", { params: { path: { deploymentId } } })).pipe(Effect.flatMap((v) => v.data.status === "running" ? Effect.void : Effect.fail(new PrismaApiError({
148
+ status: 409,
149
+ message: `deployment ${deploymentId} is ${v.data.status}, not running`
150
+ }))), Effect.retry(Schedule.both(Schedule.spaced("2 seconds"), Schedule.during("2 minutes"))));
151
+ return {
152
+ stables: [],
153
+ list: () => Effect.succeed([]),
154
+ reconcile: Effect.fn(function* ({ news }) {
155
+ const created = yield* call(() => client.POST("/v1/apps/{appId}/deployments", {
156
+ params: { path: { appId: news.computeServiceId } },
157
+ body: news.port !== void 0 ? { portMapping: { http: news.port } } : {}
158
+ }));
159
+ const deploymentId = created.data.id;
160
+ if (created.data.uploadUrl) {
161
+ const uploadUrl = created.data.uploadUrl;
162
+ const artifact = yield* Effect.try({
163
+ try: () => fs.readFileSync(news.artifactPath),
164
+ catch: (cause) => new PrismaApiError({
165
+ status: 0,
166
+ message: `failed to read artifact ${news.artifactPath}: ${String(cause)}`
167
+ })
168
+ });
169
+ yield* Effect.tryPromise({
170
+ try: async () => {
171
+ const res = await fetch(uploadUrl, {
172
+ method: "PUT",
173
+ body: artifact
174
+ });
175
+ if (!res.ok) throw new PrismaApiError({
176
+ status: res.status,
177
+ message: `artifact upload failed: ${res.status} ${res.statusText}`
178
+ });
179
+ },
180
+ catch: (cause) => cause instanceof PrismaApiError ? cause : new PrismaApiError({
181
+ status: 0,
182
+ message: String(cause)
183
+ })
184
+ });
185
+ }
186
+ yield* call(() => client.POST("/v1/deployments/{deploymentId}/start", { params: { path: { deploymentId } } }));
187
+ yield* waitForRunning(deploymentId);
188
+ const deployedUrl = (yield* call(() => client.POST("/v1/apps/{appId}/promote", {
189
+ params: { path: { appId: news.computeServiceId } },
190
+ body: { deploymentId }
191
+ }))).data.appEndpointDomain;
192
+ return {
193
+ deploymentId,
194
+ ...deployedUrl !== void 0 && { deployedUrl }
195
+ };
196
+ }),
197
+ delete: Effect.fn(function* () {}),
198
+ read: Effect.fn(function* ({ output }) {
199
+ if (!output?.deploymentId) return void 0;
200
+ const v = yield* callOptional(() => client.GET("/v1/deployments/{deploymentId}", { params: { path: { deploymentId: output.deploymentId } } }));
201
+ return v ? {
202
+ deploymentId: v.data.id,
203
+ ...v.data.previewDomain && { deployedUrl: v.data.previewDomain }
204
+ } : void 0;
205
+ })
206
+ };
207
+ }));
208
+ /**
209
+ * A project-scoped **environment variable** that Compute injects into the
210
+ * project's services from their attached branch (e.g. wiring one module's URL into
211
+ * another).
212
+ */
213
+ const EnvironmentVariable = Resource("Prisma.EnvironmentVariable");
214
+ const EnvironmentVariableProvider = () => Provider.effect(EnvironmentVariable, Effect.gen(function* () {
215
+ const client = yield* ManagementClient;
216
+ return {
217
+ stables: ["id"],
218
+ list: () => Effect.succeed([]),
219
+ reconcile: Effect.fn(function* ({ news, output }) {
220
+ const cls = news.class ?? "production";
221
+ let id = output?.id;
222
+ if (id !== void 0) {
223
+ const priorId = id;
224
+ if (!(yield* callOptional(() => client.GET("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: priorId } } })))) id = void 0;
225
+ }
226
+ if (id === void 0) {
227
+ const matchId = (yield* call(() => client.GET("/v1/environment-variables", { params: { query: {
228
+ projectId: news.projectId,
229
+ class: cls,
230
+ key: news.key
231
+ } } }))).data?.[0]?.id;
232
+ if (matchId !== void 0) {
233
+ if (!(news.key === "DATABASE_URL" || news.key === "DATABASE_URL_POOLED")) throw new Error(`EnvironmentVariable "${news.key}" (project "${news.projectId}", class "${cls}") exists but is untracked in this deploy state — refusing to overwrite a reserved COMPOSER_ key. Restore this deploy's hosted state, or remove the variable to let this deploy recreate it.`);
234
+ id = matchId;
235
+ }
236
+ }
237
+ if (id !== void 0) {
238
+ const targetId = id;
239
+ yield* call(() => client.PATCH("/v1/environment-variables/{envVarId}", {
240
+ params: { path: { envVarId: targetId } },
241
+ body: { value: news.value }
242
+ }));
243
+ return {
244
+ id,
245
+ key: news.key
246
+ };
247
+ }
248
+ const created = yield* call(() => client.POST("/v1/environment-variables", { body: {
249
+ projectId: news.projectId,
250
+ class: cls,
251
+ key: news.key,
252
+ value: news.value,
253
+ ...news.branchId ? { branchId: news.branchId } : {}
254
+ } }));
255
+ return {
256
+ id: created.data.id,
257
+ key: created.data.key
258
+ };
259
+ }),
260
+ delete: Effect.fn(function* ({ output }) {
261
+ yield* callVoid(() => client.DELETE("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: output.id } } }));
262
+ }),
263
+ read: Effect.fn(function* ({ output }) {
264
+ if (!output?.id) return void 0;
265
+ const v = yield* callOptional(() => client.GET("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: output.id } } }));
266
+ return v ? {
267
+ id: v.data.id,
268
+ key: v.data.key
269
+ } : void 0;
270
+ })
271
+ };
272
+ }));
273
+ /**
274
+ * Assembles a Prisma Compute artifact: the app-built bundle plus the
275
+ * extension-printed bootstrap and manifest, tarred and gzipped deterministically
276
+ * (fixed mtimes, sorted entry order) so an unchanged service noops on
277
+ * redeploy — a rebuild is the only thing that changes the hash. Lives here
278
+ * (not in @prisma/composer-prisma-cloud/control) because it needs node:fs/node:zlib,
279
+ * which the extension's shipped src may never import (invariant 5).
280
+ */
281
+ const MANIFEST_VERSION = "1";
282
+ /** Finds main.js/main.mjs in a bundle dir when no explicit entry is given. */
283
+ function resolveEntry(bundleDir, entry) {
284
+ if (entry !== void 0) return entry;
285
+ const found = fs.readdirSync(bundleDir).find((f) => /^main\.m?js$/.test(f));
286
+ if (found === void 0) throw new Error(`no main.js/main.mjs found in bundle dir ${bundleDir}`);
287
+ return found;
288
+ }
289
+ /** All files under `dir`, as dir-relative POSIX paths, in sorted order. A
290
+ * symlink is a hard error: deploy bundles must be flat (ADR-0005), and the
291
+ * user's build owns flattening — dereferencing here would relink the tree and
292
+ * risk packaging files from outside it. */
293
+ function walkFiles(dir) {
294
+ const out = [];
295
+ const visit = (sub) => {
296
+ for (const entry of fs.readdirSync(path.join(dir, sub), { withFileTypes: true })) {
297
+ const rel = sub.length > 0 ? `${sub}/${entry.name}` : entry.name;
298
+ if (entry.isSymbolicLink()) throw new Error(`bundle contains a symlink at ${rel} — deploy bundles must be flat; materialize links in your build (e.g. cp -RL) so the tree is self-contained.`);
299
+ if (entry.isDirectory()) visit(rel);
300
+ else out.push(rel);
301
+ }
302
+ };
303
+ visit("");
304
+ return out.sort();
305
+ }
306
+ function octal(value, length) {
307
+ return `${value.toString(8).padStart(length - 1, "0")}\0`;
308
+ }
309
+ /** Splits a path into ustar's name (<=100 bytes) + prefix (<=155 bytes) fields. */
310
+ function splitUstarPath(relPath) {
311
+ if (Buffer.byteLength(relPath, "utf8") <= 100) return {
312
+ name: relPath,
313
+ prefix: ""
314
+ };
315
+ for (let i = relPath.length - 1; i >= 0; i--) {
316
+ if (relPath[i] !== "/") continue;
317
+ const prefix = relPath.slice(0, i);
318
+ const name = relPath.slice(i + 1);
319
+ if (Buffer.byteLength(prefix, "utf8") <= 155 && Buffer.byteLength(name, "utf8") <= 100) return {
320
+ name,
321
+ prefix
322
+ };
323
+ }
324
+ throw new Error(`path too long for a ustar tar entry: ${relPath}`);
325
+ }
326
+ function ustarHeader(relPath, size) {
327
+ const { name, prefix } = splitUstarPath(relPath);
328
+ const buf = Buffer.alloc(512);
329
+ buf.write(name, 0, 100, "utf8");
330
+ buf.write(octal(420, 8), 100, 8, "utf8");
331
+ buf.write(octal(0, 8), 108, 8, "utf8");
332
+ buf.write(octal(0, 8), 116, 8, "utf8");
333
+ buf.write(octal(size, 12), 124, 12, "utf8");
334
+ buf.write(octal(0, 12), 136, 12, "utf8");
335
+ buf.write(" ", 148, 8, "utf8");
336
+ buf.write("0", 156, 1, "utf8");
337
+ buf.write("ustar\0", 257, 6, "utf8");
338
+ buf.write("00", 263, 2, "utf8");
339
+ buf.write(prefix, 345, 155, "utf8");
340
+ let sum = 0;
341
+ for (const b of buf) sum += b;
342
+ buf.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, 8, "utf8");
343
+ return buf;
344
+ }
345
+ function createDeterministicTarGz(entries) {
346
+ const sorted = [...entries].sort((a, b) => a.relPath.localeCompare(b.relPath));
347
+ const chunks = [];
348
+ for (const entry of sorted) {
349
+ chunks.push(ustarHeader(entry.relPath, entry.content.length));
350
+ chunks.push(entry.content);
351
+ const pad = (512 - entry.content.length % 512) % 512;
352
+ if (pad > 0) chunks.push(Buffer.alloc(pad));
353
+ }
354
+ chunks.push(Buffer.alloc(1024));
355
+ return zlib.gzipSync(Buffer.concat(chunks));
356
+ }
357
+ /**
358
+ * Prints the bootstrap + manifest and tars them with the bundle into a
359
+ * deterministic artifact. If bundleDir doesn't exist (e.g. `alchemy destroy`
360
+ * run before any build), returns a placeholder rather than throwing — the
361
+ * artifact is never read on destroy.
362
+ */
363
+ function packageComputeArtifact(opts) {
364
+ if (!fs.existsSync(opts.bundleDir)) return {
365
+ path: "",
366
+ sha256: "absent"
367
+ };
368
+ const bootstrap = `import main from "./${resolveEntry(opts.bundleDir, opts.bundleEntry)}";\nawait main.run(${JSON.stringify(opts.address)}, () => import(${JSON.stringify(`./${opts.appEntry}`)}));\n`;
369
+ const manifest = `${JSON.stringify({
370
+ manifestVersion: MANIFEST_VERSION,
371
+ entrypoint: "bootstrap.js"
372
+ }, null, 2)}\n`;
373
+ const files = walkFiles(opts.bundleDir).map((relPath) => ({
374
+ relPath,
375
+ content: fs.readFileSync(path.join(opts.bundleDir, relPath))
376
+ }));
377
+ files.push({
378
+ relPath: "bootstrap.js",
379
+ content: Buffer.from(bootstrap, "utf8")
380
+ });
381
+ files.push({
382
+ relPath: "compute.manifest.json",
383
+ content: Buffer.from(manifest, "utf8")
384
+ });
385
+ files.push({
386
+ relPath: "bunfig.toml",
387
+ content: Buffer.from("[install]\nauto = \"disable\"\n", "utf8")
388
+ });
389
+ const gz = createDeterministicTarGz(files);
390
+ const sha256 = crypto$1.createHash("sha256").update(gz).digest("hex");
391
+ const outDir = path.join(os.tmpdir(), `prisma-composer-compute-${String(os.userInfo().uid)}`, sha256.slice(0, 16));
392
+ fs.mkdirSync(outDir, { recursive: true });
393
+ const outPath = path.join(outDir, `${opts.id}.tar.gz`);
394
+ const tmpPath = path.join(outDir, `.${opts.id}.${crypto$1.randomUUID()}.tmp`);
395
+ fs.writeFileSync(tmpPath, gz);
396
+ fs.renameSync(tmpPath, outPath);
397
+ return {
398
+ path: outPath,
399
+ sha256
400
+ };
401
+ }
402
+ /**
403
+ * The `ServiceKey` Alchemy resource (ADR-0030) — mints a random 256-bit key
404
+ * ONCE at create and keeps it STABLE across deploys, so an unchanged edge
405
+ * no-ops on redeploy. Same mint-once-stable lifecycle as `S3Credentials`
406
+ * (`packages/1-prisma-cloud/1-extensions/target/src/s3-credentials-resource.ts`):
407
+ * Web Crypto only (`crypto.getRandomValues` — no `node:` import), persisted in
408
+ * Alchemy state; on every later apply the provider returns the persisted
409
+ * attributes (`reconcile`'s `output`) unchanged. One resource per RPC edge;
410
+ * rotation is destroy/recreate.
411
+ */
412
+ /** The `ServiceKey` resource constructor — `yield* Prisma.ServiceKey(id, {})` in the lowering. */
413
+ const ServiceKey = Resource("PrismaCloud.ServiceKey");
414
+ /** A fresh 256-bit key as 64 lowercase hex chars (Web Crypto — no node import). */
415
+ function mintServiceKey() {
416
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
417
+ return { value: Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("") };
418
+ }
419
+ /**
420
+ * The `ServiceKey` provider service. `reconcile` runs for create and update;
421
+ * it returns the persisted `output` when present (a redeploy reuses the
422
+ * stored key — the no-op property) and mints a fresh key only on first
423
+ * create. Nothing to enumerate (`list` → `[]`) or tear down (`delete` →
424
+ * no-op; the key lives only in state).
425
+ */
426
+ const serviceKeyProviderService = {
427
+ list: () => Effect.succeed([]),
428
+ reconcile: ({ output }) => Effect.sync(() => output ?? mintServiceKey()),
429
+ delete: () => Effect.void
430
+ };
431
+ /** The `ServiceKey` provider layer — merged into the Prisma Cloud extension's `providers()`. */
432
+ const ServiceKeyProvider = () => Provider.effect(ServiceKey, Effect.succeed(serviceKeyProviderService));
433
+ //#endregion
434
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/postgres/index.mjs
435
+ /** A **connection** to a Prisma Postgres database — yields the connection string. */
436
+ const Connection = Resource("Prisma.Connection");
437
+ const ConnectionProvider = () => Provider.effect(Connection, Effect.gen(function* () {
438
+ const client = yield* ManagementClient;
439
+ return {
440
+ stables: ["id", "connectionString"],
441
+ list: () => Effect.succeed([]),
442
+ reconcile: Effect.fn(function* ({ news, output }) {
443
+ if (output?.id) return output;
444
+ const created = yield* call(() => client.POST("/v1/databases/{databaseId}/connections", {
445
+ params: { path: { databaseId: news.databaseId } },
446
+ body: { name: news.name }
447
+ }));
448
+ const endpoints = created.data.endpoints;
449
+ const dsn = endpoints?.direct?.connectionString ?? endpoints?.pooled?.connectionString;
450
+ if (dsn === void 0) return yield* Effect.fail(new PrismaApiError({
451
+ status: 0,
452
+ message: `connection ${created.data.id} returned no direct/pooled connection string`
453
+ }));
454
+ return {
455
+ id: created.data.id,
456
+ connectionString: Redacted.make(dsn)
457
+ };
458
+ }),
459
+ delete: Effect.fn(function* ({ output }) {
460
+ yield* callVoid(() => client.DELETE("/v1/connections/{id}", { params: { path: { id: output.id } } }));
461
+ })
462
+ };
463
+ }));
464
+ /** A Prisma **Postgres database** inside a project. */
465
+ const Database = Resource("Prisma.Database");
466
+ const DatabaseProvider = () => Provider.effect(Database, Effect.gen(function* () {
467
+ const client = yield* ManagementClient;
468
+ return {
469
+ stables: ["id"],
470
+ list: () => Effect.succeed([]),
471
+ reconcile: Effect.fn(function* ({ news, output }) {
472
+ const observed = output?.id ? yield* callOptional(() => client.GET("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } })) : void 0;
473
+ let result;
474
+ if (observed) result = {
475
+ id: observed.data.id,
476
+ name: observed.data.name
477
+ };
478
+ else {
479
+ const created = yield* call(() => client.POST("/v1/projects/{projectId}/databases", {
480
+ params: { path: { projectId: news.projectId } },
481
+ body: {
482
+ name: news.name,
483
+ region: news.region,
484
+ ...news.isDefault !== void 0 && { isDefault: news.isDefault }
485
+ }
486
+ }));
487
+ result = {
488
+ id: created.data.id,
489
+ name: created.data.name
490
+ };
491
+ }
492
+ if (news.branchId !== void 0) {
493
+ const branchId = news.branchId;
494
+ yield* call(() => client.PATCH("/v1/databases/{databaseId}", {
495
+ params: { path: { databaseId: result.id } },
496
+ body: { branchId }
497
+ }));
498
+ }
499
+ return result;
500
+ }),
501
+ delete: Effect.fn(function* ({ output }) {
502
+ yield* callVoid(() => client.DELETE("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } }));
503
+ }),
504
+ read: Effect.fn(function* ({ output }) {
505
+ if (!output?.id) return void 0;
506
+ const d = yield* callOptional(() => client.GET("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } }));
507
+ return d ? {
508
+ id: d.data.id,
509
+ name: d.data.name
510
+ } : void 0;
511
+ })
512
+ };
513
+ }));
514
+ /** A Prisma Developer Platform **Project** — the container for databases and compute services. */
515
+ const Project = Resource("Prisma.Project");
516
+ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
517
+ const client = yield* ManagementClient;
518
+ return {
519
+ stables: ["id"],
520
+ list: () => Effect.succeed([]),
521
+ reconcile: Effect.fn(function* ({ news, output }) {
522
+ const observed = output?.id ? yield* callOptional(() => client.GET("/v1/projects/{id}", { params: { path: { id: output.id } } })) : void 0;
523
+ if (observed) return {
524
+ id: observed.data.id,
525
+ name: observed.data.name
526
+ };
527
+ const created = yield* call(() => client.POST("/v1/projects", { body: {
528
+ name: news.name,
529
+ workspaceId: news.workspaceId
530
+ } }));
531
+ return {
532
+ id: created.data.id,
533
+ name: created.data.name
534
+ };
535
+ }),
536
+ delete: Effect.fn(function* ({ output }) {
537
+ yield* callVoid(() => client.DELETE("/v1/projects/{id}", { params: { path: { id: output.id } } }));
538
+ }),
539
+ read: Effect.fn(function* ({ output }) {
540
+ if (!output?.id) return void 0;
541
+ const p = yield* callOptional(() => client.GET("/v1/projects/{id}", { params: { path: { id: output.id } } }));
542
+ return p ? {
543
+ id: p.data.id,
544
+ name: p.data.name
545
+ } : void 0;
546
+ })
547
+ };
548
+ }));
549
+ Data.TaggedError("ContainerNotFoundError");
550
+ /** The collection of Prisma resource providers. */
551
+ var Providers = class extends Provider.ProviderCollection()("Prisma") {};
552
+ /**
553
+ * The Prisma provider bundle: every resource provider, the Management API
554
+ * client, and env-based credentials. Plug into a stack with
555
+ * `{ providers: Prisma.providers() }`.
556
+ */
557
+ const providers = () => Layer.effect(Providers, Provider.collection([
558
+ Project,
559
+ Database,
560
+ Connection,
561
+ ComputeService,
562
+ Deployment,
563
+ EnvironmentVariable
564
+ ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DatabaseProvider(), ConnectionProvider(), ComputeServiceProvider(), DeploymentProvider(), EnvironmentVariableProvider())), Layer.provideMerge(layer()), Layer.provideMerge(fromEnv()), Layer.orDie);
565
+ //#endregion
566
+ //#region ../../1-prisma-cloud/0-lowering/lowering/dist/state/index.mjs
567
+ /** The framework-owned database a stage's deploy state lives in — a child of that stage's Branch (ADR-0034). */
568
+ const STATE_DATABASE_NAME = "prisma-composer-state";
569
+ /** Every connection created against a state database carries this prefix — see `cleanupAgedConnections`. */
570
+ const CONNECTION_NAME_PREFIX = "prisma-composer-state-";
571
+ const listAllBranches = (client, projectId) => Effect.gen(function* () {
572
+ const branches = [];
573
+ let cursor;
574
+ for (;;) {
575
+ const query = cursor === void 0 ? {} : { cursor };
576
+ const page = yield* call(() => client.GET("/v1/projects/{projectId}/branches", { params: {
577
+ path: { projectId },
578
+ query
579
+ } }));
580
+ branches.push(...page.data);
581
+ if (!page.pagination.hasMore || page.pagination.nextCursor === null) break;
582
+ cursor = page.pagination.nextCursor;
583
+ }
584
+ return branches;
585
+ });
586
+ /**
587
+ * The project's implicit default Branch — every live Project owns exactly
588
+ * one (a platform invariant). The list endpoint has no `isDefault` filter, so
589
+ * this pages through every Branch and picks it out client-side. Never creates
590
+ * one: its absence means the platform's invariant is broken, which is not
591
+ * something a deploy can repair.
592
+ */
593
+ const resolveDefaultBranchId = (client, projectId) => Effect.gen(function* () {
594
+ const found = (yield* listAllBranches(client, projectId)).find((b) => b.isDefault);
595
+ if (found !== void 0) return found.id;
596
+ return yield* Effect.fail(new PrismaApiError({
597
+ status: 0,
598
+ message: `project ${projectId} has no default Branch — the platform guarantees every live Project owns one; contact support.`
599
+ }));
600
+ });
601
+ /** A named stage carries its `branchId`; production omits it, and its state lives on the Project's default Branch. */
602
+ const resolveBranchId = (client, container) => container.branchId !== void 0 ? Effect.succeed(container.branchId) : resolveDefaultBranchId(client, container.projectId);
603
+ /**
604
+ * Every database on this Branch. Uses the flat `GET /v1/databases`, which
605
+ * accepts `projectId` and `branchId` together — the project-scoped listing
606
+ * has no branch filter at all.
607
+ */
608
+ const listAllDatabasesOnBranch = (client, projectId, branchId) => Effect.gen(function* () {
609
+ const databases = [];
610
+ let cursor;
611
+ for (;;) {
612
+ const query = cursor === void 0 ? {
613
+ projectId,
614
+ branchId
615
+ } : {
616
+ projectId,
617
+ branchId,
618
+ cursor
619
+ };
620
+ const page = yield* call(() => client.GET("/v1/databases", { params: { query } }));
621
+ databases.push(...page.data);
622
+ if (!page.pagination.hasMore || page.pagination.nextCursor === null) break;
623
+ cursor = page.pagination.nextCursor;
624
+ }
625
+ return databases;
626
+ });
627
+ /**
628
+ * Databases on this Branch named `prisma-composer-state`, oldest first,
629
+ * excluding the Branch's own default database. The default database is always
630
+ * the user's, never ours to adopt or delete. A name match alone proves
631
+ * nothing — the platform allows duplicate names — so every caller must still
632
+ * verify ownership before acting on a candidate.
633
+ */
634
+ const listStateDatabaseCandidates = (client, projectId, branchId) => listAllDatabasesOnBranch(client, projectId, branchId).pipe(Effect.map((databases) => databases.filter((d) => d.name === "prisma-composer-state" && !d.isDefault).sort((a, b) => a.createdAt.localeCompare(b.createdAt))));
635
+ /**
636
+ * Creates a fresh Postgres connection and reads its connection string. Reads
637
+ * `endpoints.direct.connectionString` only — never `endpoints.pooled`, and
638
+ * never the deprecated top-level `connectionString`/`url` (PRO-212), neither
639
+ * of which the platform guarantees.
640
+ *
641
+ * The connection string is returned only when the connection is created and
642
+ * cannot be read back afterwards, which is why every run creates a fresh
643
+ * connection instead of reusing one.
644
+ */
645
+ const createConnection = (client, databaseId) => call(() => client.POST("/v1/databases/{databaseId}/connections", {
646
+ params: { path: { databaseId } },
647
+ body: { name: `${CONNECTION_NAME_PREFIX}${Date.now()}` }
648
+ })).pipe(Effect.flatMap((r) => {
649
+ const created = r.data;
650
+ const dsn = created.endpoints.direct?.connectionString;
651
+ return dsn === void 0 ? Effect.fail(new PrismaApiError({
652
+ status: 0,
653
+ message: `connection ${created.id} returned no endpoints.direct.connectionString (PRO-212)`
654
+ })) : Effect.succeed(Redacted.make(dsn));
655
+ }));
656
+ /** Collapses any thrown value (postgres.js failures included) into a {@link StateStoreError}. */
657
+ const toStateStoreError = (cause) => cause instanceof Error ? new StateStoreError({
658
+ message: cause.message,
659
+ cause
660
+ }) : new StateStoreError({ message: String(cause) });
661
+ /**
662
+ * An operator-facing failure from the hosted-state bootstrap pipeline
663
+ * (branch/database discovery, connection creation, schema migration, or lock
664
+ * acquisition) — what a deployer actually sees, instead of a raw Effect
665
+ * defect.
666
+ */
667
+ var HostedStateBootstrapError = class extends Data.TaggedError("HostedStateBootstrapError") {
668
+ get message() {
669
+ return `hosted-state bootstrap failed in ${this.container}: ${this.step} — ${this.reason}`;
670
+ }
671
+ };
672
+ /**
673
+ * Builds a {@link HostedStateBootstrapError} from whatever the failed step
674
+ * threw. Never retains the raw driver/API error object as `cause`: a
675
+ * postgres.js connection failure's `.message`/properties are not verified to
676
+ * omit the DSN or credentials, so only the extracted message text survives
677
+ * into the operator-facing error.
678
+ */
679
+ const hostedStateBootstrapError = (container, step, cause) => new HostedStateBootstrapError({
680
+ container,
681
+ step,
682
+ reason: cause instanceof Error ? cause.message : String(cause)
683
+ });
684
+ /**
685
+ * The well-known marker row written into every database this store owns.
686
+ * Its presence proves the database is genuinely Prisma App's state store, not
687
+ * a same-named project squatting on the discovery query (see `bootstrap.ts`
688
+ * `verifyOwnership` — PDP allows duplicate project names).
689
+ */
690
+ const STATE_META_MARKER = "prisma-composer-state-v1";
691
+ /**
692
+ * Idempotent schema migration for the Prisma-hosted state store — safe to run
693
+ * on every deploy, since `create table if not exists` no-ops once the tables
694
+ * exist. Run this against `sql` before serving a {@link StateService} built
695
+ * by `makePrismaStateService` over the same client.
696
+ */
697
+ const migratePrismaState = (sql) => Effect.tryPromise({
698
+ try: async () => {
699
+ await sql`
700
+ create table if not exists alchemy_resource_state (
701
+ stack text not null,
702
+ stage text not null,
703
+ fqn text not null,
704
+ value jsonb not null,
705
+ updated_at timestamptz not null default now(),
706
+ primary key (stack, stage, fqn)
707
+ )
708
+ `;
709
+ await sql`
710
+ create table if not exists alchemy_stack_output (
711
+ stack text not null,
712
+ stage text not null,
713
+ value jsonb not null,
714
+ updated_at timestamptz not null default now(),
715
+ primary key (stack, stage)
716
+ )
717
+ `;
718
+ await sql`
719
+ create table if not exists prisma_app_state_meta (
720
+ marker text primary key,
721
+ created_at timestamptz not null default now()
722
+ )
723
+ `;
724
+ await sql`
725
+ insert into prisma_app_state_meta (marker) values (${STATE_META_MARKER})
726
+ on conflict (marker) do nothing
727
+ `;
728
+ },
729
+ catch: toStateStoreError
730
+ });
731
+ const CONNECTION_MAX_AGE_MS = 1440 * 60 * 1e3;
732
+ /**
733
+ * Creates the state database on the stage's Branch, using the flat endpoint
734
+ * because it is the only one that accepts a `branchId`. The platform still
735
+ * creates the row on the project's default Branch and attaches it afterwards,
736
+ * so a failed attach can leave a database behind on the default Branch. It
737
+ * checks the Branch exists before creating, and this is one request instead of
738
+ * two, so that window is much narrower than attaching from here — but it is
739
+ * narrowed, not closed.
740
+ *
741
+ * `isDefault` is left at the API's `false` default: the state database must
742
+ * never be the stage's default database, which belongs to the user.
743
+ */
744
+ const createStateDatabase = (client, projectId, branchId) => call(() => client.POST("/v1/databases", { body: {
745
+ projectId,
746
+ name: STATE_DATABASE_NAME,
747
+ region: "inherit",
748
+ branchId
749
+ } })).pipe(Effect.map((created) => ({
750
+ id: created.data.id,
751
+ name: created.data.name,
752
+ isDefault: created.data.isDefault,
753
+ createdAt: created.data.createdAt
754
+ })));
755
+ const listAllConnections = (client, databaseId) => Effect.gen(function* () {
756
+ const connections = [];
757
+ let cursor;
758
+ for (;;) {
759
+ const query = cursor === void 0 ? {} : { cursor };
760
+ const page = yield* call(() => client.GET("/v1/databases/{databaseId}/connections", { params: {
761
+ path: { databaseId },
762
+ query
763
+ } }));
764
+ connections.push(...page.data);
765
+ if (!page.pagination.hasMore || page.pagination.nextCursor === null) break;
766
+ cursor = page.pagination.nextCursor;
767
+ }
768
+ return connections;
769
+ });
770
+ const deleteConnection = (client, connectionId) => callVoid(() => client.DELETE("/v1/connections/{id}", { params: { path: { id: connectionId } } }));
771
+ /**
772
+ * Every deploy creates a fresh connection (`createConnection`) and nothing ever
773
+ * closes it, so the state database otherwise accumulates one connection
774
+ * resource per run without bound. Best-effort, never blocks bootstrap: lists
775
+ * this database's connections, deletes the ones matching our naming pattern
776
+ * older than the age threshold, and swallows any failure (a transient API
777
+ * error here must never fail the deploy it's cleaning up after).
778
+ */
779
+ const cleanupAgedConnections = (client, databaseId) => Effect.gen(function* () {
780
+ const connections = yield* listAllConnections(client, databaseId);
781
+ const cutoff = Date.now() - CONNECTION_MAX_AGE_MS;
782
+ const aged = connections.filter((c) => c.name.startsWith("prisma-composer-state-") && Date.parse(c.createdAt) < cutoff);
783
+ yield* Effect.forEach(aged, (c) => deleteConnection(client, c.id), { discard: true });
784
+ }).pipe(Effect.ignore);
785
+ /**
786
+ * PDP allows duplicate database names, so a database named `prisma-composer-state`
787
+ * found by listing is not proof it's ours — it could be an unrelated
788
+ * database that happens to share the name (a squatter, deliberate or not).
789
+ * Connects to the candidate and inspects its tables:
790
+ *
791
+ * - our marker table with our marker row present → `ours`, adopt outright.
792
+ * - our state tables (`alchemy_resource_state`/`alchemy_stack_output`) but no
793
+ * marker → `legacy`: a database from before this ownership check existed.
794
+ * The real, currently-in-use workspace state is in this shape today, so it
795
+ * must keep working — adopt it, and `migratePrismaState` (idempotent)
796
+ * writes the marker on the way in.
797
+ * - no tables at all → `empty`, a freshly-created database — adopt.
798
+ * - anything else → `squatter`: foreign data occupies the name; refuse it.
799
+ */
800
+ const verifyOwnership = (connectionString) => Effect.tryPromise({
801
+ try: async () => {
802
+ const sql = postgres(Redacted.value(connectionString), {
803
+ max: 1,
804
+ onnotice: () => {}
805
+ });
806
+ try {
807
+ const rows = await sql`
808
+ select tablename from pg_tables where schemaname = 'public'
809
+ `;
810
+ const tables = new Set(rows.map((row) => row.tablename));
811
+ if (tables.has("prisma_app_state_meta")) return (await sql`
812
+ select marker from prisma_app_state_meta where marker = ${"prisma-composer-state-v1"}
813
+ `).length > 0 ? { kind: "ours" } : {
814
+ kind: "squatter",
815
+ tables: [...tables]
816
+ };
817
+ if (tables.has("alchemy_resource_state") || tables.has("alchemy_stack_output")) return { kind: "legacy" };
818
+ return tables.size === 0 ? { kind: "empty" } : {
819
+ kind: "squatter",
820
+ tables: [...tables]
821
+ };
822
+ } finally {
823
+ await sql.end({ timeout: 5 });
824
+ }
825
+ },
826
+ catch: (cause) => new PrismaApiError({
827
+ status: 0,
828
+ message: `ownership verification failed: ${cause instanceof Error ? cause.message : String(cause)}`
829
+ })
830
+ });
831
+ /**
832
+ * Finds the Branch's `prisma-composer-state` database, verifying ownership
833
+ * rather than trusting the name alone (PDP allows duplicate names — see
834
+ * `verifyOwnership`). Finding none creates one, with nothing to verify: only
835
+ * this run can have touched a database it just created.
836
+ *
837
+ * Candidates are tried oldest first, so repeated runs pick the same one. The
838
+ * first that verifies as ours is used. A candidate that fails verification is
839
+ * skipped. If every candidate fails, bootstrap fails and names each rejected
840
+ * database id, so an operator knows which to rename or remove.
841
+ */
842
+ const resolveStateDatabase = (client, projectId, branchId, verify) => Effect.gen(function* () {
843
+ const candidates = yield* listStateDatabaseCandidates(client, projectId, branchId);
844
+ if (candidates.length === 0) {
845
+ const database = yield* createStateDatabase(client, projectId, branchId);
846
+ const connectionString = yield* createConnection(client, database.id);
847
+ console.error(`hosted state: provisioned state database ${database.id} on branch ${branchId} (project ${projectId})`);
848
+ return {
849
+ database,
850
+ connectionString
851
+ };
852
+ }
853
+ const rejected = [];
854
+ for (const candidate of candidates) {
855
+ const connectionString = yield* createConnection(client, candidate.id);
856
+ const verdict = yield* verify(connectionString);
857
+ if (verdict.kind === "squatter") {
858
+ rejected.push(`${candidate.id} (foreign tables: ${verdict.tables.join(", ")})`);
859
+ continue;
860
+ }
861
+ console.error(`hosted state: using state database ${candidate.id} on branch ${branchId} (${verdict.kind}) — ${candidates.length} candidate(s) named ${STATE_DATABASE_NAME}`);
862
+ return {
863
+ database: candidate,
864
+ connectionString
865
+ };
866
+ }
867
+ return yield* Effect.fail(new PrismaApiError({
868
+ status: 0,
869
+ message: `found ${candidates.length} database(s) named "${STATE_DATABASE_NAME}" on branch ${branchId}, but none verified as Composer's state store: ${rejected.join("; ")}. Rename or remove the offending database(s).`
870
+ }));
871
+ });
872
+ /**
873
+ * Resolves the stage's Branch, find-or-creates its `prisma-composer-state`
874
+ * database, and creates a fresh connection — the automatic bootstrap every
875
+ * deploy runs once, needing nothing beyond the service token and the
876
+ * Project/Branch ids the CLI already resolved.
877
+ */
878
+ const bootstrapStateConnection = (container) => bootstrapStateConnectionWith(container, verifyOwnership);
879
+ /**
880
+ * Identical to {@link bootstrapStateConnection}, except the ownership check is
881
+ * a parameter so `bootstrap.test.ts` can supply a fake instead of opening a
882
+ * real Postgres connection.
883
+ */
884
+ const bootstrapStateConnectionWith = (container, verify) => Effect.gen(function* () {
885
+ const client = yield* ManagementClient;
886
+ const branchId = yield* resolveBranchId(client, container);
887
+ const { database, connectionString } = yield* resolveStateDatabase(client, container.projectId, branchId, verify);
888
+ yield* cleanupAgedConnections(client, database.id);
889
+ return {
890
+ projectId: container.projectId,
891
+ databaseId: database.id,
892
+ connectionString
893
+ };
894
+ });
895
+ const deleteDatabase = (client, databaseId) => callVoid(() => client.DELETE("/v1/databases/{databaseId}", { params: { path: { databaseId } } }));
896
+ /**
897
+ * Identical to {@link deleteStateDatabase}, except the ownership check is a
898
+ * parameter so tests can supply a fake instead of opening a real Postgres
899
+ * connection.
900
+ */
901
+ const deleteStateDatabaseWith = (container, verify) => Effect.gen(function* () {
902
+ const client = yield* ManagementClient;
903
+ const branchId = yield* resolveBranchId(client, container);
904
+ const candidates = yield* listStateDatabaseCandidates(client, container.projectId, branchId);
905
+ for (const candidate of candidates) {
906
+ const verdict = yield* verify(yield* createConnection(client, candidate.id));
907
+ if (verdict.kind === "squatter") {
908
+ console.warn(`hosted state: left database ${candidate.id} on branch ${branchId} alone — it is named ${STATE_DATABASE_NAME} but holds unrelated data (tables: ${verdict.tables.join(", ")}).`);
909
+ continue;
910
+ }
911
+ yield* deleteDatabase(client, candidate.id);
912
+ console.error(`hosted state: removed state database ${candidate.id} from branch ${branchId}`);
913
+ }
914
+ });
915
+ /** Codes for "can't reach the host yet" — DNS/refusal, not a mid-session drop. */
916
+ const ESTABLISHMENT_CODES = /* @__PURE__ */ new Set([
917
+ "ECONNREFUSED",
918
+ "ENOTFOUND",
919
+ "EAI_AGAIN"
920
+ ]);
921
+ /** Connection-establishment failure messages (no useful `err.code`). `upstream database` is PPg's edge proxy while a cold/idle upstream warms up. */
922
+ const ESTABLISHMENT_MESSAGE_FRAGMENTS = ["upstream database", "connection refused"];
923
+ /**
924
+ * Whether a failure is a connection-establishment error against a warming
925
+ * upstream (retry), as opposed to a lost lease, a mid-session drop, or a real
926
+ * query error (all of which must surface at once). Unwraps a
927
+ * {@link StateStoreError} to its driver `cause` so a code-only error still
928
+ * classifies.
929
+ */
930
+ const isColdStartConnectError = (error) => {
931
+ if (typeof error !== "object" || error === null) return false;
932
+ const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
933
+ if (code !== void 0 && ESTABLISHMENT_CODES.has(code)) return true;
934
+ const message = "message" in error && typeof error.message === "string" ? error.message.toLowerCase() : "";
935
+ if (ESTABLISHMENT_MESSAGE_FRAGMENTS.some((fragment) => message.includes(fragment))) return true;
936
+ const cause = "cause" in error ? error.cause : void 0;
937
+ return cause !== void 0 && cause !== error && isColdStartConnectError(cause);
938
+ };
939
+ /** The same ~2-minute budget the bootstrap migration uses (`layer.ts`): retry every 5s, up to 2 minutes. */
940
+ const COLD_START_SCHEDULE = Schedule.both(Schedule.spaced("5 seconds"), Schedule.during("2 minutes"));
941
+ /**
942
+ * Retries a state operation past a cold-start connection rejection only; every
943
+ * other failure surfaces immediately. `schedule` is injectable so tests drive
944
+ * it without real delay.
945
+ */
946
+ const retryColdStart = (operation, schedule = COLD_START_SCHEDULE) => Effect.retry(operation, {
947
+ while: isColdStartConnectError,
948
+ schedule
949
+ });
950
+ /** Another deploy already holds the lock for this stack/stage. Never queued — fails immediately. */
951
+ var StateLockContentionError = class extends Data.TaggedError("StateLockContentionError") {
952
+ get message() {
953
+ return `another deploy holds the state lock for ${this.stack}/${this.stage}`;
954
+ }
955
+ };
956
+ const lockKey = (stack, stage) => `prisma-composer:${stack}/${stage}`;
957
+ /**
958
+ * Acquires a session-scoped Postgres advisory lock on a reserved
959
+ * connection pulled from `sql`'s pool — session (not transaction) scope,
960
+ * because a transaction-scoped lock releases at the first commit and a
961
+ * deploy spans many. Held for the run's whole lifetime; contention fails
962
+ * immediately rather than queuing. If the process crashes, the reserved
963
+ * connection drops and Postgres auto-releases the session lock — no
964
+ * explicit crash-recovery bookkeeping needed.
965
+ */
966
+ const acquireStateLock = (sql, stack, stage) => Effect.gen(function* () {
967
+ const key = lockKey(stack, stage);
968
+ const reserved = yield* Effect.tryPromise({
969
+ try: () => sql.reserve(),
970
+ catch: toStateStoreError
971
+ });
972
+ const acquired = yield* Effect.tryPromise({
973
+ try: async () => {
974
+ return (await reserved`
975
+ select
976
+ pg_try_advisory_lock(hashtextextended(${key}, 0)) as acquired,
977
+ pg_backend_pid() as pid
978
+ `)[0];
979
+ },
980
+ catch: toStateStoreError
981
+ });
982
+ if (acquired?.acquired !== true) {
983
+ reserved.release();
984
+ return yield* Effect.fail(new StateLockContentionError({
985
+ stack,
986
+ stage
987
+ }));
988
+ }
989
+ const lockPid = acquired.pid;
990
+ const checkLive = retryColdStart(Effect.tryPromise({
991
+ try: async () => {
992
+ return (await sql`
993
+ select exists (
994
+ select 1 from pg_locks
995
+ where locktype = 'advisory'
996
+ and pid = ${lockPid}
997
+ and objsubid = 1
998
+ and granted
999
+ and ((classid::bigint << 32) | (objid::bigint & 4294967295))
1000
+ = hashtextextended(${key}, 0)
1001
+ ) as live
1002
+ `)[0]?.live ?? false;
1003
+ },
1004
+ catch: toStateStoreError
1005
+ }).pipe(Effect.flatMap((live) => live ? Effect.void : Effect.fail(new StateStoreError({ message: `the state lock for ${stack}/${stage} was lost mid-run; refusing to continue unlocked` })))));
1006
+ const release = async () => {
1007
+ try {
1008
+ await reserved`select pg_advisory_unlock(hashtextextended(${key}, 0))`;
1009
+ } catch {} finally {
1010
+ reserved.release();
1011
+ }
1012
+ };
1013
+ return {
1014
+ checkLive,
1015
+ release
1016
+ };
1017
+ });
1018
+ const attempt = (f) => retryColdStart(Effect.tryPromise({
1019
+ try: f,
1020
+ catch: toStateStoreError
1021
+ }));
1022
+ /**
1023
+ * Wraps an already-`encodeState`d value as a jsonb-typed bind parameter.
1024
+ * Must go through `sql.json(...)` (not `JSON.stringify(...)::jsonb`) —
1025
+ * postgres.js re-serializes the parameter once it learns the server-inferred
1026
+ * type is jsonb, so a pre-stringified value passed through a `::jsonb` cast
1027
+ * gets JSON-encoded *twice* and lands as a jsonb string instead of an
1028
+ * object. `sql.json` gives postgres.js the raw value up front and declares
1029
+ * the jsonb oid itself, so it is serialized exactly once.
1030
+ */
1031
+ const jsonParam = (sql, value) => sql.json(blindCast(encodeState(value)));
1032
+ /**
1033
+ * `reviveStateRecursive` is typed to return `unknown` — the caller is
1034
+ * expected to know the shape it revived. Here the shape is known by
1035
+ * construction: every row was written by `set()`, which persists a value
1036
+ * through `encodeState` first, so reviving it recovers a `PersistedState`.
1037
+ */
1038
+ const revivePersistedState = (value) => blindCast(reviveStateRecursive(value));
1039
+ /** Same reasoning as {@link revivePersistedState}, narrowed by the SQL status filter. */
1040
+ const reviveReplacedResourceState = (value) => blindCast(reviveStateRecursive(value));
1041
+ /**
1042
+ * Builds alchemy's `StateService` over a caller-supplied postgres.js client,
1043
+ * against the two-table schema `migratePrismaState` creates. The caller owns
1044
+ * the client's lifecycle (connection pooling, reconnects, `.end()`); this
1045
+ * factory only issues queries.
1046
+ */
1047
+ const makePrismaStateService = (sql) => ({
1048
+ id: "prisma-postgres",
1049
+ getVersion: () => Effect.succeed(STATE_STORE_VERSION),
1050
+ listStacks: () => attempt(() => sql`
1051
+ select stack from alchemy_resource_state
1052
+ union
1053
+ select stack from alchemy_stack_output
1054
+ order by stack
1055
+ `).pipe(Effect.map((rows) => rows.map((row) => row.stack))),
1056
+ listStages: (stack) => attempt(() => sql`
1057
+ select stage from alchemy_resource_state where stack = ${stack}
1058
+ union
1059
+ select stage from alchemy_stack_output where stack = ${stack}
1060
+ order by stage
1061
+ `).pipe(Effect.map((rows) => rows.map((row) => row.stage))),
1062
+ get: (request) => attempt(() => sql`
1063
+ select value from alchemy_resource_state
1064
+ where stack = ${request.stack} and stage = ${request.stage} and fqn = ${request.fqn}
1065
+ `).pipe(Effect.map((rows) => {
1066
+ const row = rows[0];
1067
+ return row === void 0 ? void 0 : revivePersistedState(row.value);
1068
+ })),
1069
+ getReplacedResources: (request) => attempt(() => sql`
1070
+ select value from alchemy_resource_state
1071
+ where stack = ${request.stack} and stage = ${request.stage}
1072
+ and value ->> 'status' = 'replaced'
1073
+ `).pipe(Effect.map((rows) => rows.map((row) => reviveReplacedResourceState(row.value)))),
1074
+ set: (request) => attempt(() => sql`
1075
+ insert into alchemy_resource_state (stack, stage, fqn, value, updated_at)
1076
+ values (
1077
+ ${request.stack}, ${request.stage}, ${request.fqn},
1078
+ ${jsonParam(sql, request.value)}, now()
1079
+ )
1080
+ on conflict (stack, stage, fqn) do update
1081
+ set value = excluded.value, updated_at = excluded.updated_at
1082
+ `).pipe(Effect.map(() => request.value)),
1083
+ delete: (request) => attempt(() => sql`
1084
+ delete from alchemy_resource_state
1085
+ where stack = ${request.stack} and stage = ${request.stage} and fqn = ${request.fqn}
1086
+ `).pipe(Effect.asVoid),
1087
+ deleteStack: (request) => attempt(async () => {
1088
+ if (request.stage === void 0) {
1089
+ await sql`delete from alchemy_resource_state where stack = ${request.stack}`;
1090
+ await sql`delete from alchemy_stack_output where stack = ${request.stack}`;
1091
+ } else {
1092
+ await sql`
1093
+ delete from alchemy_resource_state
1094
+ where stack = ${request.stack} and stage = ${request.stage}
1095
+ `;
1096
+ await sql`
1097
+ delete from alchemy_stack_output
1098
+ where stack = ${request.stack} and stage = ${request.stage}
1099
+ `;
1100
+ }
1101
+ }),
1102
+ list: (request) => attempt(() => sql`
1103
+ select fqn from alchemy_resource_state
1104
+ where stack = ${request.stack} and stage = ${request.stage}
1105
+ order by fqn
1106
+ `).pipe(Effect.map((rows) => rows.map((row) => row.fqn))),
1107
+ getOutput: (request) => attempt(() => sql`
1108
+ select value from alchemy_stack_output
1109
+ where stack = ${request.stack} and stage = ${request.stage}
1110
+ `).pipe(Effect.map((rows) => {
1111
+ const row = rows[0];
1112
+ return row === void 0 ? void 0 : reviveStateRecursive(row.value);
1113
+ })),
1114
+ setOutput: (request) => attempt(() => sql`
1115
+ insert into alchemy_stack_output (stack, stage, value, updated_at)
1116
+ values (${request.stack}, ${request.stage}, ${jsonParam(sql, request.value)}, now())
1117
+ on conflict (stack, stage) do update
1118
+ set value = excluded.value, updated_at = excluded.updated_at
1119
+ `).pipe(Effect.map(() => request.value))
1120
+ });
1121
+ /**
1122
+ * How long a passing lease check is trusted before the next storage
1123
+ * operation re-verifies it. A deploy issues many state ops in quick
1124
+ * succession, and each raw `checkLive` is a `pg_locks` round-trip; without
1125
+ * amortization the guard roughly doubles the store's traffic. The cost of the
1126
+ * window is bounded: a lease lost mid-window is detected within this many ms,
1127
+ * not instantly — an accepted tradeoff on top of the already-accepted
1128
+ * non-atomic (TOCTOU) gap between the check and the operation.
1129
+ */
1130
+ const LEASE_CHECK_TTL_MS = 5e3;
1131
+ /**
1132
+ * Amortizes a lease check over a short TTL: a *passing* check is trusted for
1133
+ * `ttlMs`, so a burst of operations inside the window does one round-trip, not
1134
+ * one per op. A *failing* check is never cached — it propagates immediately
1135
+ * and leaves the last-good timestamp untouched, so the very next op re-checks.
1136
+ * The `lastOkAt` state is captured per call, so each store (each layer) gets
1137
+ * its own window — two stores in one process never share a cached success.
1138
+ */
1139
+ const amortizeCheck = (checkLive, ttlMs, now) => {
1140
+ let lastOkAt;
1141
+ return Effect.suspend(() => {
1142
+ if (lastOkAt !== void 0 && now() - lastOkAt < ttlMs) return Effect.void;
1143
+ return checkLive.pipe(Effect.tap(() => Effect.sync(() => {
1144
+ lastOkAt = now();
1145
+ })));
1146
+ });
1147
+ };
1148
+ /**
1149
+ * Wraps a {@link StateService} so every method that touches storage first
1150
+ * re-verifies the state lock's lease via `checkLive`. Used to enforce "a
1151
+ * dropped lock connection fails loudly" — see {@link ../lock.ts}. The check is
1152
+ * amortized over a short TTL (see {@link amortizeCheck}), so a run of
1153
+ * back-to-back operations does not fire one `pg_locks` round-trip per call.
1154
+ *
1155
+ * Reads are gated too, not just writes: a lost lease means a concurrent
1156
+ * deploy may already be mutating this stack's rows, so a read could return
1157
+ * stale or conflicting data — untrustworthy either way, not just the writes.
1158
+ * The check is best-effort and not atomic with the operation it guards (the
1159
+ * lease could be lost in the gap between `checkLive` passing and the wrapped
1160
+ * call executing, or within the TTL window); that residual race is accepted.
1161
+ *
1162
+ * `getVersion` is excluded: it returns a compile-time constant
1163
+ * (`STATE_STORE_VERSION`), so guarding it would only add a pointless
1164
+ * reserved-connection round-trip.
1165
+ *
1166
+ * `now` is injectable so tests can advance the clock deterministically; it
1167
+ * defaults to `Date.now` (fine in library runtime code — only Workflow
1168
+ * scripts forbid it).
1169
+ */
1170
+ const guardStateService = (service, checkLive, now = Date.now) => {
1171
+ const guard = amortizeCheck(checkLive, LEASE_CHECK_TTL_MS, now);
1172
+ return {
1173
+ id: service.id,
1174
+ getVersion: () => service.getVersion(),
1175
+ listStacks: () => guard.pipe(Effect.andThen(service.listStacks())),
1176
+ listStages: (stack) => guard.pipe(Effect.andThen(service.listStages(stack))),
1177
+ get: (request) => guard.pipe(Effect.andThen(service.get(request))),
1178
+ getReplacedResources: (request) => guard.pipe(Effect.andThen(service.getReplacedResources(request))),
1179
+ set: (request) => guard.pipe(Effect.andThen(service.set(request))),
1180
+ delete: (request) => guard.pipe(Effect.andThen(service.delete(request))),
1181
+ deleteStack: (request) => guard.pipe(Effect.andThen(service.deleteStack(request))),
1182
+ list: (request) => guard.pipe(Effect.andThen(service.list(request))),
1183
+ getOutput: (request) => guard.pipe(Effect.andThen(service.getOutput(request))),
1184
+ setOutput: (request) => guard.pipe(Effect.andThen(service.setOutput(request)))
1185
+ };
1186
+ };
1187
+ /**
1188
+ * The hosted Alchemy state store. On layer init (scoped, once per stack
1189
+ * run): resolve the stage's Branch, find-or-create its `prisma-composer-state`
1190
+ * database, create a fresh connection, migrate the schema, and acquire the
1191
+ * (stack, stage) advisory lock — see `bootstrap.ts` and `lock.ts`. The
1192
+ * Management API plumbing (`ManagementClient`, `PrismaCredentials`) is
1193
+ * provided internally, so the returned layer's only requirements are the
1194
+ * ones alchemy itself already provides to every state store
1195
+ * (`StackServices`).
1196
+ *
1197
+ * Any bootstrap/lock/migration failure is wrapped into an operator-facing
1198
+ * `HostedStateBootstrapError` (naming the Project/Branch and the step that
1199
+ * failed, never the raw driver/API error — see `errors.ts`) before dying the
1200
+ * layer (loud, immediate, unrecoverable) rather than surfacing as a typed
1201
+ * error — matching core's `LowerOptions.state: Layer.Layer<State, never,
1202
+ * StackServices>` contract and alchemy's own convention (e.g. a missing
1203
+ * state store is `Effect.die` in `Stack.make`).
1204
+ */
1205
+ const prismaState = () => {
1206
+ const projectId = process.env["PRISMA_PROJECT_ID"];
1207
+ if (projectId === void 0 || projectId.length === 0) throw new Error("prismaState(): environment variable PRISMA_PROJECT_ID is required (the CLI sets it — deploy via `prisma-composer deploy`).");
1208
+ const branchIdEnv = process.env["PRISMA_BRANCH_ID"];
1209
+ const branchId = branchIdEnv === void 0 || branchIdEnv.length === 0 ? void 0 : branchIdEnv;
1210
+ return Layer.effect(State, Effect.gen(function* () {
1211
+ const stack = yield* Stack;
1212
+ const container = branchId === void 0 ? projectId : `${projectId}/${branchId}`;
1213
+ const bootstrapError = (step) => (cause) => hostedStateBootstrapError(container, step, cause);
1214
+ const { connectionString } = yield* bootstrapStateConnection(branchId === void 0 ? { projectId } : {
1215
+ projectId,
1216
+ branchId
1217
+ }).pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))), Effect.mapError(bootstrapError("resolving the state database on the stage branch")));
1218
+ const sql = postgres(Redacted.value(connectionString), {
1219
+ max: 5,
1220
+ onnotice: () => {}
1221
+ });
1222
+ yield* Effect.addFinalizer(() => Effect.promise(() => sql.end({ timeout: 5 })));
1223
+ yield* migratePrismaState(sql).pipe(Effect.retry(Schedule.both(Schedule.spaced("5 seconds"), Schedule.during("2 minutes"))), Effect.mapError(bootstrapError("schema migration")));
1224
+ const lock = yield* acquireStateLock(sql, stack.name, stack.stage).pipe(Effect.mapError(bootstrapError("lock acquisition")));
1225
+ yield* Effect.addFinalizer(() => Effect.promise(() => lock.release()));
1226
+ const service = guardStateService(makePrismaStateService(sql), lock.checkLive);
1227
+ return Effect.succeed(service);
1228
+ })).pipe(Layer.orDie);
1229
+ };
1230
+ //#endregion
1231
+ //#region ../../1-prisma-cloud/1-extensions/target/dist/control.mjs
1232
+ const PRISMA_NAME_MIN = 3;
1233
+ const PRISMA_NAME_MAX = 65;
1234
+ function validateName(value, source) {
1235
+ if (value.length < PRISMA_NAME_MIN || value.length > PRISMA_NAME_MAX) throw new Error(`prisma-cloud: ${source} "${value}" (${value.length} characters) is not a valid Prisma resource name — Prisma requires ${PRISMA_NAME_MIN}–${PRISMA_NAME_MAX} characters. Rename the provision id (or the deploy --name) to fit.`);
1236
+ }
1237
+ function isCloudApplication(value) {
1238
+ return typeof value === "object" && value !== null && "projectId" in value && typeof value.projectId === "string";
1239
+ }
1240
+ /** Narrows `ctx.application`, which core hands over as `unknown`, to this extension's own product; throws naming the hook when it hasn't run. */
1241
+ function projectIdOf(application) {
1242
+ if (!isCloudApplication(application)) throw new Error("prisma-cloud: ctx.application is not this extension's application product — the prismaCloud() application hook must run before any node lowers.");
1243
+ return application.projectId;
1244
+ }
1245
+ /** The `compute` node kind's descriptor: the four service hooks — provision, serialize, package, deploy. */
1246
+ /**
1247
+ * Returns the PRECISE descriptor type, not the erased `NodeDescriptor`: the
1248
+ * registry in control.ts erases it on assignment anyway (method bivariance),
1249
+ * but s3-store composes over these hooks and needs their P/S to stay visible.
1250
+ * Annotating this `NodeDescriptor` would force s3-store to cast them back.
1251
+ */
1252
+ function computeDescriptor(o) {
1253
+ return {
1254
+ kind: "service",
1255
+ provision: ({ id, application }) => Effect.gen(function* () {
1256
+ validateName(id, "service name (from provision id)");
1257
+ const projectId = projectIdOf(application);
1258
+ return {
1259
+ serviceId: (yield* ComputeService(`${id}-svc`, {
1260
+ projectId,
1261
+ name: id,
1262
+ region: o.region ?? "us-east-1",
1263
+ ...o.branchId !== void 0 ? { branchId: o.branchId } : {}
1264
+ })).id,
1265
+ projectId
1266
+ };
1267
+ }),
1268
+ serialize: (ctx, provisioned, config) => Effect.gen(function* () {
1269
+ const { address, node, graph } = ctx;
1270
+ const cls = o.branchId ? "preview" : "production";
1271
+ const branch = o.branchId !== void 0 ? { branchId: o.branchId } : {};
1272
+ const projectId = provisioned.projectId;
1273
+ const svc = node;
1274
+ const records = [];
1275
+ for (const d of paramEntries(svc)) {
1276
+ const value = d.owner === "service" ? config.service[d.name] : config.inputs[d.owner.input]?.[d.name];
1277
+ if (value === void 0) continue;
1278
+ const key = configKey(address, d);
1279
+ const rowValue = d.owner === "service" && isParamSource(value) ? encodeParamPointer(paramName(paramBindingFor(graph.params, address, d.name))) : encode(d.owner, value);
1280
+ records.push(yield* EnvironmentVariable(`${key}-var`, {
1281
+ projectId,
1282
+ key,
1283
+ value: rowValue,
1284
+ class: cls,
1285
+ ...branch
1286
+ }));
1287
+ }
1288
+ for (const { key, name } of secretPointerRows(svc, address, graph.secrets)) records.push(yield* EnvironmentVariable(`${key}-var`, {
1289
+ projectId,
1290
+ key,
1291
+ value: name,
1292
+ class: cls,
1293
+ ...branch
1294
+ }));
1295
+ if (svc.expose !== void 0 && Object.keys(svc.expose).length > 0) {
1296
+ const keyOuts = serviceKeyEdges(graph).filter((e) => e.providerAddress === address).map((e) => ctx.provisioned.get(e.edgeId)).filter((value) => value !== void 0).map((value) => blindCast(value));
1297
+ const acceptedJson = keyOuts.length > 0 ? Output.map(Output.all(...keyOuts), (vals) => JSON.stringify(vals)) : JSON.stringify([]);
1298
+ const key = serviceKeyEnvName(address);
1299
+ records.push(yield* EnvironmentVariable(`${key}-var`, {
1300
+ projectId,
1301
+ key,
1302
+ value: acceptedJson,
1303
+ class: cls,
1304
+ ...branch
1305
+ }));
1306
+ }
1307
+ return {
1308
+ environment: records,
1309
+ port: typeof config.service["port"] === "number" ? config.service["port"] : 3e3
1310
+ };
1311
+ }),
1312
+ package: ({ id }, { assembled, address }) => Effect.try(() => packageComputeArtifact({
1313
+ id,
1314
+ bundleDir: assembled.dir,
1315
+ appEntry: assembled.entry,
1316
+ address
1317
+ })),
1318
+ deploy: ({ id }, provisioned, artifact, serialized) => Effect.gen(function* () {
1319
+ const deployment = yield* Deployment(`${id}-deploy`, {
1320
+ computeServiceId: provisioned.serviceId,
1321
+ artifactPath: artifact.path,
1322
+ artifactHash: artifact.sha256,
1323
+ environment: serialized.environment,
1324
+ port: serialized.port
1325
+ });
1326
+ return {
1327
+ outputs: {
1328
+ url: deployment.deployedUrl,
1329
+ projectId: provisioned.projectId
1330
+ },
1331
+ entities: [{
1332
+ kind: "compute-service",
1333
+ id: provisioned.serviceId,
1334
+ url: deployment.deployedUrl
1335
+ }]
1336
+ };
1337
+ })
1338
+ };
1339
+ }
1340
+ /**
1341
+ * The `PgWarm` Alchemy resource (slice 3, FT-5226) — warm a freshly-provisioned
1342
+ * Prisma Postgres database at apply-time so it is ready by deploy-end, and the
1343
+ * first real connection (a service's runtime client, or the migration) doesn't
1344
+ * eat the cold-start reject.
1345
+ *
1346
+ * The DB `url` is a lazy `Output` at lowering time, so warming must be an
1347
+ * apply-time tracked resource (same pattern as `PnMigration`): its `reconcile`
1348
+ * receives the RESOLVED url and connects with `withConnectionRetry` + `select 1`,
1349
+ * riding out the cold-start. Shared by BOTH the bare-`postgres` and the
1350
+ * `prisma-next` lowerings; keyed on the connection `url`, so an unchanged
1351
+ * redeploy is a no-op (warming is idempotent anyway).
1352
+ *
1353
+ * Deploy-time only: imports `pg` directly + `alchemy`. Imported by `control.ts`
1354
+ * and tests, never by `index.ts` / the `./prisma-next` authoring entry — the
1355
+ * isolation invariants hold.
1356
+ */
1357
+ /** The `PgWarm` resource constructor — `yield* PgWarm(id, { url })` in a lowering. */
1358
+ const PgWarm = Resource("PrismaCloud.PgWarm");
1359
+ /** Connect (retrying the cold-start) and run `select 1`, then release the connection. */
1360
+ async function warmDatabase(url) {
1361
+ await withConnectionRetry(async () => {
1362
+ const client = new pg.Client({ connectionString: normalizeSslMode(url) });
1363
+ await client.connect();
1364
+ try {
1365
+ await client.query("select 1");
1366
+ } finally {
1367
+ await client.end();
1368
+ }
1369
+ });
1370
+ }
1371
+ /**
1372
+ * The `PgWarm` provider service. `reconcile` warms the DB (retrying the
1373
+ * cold-start) and echoes the `url` so a downstream resource that reads
1374
+ * `warm.url` runs only after the DB is warm. Idempotent — safe on redeploy;
1375
+ * nothing to enumerate (`list` → `[]`) or tear down (`delete` → no-op; the DB's
1376
+ * own deletion handles teardown). Exported so tests can drive it directly.
1377
+ */
1378
+ const pgWarmProviderService = {
1379
+ list: () => Effect.succeed([]),
1380
+ reconcile: ({ news }) => Effect.tryPromise({
1381
+ try: () => warmDatabase(news.url),
1382
+ catch: (error) => error
1383
+ }).pipe(Effect.map(() => ({ url: news.url }))),
1384
+ delete: () => Effect.void
1385
+ };
1386
+ /** The `PgWarm` provider layer — merged into the extension descriptor's `providers()`. */
1387
+ const PgWarmProvider = () => Provider.effect(PgWarm, Effect.succeed(pgWarmProviderService));
1388
+ /**
1389
+ * One Database per module-provisioned postgres resource — `id` is the
1390
+ * module provision id, so a resource shared by several consumers is created
1391
+ * exactly once.
1392
+ */
1393
+ function postgresDescriptor(o) {
1394
+ const lowering = ({ id, application }) => Effect.gen(function* () {
1395
+ validateName(id, "resource name (from provision id)");
1396
+ const db = yield* Database(`${id}-db`, {
1397
+ projectId: projectIdOf(application),
1398
+ name: id,
1399
+ region: o.region ?? "us-east-1",
1400
+ ...o.branchId !== void 0 ? { branchId: o.branchId } : {}
1401
+ });
1402
+ const conn = yield* Connection(`${id}-conn`, {
1403
+ databaseId: db.id,
1404
+ name: id
1405
+ });
1406
+ const url = Output.map(conn.connectionString, (value) => Redacted.value(value));
1407
+ return {
1408
+ outputs: { url: (yield* PgWarm(`${id}-warm`, { url })).url },
1409
+ entities: [{
1410
+ kind: "postgres-database",
1411
+ id: db.id
1412
+ }]
1413
+ };
1414
+ });
1415
+ return Object.assign(lowering, { kind: "resource" });
1416
+ }
1417
+ /**
1418
+ * Resolves a `pnPostgres` resource's `prisma-next.config.ts` path to the
1419
+ * on-disk migrations directory the control client's `migrate`/`dbInit` needs
1420
+ * (ADR-0022, slice 2). Deploy-time only: loads PN's config (via c12) and
1421
+ * applies PN's own convention — `migrations.dir`, or the default `migrations/`,
1422
+ * relative to the config file's directory (mirrors the CLI's
1423
+ * `resolveMigrationPaths`). Imported by `control.ts` + tests, never by
1424
+ * `index.ts` / the `./prisma-next` authoring entry.
1425
+ *
1426
+ * `pathe` (not `node:path`) does the path work so the shipped source carries no
1427
+ * `node:` import — the same discipline `control.ts` already follows by
1428
+ * delegating fs/tar to `@internal/lowering` (invariant 5).
1429
+ */
1430
+ /** The absolute migrations directory PN reads authored migration packages from. */
1431
+ async function resolveMigrationsDir(configPath) {
1432
+ return resolve(configPath, "..", (await loadConfig(configPath)).migrations?.dir ?? "migrations");
1433
+ }
1434
+ /**
1435
+ * The Prisma Next migration step of the deploy lowering (ADR-0022, slice 2) —
1436
+ * the safety-critical decision that brings a live database to a target REF
1437
+ * using ONLY Prisma Next's authored migrations.
1438
+ *
1439
+ * Deploy-time only: this module imports `@prisma-next/postgres/control` (which
1440
+ * transitively pulls PN's control/migration machinery + `pg`). It is imported
1441
+ * by the deploy descriptors and this package's tests, NEVER by `index.ts` / the
1442
+ * `./prisma-next` authoring entry — so it never lands in an app runtime bundle
1443
+ * (the index-isolation invariant holds).
1444
+ *
1445
+ * The target is a ref `{ hash, invariants }` — not a bare `storageHash`. A
1446
+ * ref's `invariants` are named postconditions established by `data`-class
1447
+ * migration steps (e.g. a backfill), recorded monotonically on the live
1448
+ * marker. Keying on the hash alone would make a pure data-invariant change an
1449
+ * A→A self-edge the deploy wrongly skips. The decision, given the live marker
1450
+ * and the target ref (see {@link decideMigrationAction}):
1451
+ * - marker at ref.hash AND ref.invariants ⊆ marker.invariants → no-op
1452
+ * - no marker (fresh DB) AND no required invariants → `dbInit`
1453
+ * - otherwise → `migrate`
1454
+ *
1455
+ * `dbInit` is additive-only synthesis — it NEVER runs app-space data steps —
1456
+ * so it is only correct when the ref requires no invariants; a fresh DB whose
1457
+ * target carries invariants goes through `migrate`, which walks the AUTHORED
1458
+ * graph (including the invariant-bearing data migrations) from empty.
1459
+ *
1460
+ * Never `dbUpdate`: synthesized diff-and-apply plans are never run against a
1461
+ * deployed database. A no-authored-path (`MIGRATION_PATH_NOT_FOUND`) or a
1462
+ * runner failure fails the deploy as a typed `PnMigrationError` (not swallowed).
1463
+ * PN applies each migration in its own transaction, so a failed apply is atomic
1464
+ * and resume-safe — the marker and schema are left as the last committed step.
1465
+ */
1466
+ /** A deploy-failing migration error — surfaced, never swallowed. */
1467
+ var PnMigrationError = class extends Error {
1468
+ code;
1469
+ /** PN's structured explanation, when present. */
1470
+ why;
1471
+ constructor(code, summary, why) {
1472
+ super(`prisma-next migrate (${code}): ${summary}`);
1473
+ this.name = "PnMigrationError";
1474
+ this.code = code;
1475
+ this.why = why;
1476
+ }
1477
+ };
1478
+ /**
1479
+ * The target `storageHash` a contract heads to — `contractJson.storage.storageHash`.
1480
+ * Read defensively: `contractJson` crosses the boundary as `unknown`.
1481
+ */
1482
+ function targetStorageHash(contractJson) {
1483
+ if (typeof contractJson === "object" && contractJson !== null && "storage" in contractJson) {
1484
+ const storage = contractJson.storage;
1485
+ if (typeof storage === "object" && storage !== null && "storageHash" in storage) {
1486
+ const hash = storage.storageHash;
1487
+ if (typeof hash === "string" && hash.length > 0) return hash;
1488
+ }
1489
+ }
1490
+ throw new PnMigrationError("INIT_FAILED", "the contract has no storage.storageHash — cannot determine the target schema version");
1491
+ }
1492
+ /**
1493
+ * Resolve the deploy's target ref from the migrations dir.
1494
+ *
1495
+ * - `targetRef` named: read `migrations/app/refs/<name>.json` — fail loudly
1496
+ * (`TARGET_REF_NOT_FOUND`) when the ref doesn't exist or can't be parsed.
1497
+ * - Default: the app space's head. PN synthesizes the app head from the
1498
+ * emitted contract — `{ hash: contract.storage.storageHash, invariants: [] }`
1499
+ * (`contract emit` writes no app-space `refs/head.json` today; extension
1500
+ * spaces have one on disk). When a future PN version does emit one, the
1501
+ * on-disk `head.json` wins — read via `readContractSpaceHeadRef`, exactly
1502
+ * the loader PN's own migrate uses.
1503
+ */
1504
+ async function resolveTargetRef(migrationsDir, contractJson, targetRef) {
1505
+ if (targetRef !== void 0) {
1506
+ const refsDir = spaceRefsDirectory(spaceMigrationDirectory(migrationsDir, APP_SPACE_ID));
1507
+ try {
1508
+ const ref = await readRef(refsDir, targetRef);
1509
+ return {
1510
+ hash: ref.hash,
1511
+ invariants: ref.invariants
1512
+ };
1513
+ } catch (error) {
1514
+ throw new PnMigrationError("TARGET_REF_NOT_FOUND", `targetRef "${targetRef}" could not be read from ${refsDir}`, error instanceof Error ? error.message : String(error));
1515
+ }
1516
+ }
1517
+ const head = await readContractSpaceHeadRef(migrationsDir, APP_SPACE_ID);
1518
+ if (head !== null) return {
1519
+ hash: head.hash,
1520
+ invariants: head.invariants
1521
+ };
1522
+ return {
1523
+ hash: targetStorageHash(contractJson),
1524
+ invariants: []
1525
+ };
1526
+ }
1527
+ /**
1528
+ * The pure migration decision, mirroring PN's own verifier: the database is
1529
+ * AT the target when the marker's hash equals the ref's hash AND every ref
1530
+ * invariant is on the marker (marker invariants are monotonic). `dbInit` is
1531
+ * additive-only synthesis, so it is chosen only for a fresh DB whose
1532
+ * effective required invariants (`ref.invariants − marker.invariants`) are
1533
+ * empty; anything else — different hash, missing invariant (the A→A
1534
+ * data-only self-edge), or a fresh DB with required invariants — walks the
1535
+ * authored graph via `migrate`.
1536
+ */
1537
+ function decideMigrationAction(marker, ref) {
1538
+ const markerInvariants = new Set(marker?.invariants ?? []);
1539
+ const missing = ref.invariants.filter((id) => !markerInvariants.has(id));
1540
+ if (marker !== null && marker.storageHash === ref.hash && missing.length === 0) return "noop";
1541
+ if (marker === null && missing.length === 0) return "init";
1542
+ return "migrate";
1543
+ }
1544
+ /**
1545
+ * Bring the database at `url` to the target ref via PN's authored migrations.
1546
+ * Reads the live marker, decides no-op / init / migrate
1547
+ * ({@link decideMigrationAction}), applies, and throws a typed
1548
+ * {@link PnMigrationError} on a no-path or runner failure. `migrationsDir` is
1549
+ * the on-disk migrations root and `ref` the resolved target
1550
+ * ({@link resolveTargetRef} — both resolved by the lowering, which also keys
1551
+ * the PnMigration resource on them). `refName` (the resource's `targetRef`,
1552
+ * when set) is threaded into `migrate` so PN targets the named ref's hash and
1553
+ * plans an invariant-bearing path.
1554
+ */
1555
+ async function applyPnMigration(opts) {
1556
+ const connection = normalizeSslMode(opts.url);
1557
+ return withConnectionRetry(() => runMigration(connection, opts.contractJson, opts.migrationsDir, opts.ref, opts.refName), { shouldRetry: (error) => !(error instanceof PnMigrationError) });
1558
+ }
1559
+ async function runMigration(connection, contractJson, migrationsDir, ref, refName) {
1560
+ const client = createPostgresControlClient({ connection });
1561
+ await client.connect();
1562
+ try {
1563
+ const marker = await client.readMarker();
1564
+ const markerHashBefore = marker?.storageHash ?? null;
1565
+ const action = decideMigrationAction(marker, ref);
1566
+ if (action === "noop") return {
1567
+ action,
1568
+ targetHash: ref.hash,
1569
+ markerHashBefore
1570
+ };
1571
+ if (action === "init") {
1572
+ const result = await client.dbInit({
1573
+ contract: contractJson,
1574
+ mode: "apply",
1575
+ migrationsDir
1576
+ });
1577
+ if (!result.ok) throw new PnMigrationError("INIT_FAILED", result.failure.summary, result.failure.why);
1578
+ return {
1579
+ action,
1580
+ targetHash: ref.hash,
1581
+ markerHashBefore
1582
+ };
1583
+ }
1584
+ const result = await client.migrate({
1585
+ contract: contractJson,
1586
+ migrationsDir,
1587
+ ...refName !== void 0 ? {
1588
+ refHash: ref.hash,
1589
+ refInvariants: ref.invariants,
1590
+ refName
1591
+ } : {}
1592
+ });
1593
+ if (!result.ok) throw new PnMigrationError(result.failure.code === "MIGRATION_PATH_NOT_FOUND" ? "MIGRATION_PATH_NOT_FOUND" : "RUNNER_FAILED", result.failure.summary, result.failure.why);
1594
+ return {
1595
+ action,
1596
+ targetHash: ref.hash,
1597
+ markerHashBefore
1598
+ };
1599
+ } finally {
1600
+ await client.close();
1601
+ }
1602
+ }
1603
+ /**
1604
+ * The `PnMigration` Alchemy resource (ADR-0022, slice 2 D2) — the migration
1605
+ * step modeled as a tracked resource so it participates in deploy state: keyed
1606
+ * on the target REF identity (`targetHash` + sorted `invariants`), an
1607
+ * unchanged redeploy is an Alchemy-level no-op (on top of the marker read),
1608
+ * and a contract change — or a DATA-ONLY change that adds a ref invariant at
1609
+ * the same hash — re-runs the migration.
1610
+ *
1611
+ * Its provider's `reconcile` receives the RESOLVED props at apply-time — in
1612
+ * particular the concrete DB `url` (a lazy `Output` until the Connection
1613
+ * provisions) — and delegates to the proven `applyPnMigration` decision. The
1614
+ * provider is a standalone `Provider<PnMigration>` layer; the extension
1615
+ * descriptor merges it into its `providers()` (`Layer.merge(Prisma.providers(),
1616
+ * PnMigrationProvider())`), and Alchemy resolves it at apply via a direct
1617
+ * provider-tag lookup (`tryFindProviderByType`) — no change to `@internal/lowering`.
1618
+ *
1619
+ * Deploy-time only: imports `@prisma-next/postgres/control` (via the helper) +
1620
+ * `alchemy`. Imported by `control.ts` and tests, never by `index.ts` / the
1621
+ * `./prisma-next` authoring entry — index isolation holds.
1622
+ */
1623
+ /** The `PnMigration` resource constructor — `yield* PnMigration(id, props)` in the lowering. */
1624
+ const PnMigration = Resource("PrismaNext.Migration");
1625
+ /**
1626
+ * The `PnMigration` provider service. `reconcile` runs for both create and
1627
+ * update (Alchemy's unified lifecycle); `applyPnMigration` is idempotent via
1628
+ * the live marker read, so it is safe to run for either — the marker decides
1629
+ * no-op / init / migrate. A migration has nothing to enumerate (`list` → `[]`)
1630
+ * and nothing to tear down on its own (`delete` → no-op; the DB's own deletion
1631
+ * handles teardown). Exported so tests can drive `reconcile` directly, without
1632
+ * building an Effect layer.
1633
+ */
1634
+ const pnMigrationProviderService = {
1635
+ list: () => Effect.succeed([]),
1636
+ reconcile: ({ news }) => Effect.tryPromise({
1637
+ try: () => applyPnMigration({
1638
+ url: news.url,
1639
+ contractJson: news.contractJson,
1640
+ migrationsDir: news.migrationsDir,
1641
+ ref: {
1642
+ hash: news.targetHash,
1643
+ invariants: news.invariants
1644
+ },
1645
+ ...news.refName !== void 0 ? { refName: news.refName } : {}
1646
+ }),
1647
+ catch: (error) => error
1648
+ }).pipe(Effect.map((outcome) => ({
1649
+ storageHash: outcome.targetHash,
1650
+ invariants: news.invariants
1651
+ }))),
1652
+ delete: () => Effect.void
1653
+ };
1654
+ /** The `PnMigration` provider layer — merged into the extension descriptor's `providers()`. */
1655
+ const PnMigrationProvider = () => Provider.effect(PnMigration, Effect.succeed(pnMigrationProviderService));
1656
+ /**
1657
+ * The migration is a tracked `PnMigration` Alchemy resource keyed on the
1658
+ * target REF identity (hash + sorted invariants): unchanged redeploy is a
1659
+ * no-op, a contract or ref-invariant change re-migrates.
1660
+ */
1661
+ function prismaNextDescriptor(o) {
1662
+ const lowering = ({ id, node, application }) => Effect.gen(function* () {
1663
+ validateName(id, "resource name (from provision id)");
1664
+ const db = yield* Database(`${id}-db`, {
1665
+ projectId: projectIdOf(application),
1666
+ name: id,
1667
+ region: o.region ?? "us-east-1",
1668
+ ...o.branchId !== void 0 ? { branchId: o.branchId } : {}
1669
+ });
1670
+ const conn = yield* Connection(`${id}-conn`, {
1671
+ databaseId: db.id,
1672
+ name: id
1673
+ });
1674
+ const url = Output.map(conn.connectionString, (value) => Redacted.value(value));
1675
+ if (!isPnPostgresResourceNode(node)) throw new Error(`prisma-next lowering received a non-prisma-next node (${id}).`);
1676
+ const contractJson = node.provides.__cmp.contractJson;
1677
+ const migrationsDir = yield* Effect.promise(() => resolveMigrationsDir(node.config));
1678
+ const ref = yield* Effect.promise(() => resolveTargetRef(migrationsDir, contractJson, node.targetRef));
1679
+ const warm = yield* PgWarm(`${id}-warm`, { url });
1680
+ yield* PnMigration(`${id}-migrate`, {
1681
+ url: warm.url,
1682
+ contractJson,
1683
+ migrationsDir,
1684
+ targetHash: ref.hash,
1685
+ invariants: [...ref.invariants].sort(),
1686
+ ...node.targetRef !== void 0 ? { refName: node.targetRef } : {}
1687
+ });
1688
+ return {
1689
+ outputs: { url: warm.url },
1690
+ entities: [{
1691
+ kind: "postgres-database",
1692
+ id: db.id
1693
+ }]
1694
+ };
1695
+ });
1696
+ return Object.assign(lowering, { kind: "resource" });
1697
+ }
1698
+ /**
1699
+ * The `S3Credentials` Alchemy resource (S5) — mints a random SigV4 key pair
1700
+ * ONCE at create and keeps it STABLE across deploys, so an unchanged module
1701
+ * no-ops on redeploy. The pair is generated with the Web Crypto global
1702
+ * (`crypto.getRandomValues` — no `node:` import, matching this package's
1703
+ * runtime-coupling invariant) and persisted in Alchemy state; on every later
1704
+ * apply the provider returns the persisted attributes (`reconcile`'s `output`)
1705
+ * unchanged — the same way the postgres resource keeps a Connection stable.
1706
+ * Rotation is destroy/recreate (a platform ask, not solved here).
1707
+ *
1708
+ * Deploy-time only: imports `alchemy`. Imported by `control.ts` and tests,
1709
+ * never by `index.ts` / the authoring entry.
1710
+ */
1711
+ /** The `S3Credentials` resource constructor — `yield* S3Credentials(id, {})` in the lowering. */
1712
+ const S3Credentials = Resource("PrismaCloud.S3Credentials");
1713
+ function randomBytes(n) {
1714
+ return crypto.getRandomValues(new Uint8Array(n));
1715
+ }
1716
+ function toHexUpper(bytes) {
1717
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
1718
+ }
1719
+ /** A fresh SigV4 key pair: an AKIA-prefixed id and a 40-char base64 secret. */
1720
+ function mintKeyPair() {
1721
+ return {
1722
+ accessKeyId: `AKIA${toHexUpper(randomBytes(8))}`,
1723
+ secretAccessKey: btoa(String.fromCharCode(...randomBytes(30)))
1724
+ };
1725
+ }
1726
+ /**
1727
+ * The `S3Credentials` provider service. `reconcile` runs for create and update;
1728
+ * it returns the persisted `output` when present (a redeploy reuses the stored
1729
+ * pair — the no-op property) and mints a fresh pair only on first create.
1730
+ * Nothing to enumerate (`list` → `[]`) or tear down (`delete` → no-op; the pair
1731
+ * lives only in state). Exported so tests can drive it directly.
1732
+ */
1733
+ const s3CredentialsProviderService = {
1734
+ list: () => Effect.succeed([]),
1735
+ reconcile: ({ output }) => Effect.sync(() => output ?? mintKeyPair()),
1736
+ delete: () => Effect.void
1737
+ };
1738
+ /** The `S3Credentials` provider layer — merged into the extension descriptor's `providers()`. */
1739
+ const S3CredentialsProvider = () => Provider.effect(S3Credentials, Effect.succeed(s3CredentialsProviderService));
1740
+ /**
1741
+ * One `S3Credentials` resource per provisioned credentials node — `id` is the
1742
+ * module provision id, so a pair shared by the storage service is minted once
1743
+ * and kept stable across deploys (the resource's provider preserves it).
1744
+ * `_o` is unused today (the mint needs no region/project) but kept for symmetry
1745
+ * with the other descriptors' signature.
1746
+ */
1747
+ function s3CredentialsDescriptor(_o) {
1748
+ const lowering = ({ id }) => Effect.gen(function* () {
1749
+ const creds = yield* S3Credentials(`${id}-creds`, {});
1750
+ return {
1751
+ outputs: {
1752
+ accessKeyId: creds.accessKeyId,
1753
+ secretAccessKey: creds.secretAccessKey
1754
+ },
1755
+ entities: []
1756
+ };
1757
+ });
1758
+ return Object.assign(lowering, { kind: "resource" });
1759
+ }
1760
+ function s3StoreDescriptor(o) {
1761
+ const base = computeDescriptor(o);
1762
+ return {
1763
+ kind: "service",
1764
+ provision: base.provision,
1765
+ package: base.package,
1766
+ serialize: (ctx, provisioned, config) => Effect.gen(function* () {
1767
+ const serialized = yield* base.serialize(ctx, provisioned, config);
1768
+ const credentials = config.inputs["credentials"] ?? {};
1769
+ const bucket = config.service["bucket"];
1770
+ if (credentials["accessKeyId"] === void 0 || credentials["secretAccessKey"] === void 0 || bucket === void 0) throw new Error("s3-store service must wire a 'credentials' dependency and a 'bucket' param");
1771
+ return {
1772
+ ...serialized,
1773
+ bucket,
1774
+ accessKeyId: credentials["accessKeyId"],
1775
+ secretAccessKey: credentials["secretAccessKey"]
1776
+ };
1777
+ }),
1778
+ deploy: (ctx, provisioned, artifact, serialized) => Effect.gen(function* () {
1779
+ const deployed = yield* base.deploy(ctx, provisioned, artifact, serialized);
1780
+ return {
1781
+ ...deployed,
1782
+ outputs: {
1783
+ ...deployed.outputs,
1784
+ bucket: serialized.bucket,
1785
+ accessKeyId: serialized.accessKeyId,
1786
+ secretAccessKey: serialized.secretAccessKey
1787
+ }
1788
+ };
1789
+ })
1790
+ };
1791
+ }
1792
+ /**
1793
+ * Deploy preflight (ADR-0029, extended for env-sourced params): before Alchemy
1794
+ * runs, verify every secret binding AND every env-sourced param binding in the
1795
+ * app's manifests (each a platform env-var NAME) exists on Prisma Cloud for
1796
+ * the target stage. A literal-bound param never touches the platform — only
1797
+ * `envParam(...)` sources are checked here.
1798
+ * A name absent on the platform but present in the deploy shell is provisioned
1799
+ * via a direct Management API POST — NEVER an Alchemy resource, so the value
1800
+ * never lands in hosted deploy state. A name absent from both fails the deploy,
1801
+ * listing exactly what is missing and where to set it.
1802
+ *
1803
+ * Control-plane only (imported by control.ts → prisma-composer.config.ts); runs
1804
+ * in the CLI parent, so it builds its own Management API client from env — the
1805
+ * same credential path `ensureContainers` uses.
1806
+ */
1807
+ /** production for the default stage; preview for a named stage — matching how the pack writes config rows. */
1808
+ const classFor = (branchId) => branchId === void 0 ? "production" : "preview";
1809
+ /**
1810
+ * One page of the env-var list. The query is `blindCast` to `never` because
1811
+ * openapi-fetch types this path's query as `never` (an SDK path/operation
1812
+ * mismatch); that same workaround defeats the client's response-type inference,
1813
+ * so the result is projected to the small shape we actually read.
1814
+ */
1815
+ async function listEnvVars(client, query) {
1816
+ return blindCast(await client.GET("/v1/environment-variables", { params: { query: blindCast(query) } }));
1817
+ }
1818
+ async function existsOnPlatform(client, projectId, branchId, key) {
1819
+ const cls = classFor(branchId);
1820
+ const visible = (row) => branchId === void 0 || row.branchId === null || row.branchId === branchId;
1821
+ let cursor = null;
1822
+ do {
1823
+ const res = await listEnvVars(client, cursor === null ? {
1824
+ projectId,
1825
+ class: cls,
1826
+ key
1827
+ } : {
1828
+ projectId,
1829
+ class: cls,
1830
+ key,
1831
+ cursor
1832
+ });
1833
+ if (res.error !== void 0) throw listFailedError(key, res.error);
1834
+ const page = res.data;
1835
+ if (page === void 0) return false;
1836
+ if (page.data.some(visible)) return true;
1837
+ cursor = page.pagination.hasMore ? page.pagination.nextCursor : null;
1838
+ } while (cursor !== null);
1839
+ return false;
1840
+ }
1841
+ /**
1842
+ * Provision `key`=`value` directly via the Management API for the target
1843
+ * stage's scope (a production template for the default stage; a preview branch
1844
+ * override for a named stage — the same scope the pack writes config rows to,
1845
+ * EnvironmentVariable.ts). A 409 means a concurrent deploy already provisioned
1846
+ * it — tolerated. The value is never logged.
1847
+ */
1848
+ async function fillMissing(client, input, key, value) {
1849
+ const res = await client.POST("/v1/environment-variables", { body: {
1850
+ projectId: input.projectId,
1851
+ class: classFor(input.branchId),
1852
+ key,
1853
+ value,
1854
+ ...input.branchId !== void 0 ? { branchId: input.branchId } : {}
1855
+ } });
1856
+ if (res.error !== void 0 && res.response.status !== 409) throw fillFailedError(key, res.error);
1857
+ }
1858
+ const tokenRequiredError$1 = () => /* @__PURE__ */ new Error("environment variable PRISMA_SERVICE_TOKEN is required for deploy preflight.");
1859
+ const listFailedError = (key, error) => /* @__PURE__ */ new Error(`deploy preflight: Prisma Management API error listing "${key}": ${JSON.stringify(error)}.`);
1860
+ const fillFailedError = (key, error) => /* @__PURE__ */ new Error(`deploy preflight: failed to provision "${key}" from the deploy shell: ${JSON.stringify(error)}.`);
1861
+ function missingError(missing, input) {
1862
+ const scope = input.branchId === void 0 ? "the production class (project-level template)" : `the preview class of stage "${input.stage ?? input.branchId}" (branch override or template)`;
1863
+ const lines = missing.map((m) => ` - ${m.name} (required by service "${m.serviceAddress}")`);
1864
+ return /* @__PURE__ */ new Error(`Deploy preflight failed — ${missing.length} env var(s) (secret or env-sourced param) are not provisioned on Prisma Cloud for ${scope}, and are absent from the deploy shell:\n${lines.join("\n")}\n\nSet each in the deploy shell environment (the CLI will provision it on deploy), or create it on the platform (Prisma Console or the Management API) in ${scope}.`);
1865
+ }
1866
+ async function managementClient$1() {
1867
+ if ((process.env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) throw tokenRequiredError$1();
1868
+ return Effect.runPromise(Effect.gen(function* () {
1869
+ return yield* ManagementClient;
1870
+ }).pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv())))));
1871
+ }
1872
+ /**
1873
+ * The Prisma Cloud extension's `preflight`. Aggregates the target-agnostic
1874
+ * manifests (core's `provisionManifest` for secrets, `paramManifest` filtered
1875
+ * to env-sourced bindings for params), checks each pointer name against the
1876
+ * platform, fills from the shell where possible, and fails loudly on anything
1877
+ * absent from both. Accepts an injected client for tests; otherwise builds one
1878
+ * from env.
1879
+ */
1880
+ async function runPreflight(input, deps) {
1881
+ const names = /* @__PURE__ */ new Map();
1882
+ for (const binding of provisionManifest(input.graph)) {
1883
+ const name = secretName(binding);
1884
+ if (!names.has(name)) names.set(name, {
1885
+ name,
1886
+ serviceAddress: binding.serviceAddress
1887
+ });
1888
+ }
1889
+ for (const binding of paramManifest(input.graph)) {
1890
+ if (!isEnvParamSource(binding.binding)) continue;
1891
+ const name = paramName(binding);
1892
+ if (!names.has(name)) names.set(name, {
1893
+ name,
1894
+ serviceAddress: binding.serviceAddress
1895
+ });
1896
+ }
1897
+ if (names.size === 0) return;
1898
+ const client = deps?.client ?? await managementClient$1();
1899
+ const missing = [];
1900
+ for (const meta of names.values()) {
1901
+ if (await existsOnPlatform(client, input.projectId, input.branchId, meta.name)) continue;
1902
+ const shellValue = process.env[meta.name];
1903
+ if (shellValue !== void 0 && shellValue.length > 0) {
1904
+ await fillMissing(client, input, meta.name, shellValue);
1905
+ continue;
1906
+ }
1907
+ missing.push(meta);
1908
+ }
1909
+ if (missing.length > 0) throw missingError(missing, input);
1910
+ }
1911
+ const tokenRequiredError = () => /* @__PURE__ */ new Error("environment variable PRISMA_SERVICE_TOKEN is required for destroy teardown.");
1912
+ async function managementClient() {
1913
+ if ((process.env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) throw tokenRequiredError();
1914
+ return Effect.runPromise(Effect.gen(function* () {
1915
+ return yield* ManagementClient;
1916
+ }).pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv())))));
1917
+ }
1918
+ /**
1919
+ * The Prisma Cloud extension's `teardown`. Removes the stage's state database,
1920
+ * with failure handling that differs by stage because the consequences do:
1921
+ *
1922
+ * - **Named stage: throw.** The Branch delete that follows would fail anyway —
1923
+ * the platform refuses a Branch that still has a database attached — so
1924
+ * failing here names the actual cause instead of a confusing symptom.
1925
+ * - **Production: warn and continue.** Nothing blocks the Project delete on
1926
+ * this; removing the database only stops production's state outliving
1927
+ * production and holding a quota slot. That is a cleanup step, and a cleanup
1928
+ * step must not fail the command.
1929
+ *
1930
+ * Accepts an injected client and ownership verifier for tests; otherwise
1931
+ * builds a client from env and verifies against the real database.
1932
+ */
1933
+ async function runTeardown(input, deps) {
1934
+ const isNamedStage = input.branchId !== void 0;
1935
+ try {
1936
+ const client = deps?.client ?? await managementClient();
1937
+ await Effect.runPromise(deleteStateDatabaseWith({
1938
+ projectId: input.projectId,
1939
+ ...input.branchId !== void 0 ? { branchId: input.branchId } : {}
1940
+ }, deps?.verify ?? verifyOwnership).pipe(Effect.provideService(ManagementClient, client)));
1941
+ } catch (error) {
1942
+ const reason = error instanceof Error ? error.message : String(error);
1943
+ if (isNamedStage) throw new Error(`Failed to delete the deploy-state database: ${reason}`);
1944
+ console.warn(`Could not remove production's deploy-state database: ${reason}`);
1945
+ }
1946
+ }
1947
+ /** The Prisma Cloud–hosted deploy state store; its implementation lives in @internal/lowering. */
1948
+ /**
1949
+ * ADR-0031's registered provisioner for RPC_PEER_KEY: mints one `ServiceKey`
1950
+ * resource per edge (ADR-0030) and forwards its value as the opaque ref core
1951
+ * writes into the consumer's `serviceKey` param. The resource id keeps the
1952
+ * `servicekey-${edgeId}` scheme byte-identical to slice 2's, so an existing
1953
+ * deploy's keys are found, not re-minted. Defined here, not in service-keys.ts:
1954
+ * that module is also reachable from the runtime/authoring side, which must
1955
+ * never import `@internal/lowering` or `effect`.
1956
+ */
1957
+ const serviceKeyProvisioner = { provision: (edge) => Effect.gen(function* () {
1958
+ return (yield* ServiceKey(`servicekey-${edge.edgeId}`, {})).value;
1959
+ }) };
1960
+ const KNOWN_REGION_SET = new Set(COMPUTE_REGIONS);
1961
+ function isComputeRegion(value) {
1962
+ return KNOWN_REGION_SET.has(value);
1963
+ }
1964
+ /** Prisma.providers()'s ProviderCollection doesn't structurally unify with Alchemy's inferred providers Layer (a @internal/lowering typings gap); it satisfies it at runtime. */
1965
+ function asProvidersLayer(layer) {
1966
+ return layer;
1967
+ }
1968
+ /**
1969
+ * Resolves the factory's env-or-option inputs, failing fast with the exact
1970
+ * variable name. `projectId`/`branchId` aren't required here — `prismaCloud()`
1971
+ * also runs in the CLI parent, before they're set; the required check lives in `application.provision`.
1972
+ */
1973
+ function resolveOptions(opts) {
1974
+ const workspaceId = opts.workspaceId ?? process.env["PRISMA_WORKSPACE_ID"];
1975
+ if (workspaceId === void 0 || workspaceId.length === 0) throw new Error("prismaCloud(): environment variable PRISMA_WORKSPACE_ID is required.");
1976
+ const projectId = process.env["PRISMA_PROJECT_ID"] || void 0;
1977
+ const branchId = process.env["PRISMA_BRANCH_ID"] || void 0;
1978
+ if (opts.region !== void 0) return {
1979
+ workspaceId,
1980
+ region: opts.region,
1981
+ projectId,
1982
+ branchId
1983
+ };
1984
+ const region = process.env["PRISMA_REGION"];
1985
+ if (region === void 0 || region.length === 0) return {
1986
+ workspaceId,
1987
+ projectId,
1988
+ branchId
1989
+ };
1990
+ if (!isComputeRegion(region)) throw new Error(`prismaCloud(): environment variable PRISMA_REGION="${region}" is not a known region (expected one of: ${COMPUTE_REGIONS.join(", ")}).`);
1991
+ return {
1992
+ workspaceId,
1993
+ region,
1994
+ projectId,
1995
+ branchId
1996
+ };
1997
+ }
1998
+ /** The Prisma Cloud extension descriptor — `prisma-composer.config.ts` lists it under `extensions`. */
1999
+ const prismaCloud = (opts = {}) => {
2000
+ const o = resolveOptions(opts);
2001
+ return {
2002
+ id: "@prisma/composer-prisma-cloud",
2003
+ providers: () => asProvidersLayer(Layer.mergeAll(providers(), PgWarmProvider(), PnMigrationProvider(), S3CredentialsProvider(), ServiceKeyProvider())),
2004
+ preflight: (input) => runPreflight(input),
2005
+ teardown: (input) => runTeardown(input),
2006
+ application: { provision: () => Effect.gen(function* () {
2007
+ const projectId = o.projectId;
2008
+ if (projectId === void 0 || projectId.length === 0) throw new Error("prismaCloud(): environment variable PRISMA_PROJECT_ID is required (the CLI sets it — deploy via `prisma-composer deploy`).");
2009
+ for (const key of ["DATABASE_URL", "DATABASE_URL_POOLED"]) yield* EnvironmentVariable(`${key}-poison`, {
2010
+ projectId,
2011
+ key,
2012
+ value: "-",
2013
+ class: o.branchId ? "preview" : "production",
2014
+ ...o.branchId !== void 0 ? { branchId: o.branchId } : {}
2015
+ });
2016
+ return { projectId };
2017
+ }) },
2018
+ provisions: /* @__PURE__ */ new Map([[RPC_PEER_KEY, serviceKeyProvisioner]]),
2019
+ nodes: {
2020
+ postgres: postgresDescriptor(o),
2021
+ "prisma-next": prismaNextDescriptor(o),
2022
+ compute: computeDescriptor(o),
2023
+ credentials: s3CredentialsDescriptor(o),
2024
+ "s3-store": s3StoreDescriptor(o)
2025
+ }
2026
+ };
2027
+ };
2028
+ //#endregion
2029
+ export { prismaCloud, prismaState };
2030
+
2031
+ //# sourceMappingURL=control.mjs.map