@prisma/composer-prisma-cloud 0.2.0-dev.12 → 0.2.0-dev.13

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 (61) hide show
  1. package/dist/buckets-main.mjs +795 -0
  2. package/dist/buckets-main.mjs.map +1 -0
  3. package/dist/compute-main.mjs +532 -0
  4. package/dist/compute-main.mjs.map +1 -0
  5. package/dist/control.mjs +41 -1257
  6. package/dist/control.mjs.map +1 -1
  7. package/dist/cron/index.mjs +2 -3
  8. package/dist/cron/index.mjs.map +1 -1
  9. package/dist/cron/scheduler-entrypoint.mjs.map +1 -1
  10. package/dist/cron/scheduler-service.mjs +2 -3
  11. package/dist/cron/scheduler-service.mjs.map +1 -1
  12. package/dist/email/email-entrypoint.mjs.map +1 -1
  13. package/dist/email/email-service.mjs +2 -3
  14. package/dist/email/email-service.mjs.map +1 -1
  15. package/dist/email/index.mjs +2 -3
  16. package/dist/email/index.mjs.map +1 -1
  17. package/dist/email/testing.mjs.map +1 -1
  18. package/dist/get-port-BYnpbW5H.mjs +111 -0
  19. package/dist/get-port-BYnpbW5H.mjs.map +1 -0
  20. package/dist/index.mjs +4 -2
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/local-target.d.mts +12 -0
  23. package/dist/local-target.d.mts.map +1 -0
  24. package/dist/local-target.mjs +6129 -0
  25. package/dist/local-target.mjs.map +1 -0
  26. package/dist/param-BTzY0ne5-CW6ojZ3E.mjs +66 -0
  27. package/dist/param-BTzY0ne5-CW6ojZ3E.mjs.map +1 -0
  28. package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs +79 -0
  29. package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs.map +1 -0
  30. package/dist/postgres-main.mjs +402 -0
  31. package/dist/postgres-main.mjs.map +1 -0
  32. package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs +1252 -0
  33. package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs.map +1 -0
  34. package/dist/{prisma-next-BvBwGCIt-CSauMX4l.mjs → prisma-next-BvBwGCIt-DssgnctU.mjs} +3 -78
  35. package/dist/prisma-next-BvBwGCIt-DssgnctU.mjs.map +1 -0
  36. package/dist/prisma-next.mjs +1 -1
  37. package/dist/{provisioned-edges-B_XS1Mz--NFJgcXK7.mjs → provisioned-edges-C1wSO3cx-YC5C19f9.mjs} +5 -65
  38. package/dist/provisioned-edges-C1wSO3cx-YC5C19f9.mjs.map +1 -0
  39. package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs +47 -0
  40. package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs.map +1 -0
  41. package/dist/segments-NpKN-46R-B01DmCqy.mjs +1441 -0
  42. package/dist/segments-NpKN-46R-B01DmCqy.mjs.map +1 -0
  43. package/dist/{serializer-D8_84XWO-DA2B6YbX.mjs → serializer-CJiOhF2d-DJUjQj1i.mjs} +4 -44
  44. package/dist/serializer-CJiOhF2d-DJUjQj1i.mjs.map +1 -0
  45. package/dist/storage/index.mjs +2 -3
  46. package/dist/storage/index.mjs.map +1 -1
  47. package/dist/storage/storage-entrypoint.mjs.map +1 -1
  48. package/dist/storage/storage-service.mjs +2 -3
  49. package/dist/storage/storage-service.mjs.map +1 -1
  50. package/dist/streams/index.mjs +2 -3
  51. package/dist/streams/index.mjs.map +1 -1
  52. package/dist/streams/streams-entrypoint.mjs.map +1 -1
  53. package/dist/streams/streams-service.mjs +2 -3
  54. package/dist/streams/streams-service.mjs.map +1 -1
  55. package/dist/testing.mjs +1 -1
  56. package/dist/testing.mjs.map +1 -1
  57. package/package.json +21 -15
  58. package/src/exports/local-target.ts +1 -0
  59. package/dist/prisma-next-BvBwGCIt-CSauMX4l.mjs.map +0 -1
  60. package/dist/provisioned-edges-B_XS1Mz--NFJgcXK7.mjs.map +0 -1
  61. package/dist/serializer-D8_84XWO-DA2B6YbX.mjs.map +0 -1
package/dist/control.mjs CHANGED
@@ -1,746 +1,22 @@
1
- import { a as encode, c as paramEntries, d as secretPointerRows, n as configKey, o as encodeParamPointer, u as secretName } from "./serializer-D8_84XWO-DA2B6YbX.mjs";
2
- import { c as paramName, l as provisionedEdges, n as SELF_ORIGIN, o as isEnvParamSource, r as STREAMS_API_KEY, s as paramBindingFor, t as RESERVED_PROVIDER_PARAMS } from "./provisioned-edges-B_XS1Mz--NFJgcXK7.mjs";
3
- import { a as normalizeSslMode, n as isPnPostgresResourceNode, o as withConnectionRetry } from "./prisma-next-BvBwGCIt-CSauMX4l.mjs";
4
- import { isParamSource, paramManifest, provisionManifest } from "@prisma/composer";
1
+ import { a as encode, l as secretPointerRows, n as configKey, o as encodeParamPointer, s as paramEntries } from "./serializer-CJiOhF2d-DJUjQj1i.mjs";
2
+ import { a as provisionedEdges, n as SELF_ORIGIN, r as STREAMS_API_KEY, t as RESERVED_PROVIDER_PARAMS } from "./provisioned-edges-C1wSO3cx-YC5C19f9.mjs";
3
+ import { i as paramName, r as paramBindingFor } from "./param-BTzY0ne5-CW6ojZ3E.mjs";
4
+ import { A as PrismaApiError, C as EnvironmentVariable, D as Bucket, E as packageComputeArtifact, M as callVoid, N as fromEnv, O as BucketKey, P as layer, S as Deployment, T as ServiceKeyProvider, _ as Connection, a as PnMigrationProvider, b as COMPUTE_REGIONS, c as S3CredentialsProvider, f as prismaCloudContainerOf, g as providers, i as PnMigration, j as call, k as ManagementClient, l as collectPreflightNames, n as PgWarm, p as resolveTargetRef, r as PgWarmProvider, s as S3Credentials, t as PRISMA_CLOUD_EXTENSION_ID, u as containerDescriptor, v as Database, w as ServiceKey, x as ComputeService } from "./preflight-names-BPL-qsZF-BfoRgbgb.mjs";
5
+ import { n as isPnPostgresResourceNode } from "./prisma-next-BvBwGCIt-DssgnctU.mjs";
6
+ import { isParamSource } from "@prisma/composer";
5
7
  import { blindCast } from "@prisma/composer/casts";
6
8
  import { RPC_PEER_KEY } from "@prisma/composer/service-rpc";
7
- import pg from "pg";
8
- import { createManagementApiClient } from "@prisma/management-api-sdk";
9
- import * as Context from "effect/Context";
10
9
  import * as Effect from "effect/Effect";
11
10
  import * as Layer from "effect/Layer";
12
11
  import * as Redacted from "effect/Redacted";
13
- import * as Config$1 from "effect/Config";
14
12
  import * as Data from "effect/Data";
15
- import * as Provider from "alchemy/Provider";
16
- import { Resource, Stack } from "alchemy";
13
+ import { Stack } from "alchemy";
17
14
  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
15
  import postgres from "postgres";
24
16
  import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveStateRecursive } from "alchemy/State";
25
17
  import * as Output from "alchemy/Output";
26
18
  import { loadConfig } from "@prisma-next/config-loader";
27
19
  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-CJM0E6rj.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/buckets.mjs
72
- /** A Prisma **Object Store bucket** inside a project. */
73
- const Bucket = Resource("Prisma.Bucket");
74
- const BucketProvider = () => Provider.effect(Bucket, Effect.gen(function* () {
75
- const client = yield* ManagementClient;
76
- return {
77
- stables: ["id"],
78
- list: () => Effect.succeed([]),
79
- reconcile: Effect.fn(function* ({ news, output }) {
80
- const observed = output?.id ? yield* callOptional(() => client.GET("/v1/buckets/{bucketId}", { params: { path: { bucketId: output.id } } })) : void 0;
81
- if (observed) return {
82
- id: observed.data.id,
83
- name: observed.data.name
84
- };
85
- const created = yield* call(() => client.POST("/v1/buckets", { body: {
86
- projectId: news.projectId,
87
- name: news.name,
88
- ...news.branchId !== void 0 ? { branchId: news.branchId } : {}
89
- } }));
90
- return {
91
- id: created.data.id,
92
- name: created.data.name
93
- };
94
- }),
95
- delete: Effect.fn(function* ({ output }) {
96
- yield* callVoid(() => client.DELETE("/v1/buckets/{bucketId}", { params: { path: { bucketId: output.id } } }));
97
- }),
98
- read: Effect.fn(function* ({ output }) {
99
- if (!output?.id) return void 0;
100
- const b = yield* callOptional(() => client.GET("/v1/buckets/{bucketId}", { params: { path: { bucketId: output.id } } }));
101
- return b ? {
102
- id: b.data.id,
103
- name: b.data.name
104
- } : void 0;
105
- })
106
- };
107
- }));
108
- /** A **bucket access key** for a Prisma Object Store bucket — yields the S3 credentials. */
109
- const BucketKey = Resource("Prisma.BucketKey");
110
- const BucketKeyProvider = () => Provider.effect(BucketKey, Effect.gen(function* () {
111
- const client = yield* ManagementClient;
112
- return {
113
- stables: [
114
- "id",
115
- "bucketId",
116
- "secretAccessKey",
117
- "accessKeyId",
118
- "endpoint",
119
- "bucketName"
120
- ],
121
- list: () => Effect.succeed([]),
122
- reconcile: Effect.fn(function* ({ news, output }) {
123
- if (output?.id) return output;
124
- const created = yield* call(() => client.POST("/v1/buckets/{bucketId}/keys", {
125
- params: { path: { bucketId: news.bucketId } },
126
- body: {
127
- name: news.name,
128
- role: news.role
129
- }
130
- }));
131
- return {
132
- id: created.data.id,
133
- bucketId: news.bucketId,
134
- accessKeyId: created.data.accessKeyId,
135
- secretAccessKey: Redacted.make(created.data.secretAccessKey),
136
- endpoint: created.data.endpoint,
137
- bucketName: created.data.bucketName
138
- };
139
- }),
140
- delete: Effect.fn(function* ({ output }) {
141
- yield* callVoid(() => client.DELETE("/v1/buckets/{bucketId}/keys/{keyId}", { params: { path: {
142
- bucketId: output.bucketId,
143
- keyId: output.id
144
- } } }));
145
- })
146
- };
147
- }));
148
- //#endregion
149
- //#region ../../1-prisma-cloud/0-lowering/lowering/dist/compute.mjs
150
- /**
151
- * Stopping a deployment before the app that owns it can be
152
- * deleted is asynchronous on the platform's side: DELETE can 409 with this
153
- * message while the deployment is still winding down. Retrying blindly on
154
- * every API error would mask real failures (bad auth, a genuinely conflicting
155
- * state, etc.), so this only matches the platform's specific "not delete-safe
156
- * yet" wording — everything else fails immediately, as before.
157
- */
158
- const isDeleteNotSafeYet = (error) => error.message.includes("did not reach a delete-safe state");
159
- /**
160
- * Backs off exponentially from 2s, capped at 5 minutes total — long enough
161
- * for the platform to finish stopping the deployment, short enough to still
162
- * fail loudly (rather than hang forever) if it never does.
163
- */
164
- const deleteSafeRetrySchedule = Schedule.both(Schedule.exponential("2 seconds", 2), Schedule.during("5 minutes"));
165
- /** Every region Prisma Compute serves — the runtime source of truth; `ComputeRegion` is derived from it so the two can never drift. */
166
- const COMPUTE_REGIONS = [
167
- "us-east-1",
168
- "us-west-1",
169
- "eu-west-3",
170
- "eu-central-1",
171
- "ap-northeast-1",
172
- "ap-southeast-1"
173
- ];
174
- /** A Prisma **Compute service** — the stable app identity behind a project. */
175
- const ComputeService = Resource("Prisma.ComputeService");
176
- const ComputeServiceProvider = () => Provider.effect(ComputeService, Effect.gen(function* () {
177
- const client = yield* ManagementClient;
178
- return {
179
- stables: ["id"],
180
- list: () => Effect.succeed([]),
181
- reconcile: Effect.fn(function* ({ news, output }) {
182
- const observed = output?.id ? yield* callOptional(() => client.GET("/v1/apps/{appId}", { params: { path: { appId: output.id } } })) : void 0;
183
- if (observed) return {
184
- id: observed.data.id,
185
- name: observed.data.name,
186
- endpointDomain: observed.data.appEndpointDomain
187
- };
188
- const created = yield* call(() => client.POST("/v1/apps", { body: {
189
- displayName: news.name,
190
- projectId: news.projectId,
191
- ...news.region && { regionId: news.region },
192
- ...news.branchId !== void 0 && { branchId: news.branchId }
193
- } }));
194
- return {
195
- id: created.data.id,
196
- name: created.data.name,
197
- endpointDomain: created.data.appEndpointDomain
198
- };
199
- }),
200
- delete: Effect.fn(function* ({ output }) {
201
- yield* callVoid(() => client.DELETE("/v1/apps/{appId}", { params: { path: { appId: output.id } } })).pipe(Effect.retry({
202
- schedule: deleteSafeRetrySchedule,
203
- while: isDeleteNotSafeYet
204
- }));
205
- }),
206
- read: Effect.fn(function* ({ output }) {
207
- if (!output?.id) return void 0;
208
- const s = yield* callOptional(() => client.GET("/v1/apps/{appId}", { params: { path: { appId: output.id } } }));
209
- return s ? {
210
- id: s.data.id,
211
- name: s.data.name,
212
- endpointDomain: s.data.appEndpointDomain
213
- } : void 0;
214
- })
215
- };
216
- }));
217
- /**
218
- * A **deployment** of a Prisma app — creates a deployment, uploads
219
- * its artifact, starts the VM, waits for it to run, then promotes it to the
220
- * app's stable endpoint.
221
- */
222
- const Deployment = Resource("Prisma.Deployment");
223
- const DeploymentProvider = () => Provider.effect(Deployment, Effect.gen(function* () {
224
- const client = yield* ManagementClient;
225
- 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({
226
- status: 409,
227
- message: `deployment ${deploymentId} is ${v.data.status}, not running`
228
- }))), Effect.retry(Schedule.both(Schedule.spaced("2 seconds"), Schedule.during("2 minutes"))));
229
- return {
230
- stables: [],
231
- list: () => Effect.succeed([]),
232
- reconcile: Effect.fn(function* ({ news }) {
233
- const created = yield* call(() => client.POST("/v1/apps/{appId}/deployments", {
234
- params: { path: { appId: news.computeServiceId } },
235
- body: news.port !== void 0 ? { portMapping: { http: news.port } } : {}
236
- }));
237
- const deploymentId = created.data.id;
238
- if (created.data.uploadUrl) {
239
- const uploadUrl = created.data.uploadUrl;
240
- const artifact = yield* Effect.try({
241
- try: () => fs.readFileSync(news.artifactPath),
242
- catch: (cause) => new PrismaApiError({
243
- status: 0,
244
- message: `failed to read artifact ${news.artifactPath}: ${String(cause)}`
245
- })
246
- });
247
- yield* Effect.tryPromise({
248
- try: async () => {
249
- const res = await fetch(uploadUrl, {
250
- method: "PUT",
251
- body: artifact
252
- });
253
- if (!res.ok) throw new PrismaApiError({
254
- status: res.status,
255
- message: `artifact upload failed: ${res.status} ${res.statusText}`
256
- });
257
- },
258
- catch: (cause) => cause instanceof PrismaApiError ? cause : new PrismaApiError({
259
- status: 0,
260
- message: String(cause)
261
- })
262
- });
263
- }
264
- yield* call(() => client.POST("/v1/deployments/{deploymentId}/start", { params: { path: { deploymentId } } }));
265
- yield* waitForRunning(deploymentId);
266
- const deployedUrl = (yield* call(() => client.POST("/v1/apps/{appId}/promote", {
267
- params: { path: { appId: news.computeServiceId } },
268
- body: { deploymentId }
269
- }))).data.appEndpointDomain;
270
- return {
271
- deploymentId,
272
- ...deployedUrl !== void 0 && { deployedUrl }
273
- };
274
- }),
275
- delete: Effect.fn(function* () {}),
276
- read: Effect.fn(function* ({ output }) {
277
- if (!output?.deploymentId) return void 0;
278
- const v = yield* callOptional(() => client.GET("/v1/deployments/{deploymentId}", { params: { path: { deploymentId: output.deploymentId } } }));
279
- return v ? {
280
- deploymentId: v.data.id,
281
- ...v.data.previewDomain && { deployedUrl: v.data.previewDomain }
282
- } : void 0;
283
- })
284
- };
285
- }));
286
- /**
287
- * A project-scoped **environment variable** that Compute injects into the
288
- * project's services from their attached branch (e.g. wiring one module's URL into
289
- * another).
290
- */
291
- const EnvironmentVariable = Resource("Prisma.EnvironmentVariable");
292
- const EnvironmentVariableProvider = () => Provider.effect(EnvironmentVariable, Effect.gen(function* () {
293
- const client = yield* ManagementClient;
294
- return {
295
- stables: ["id"],
296
- list: () => Effect.succeed([]),
297
- reconcile: Effect.fn(function* ({ news, output }) {
298
- const cls = news.class ?? "production";
299
- let id = output?.id;
300
- if (id !== void 0) {
301
- const priorId = id;
302
- if (!(yield* callOptional(() => client.GET("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: priorId } } })))) id = void 0;
303
- }
304
- if (id === void 0) {
305
- const matchId = (yield* call(() => client.GET("/v1/environment-variables", { params: { query: {
306
- projectId: news.projectId,
307
- class: cls,
308
- key: news.key
309
- } } }))).data?.[0]?.id;
310
- if (matchId !== void 0) {
311
- 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.`);
312
- id = matchId;
313
- }
314
- }
315
- if (id !== void 0) {
316
- const targetId = id;
317
- yield* call(() => client.PATCH("/v1/environment-variables/{envVarId}", {
318
- params: { path: { envVarId: targetId } },
319
- body: { value: news.value }
320
- }));
321
- return {
322
- id,
323
- key: news.key
324
- };
325
- }
326
- const created = yield* call(() => client.POST("/v1/environment-variables", { body: {
327
- projectId: news.projectId,
328
- class: cls,
329
- key: news.key,
330
- value: news.value,
331
- ...news.branchId ? { branchId: news.branchId } : {}
332
- } }));
333
- return {
334
- id: created.data.id,
335
- key: created.data.key
336
- };
337
- }),
338
- delete: Effect.fn(function* ({ output }) {
339
- yield* callVoid(() => client.DELETE("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: output.id } } }));
340
- }),
341
- read: Effect.fn(function* ({ output }) {
342
- if (!output?.id) return void 0;
343
- const v = yield* callOptional(() => client.GET("/v1/environment-variables/{envVarId}", { params: { path: { envVarId: output.id } } }));
344
- return v ? {
345
- id: v.data.id,
346
- key: v.data.key
347
- } : void 0;
348
- })
349
- };
350
- }));
351
- /**
352
- * Assembles a Prisma Compute artifact: the app-built bundle plus the
353
- * extension-printed bootstrap and manifest, tarred and gzipped deterministically
354
- * (fixed mtimes, sorted entry order) so an unchanged service noops on
355
- * redeploy — a rebuild is the only thing that changes the hash. Lives here
356
- * (not in @prisma/composer-prisma-cloud/control) because it needs node:fs/node:zlib,
357
- * which the extension's shipped src may never import (invariant 5).
358
- */
359
- const MANIFEST_VERSION = "1";
360
- /** Finds main.js/main.mjs in a bundle dir when no explicit entry is given. */
361
- function resolveEntry(bundleDir, entry) {
362
- if (entry !== void 0) return entry;
363
- const found = fs.readdirSync(bundleDir).find((f) => /^main\.m?js$/.test(f));
364
- if (found === void 0) throw new Error(`no main.js/main.mjs found in bundle dir ${bundleDir}`);
365
- return found;
366
- }
367
- /** All files under `dir`, as dir-relative POSIX paths, in sorted order. A
368
- * symlink is a hard error: deploy bundles must be flat (ADR-0005), and the
369
- * user's build owns flattening — dereferencing here would relink the tree and
370
- * risk packaging files from outside it. */
371
- function walkFiles(dir) {
372
- const out = [];
373
- const visit = (sub) => {
374
- for (const entry of fs.readdirSync(path.join(dir, sub), { withFileTypes: true })) {
375
- const rel = sub.length > 0 ? `${sub}/${entry.name}` : entry.name;
376
- 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.`);
377
- if (entry.isDirectory()) visit(rel);
378
- else out.push(rel);
379
- }
380
- };
381
- visit("");
382
- return out.sort();
383
- }
384
- function octal(value, length) {
385
- return `${value.toString(8).padStart(length - 1, "0")}\0`;
386
- }
387
- /** Splits a path into ustar's name (<=100 bytes) + prefix (<=155 bytes) fields. */
388
- function splitUstarPath(relPath) {
389
- if (Buffer.byteLength(relPath, "utf8") <= 100) return {
390
- name: relPath,
391
- prefix: ""
392
- };
393
- for (let i = relPath.length - 1; i >= 0; i--) {
394
- if (relPath[i] !== "/") continue;
395
- const prefix = relPath.slice(0, i);
396
- const name = relPath.slice(i + 1);
397
- if (Buffer.byteLength(prefix, "utf8") <= 155 && Buffer.byteLength(name, "utf8") <= 100) return {
398
- name,
399
- prefix
400
- };
401
- }
402
- throw new Error(`path too long for a ustar tar entry: ${relPath}`);
403
- }
404
- function ustarHeader(relPath, size) {
405
- const { name, prefix } = splitUstarPath(relPath);
406
- const buf = Buffer.alloc(512);
407
- buf.write(name, 0, 100, "utf8");
408
- buf.write(octal(420, 8), 100, 8, "utf8");
409
- buf.write(octal(0, 8), 108, 8, "utf8");
410
- buf.write(octal(0, 8), 116, 8, "utf8");
411
- buf.write(octal(size, 12), 124, 12, "utf8");
412
- buf.write(octal(0, 12), 136, 12, "utf8");
413
- buf.write(" ", 148, 8, "utf8");
414
- buf.write("0", 156, 1, "utf8");
415
- buf.write("ustar\0", 257, 6, "utf8");
416
- buf.write("00", 263, 2, "utf8");
417
- buf.write(prefix, 345, 155, "utf8");
418
- let sum = 0;
419
- for (const b of buf) sum += b;
420
- buf.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, 8, "utf8");
421
- return buf;
422
- }
423
- function createDeterministicTarGz(entries) {
424
- const sorted = [...entries].sort((a, b) => a.relPath.localeCompare(b.relPath));
425
- const chunks = [];
426
- for (const entry of sorted) {
427
- chunks.push(ustarHeader(entry.relPath, entry.content.length));
428
- chunks.push(entry.content);
429
- const pad = (512 - entry.content.length % 512) % 512;
430
- if (pad > 0) chunks.push(Buffer.alloc(pad));
431
- }
432
- chunks.push(Buffer.alloc(1024));
433
- return zlib.gzipSync(Buffer.concat(chunks));
434
- }
435
- /**
436
- * Prints the bootstrap + manifest and tars them with the bundle into a
437
- * deterministic artifact. If bundleDir doesn't exist (e.g. `alchemy destroy`
438
- * run before any build), returns a placeholder rather than throwing — the
439
- * artifact is never read on destroy.
440
- */
441
- function packageComputeArtifact(opts) {
442
- if (!fs.existsSync(opts.bundleDir)) return {
443
- path: "",
444
- sha256: "absent"
445
- };
446
- const bootstrap = `import main from "./${resolveEntry(opts.bundleDir, opts.bundleEntry)}";\nawait main.run(${JSON.stringify(opts.address)}, () => import(${JSON.stringify(`./${opts.appEntry}`)}));\n`;
447
- const manifest = `${JSON.stringify({
448
- manifestVersion: MANIFEST_VERSION,
449
- entrypoint: "bootstrap.js"
450
- }, null, 2)}\n`;
451
- const files = walkFiles(opts.bundleDir).map((relPath) => ({
452
- relPath,
453
- content: fs.readFileSync(path.join(opts.bundleDir, relPath))
454
- }));
455
- files.push({
456
- relPath: "bootstrap.js",
457
- content: Buffer.from(bootstrap, "utf8")
458
- });
459
- files.push({
460
- relPath: "compute.manifest.json",
461
- content: Buffer.from(manifest, "utf8")
462
- });
463
- files.push({
464
- relPath: "bunfig.toml",
465
- content: Buffer.from("[install]\nauto = \"disable\"\n", "utf8")
466
- });
467
- const gz = createDeterministicTarGz(files);
468
- const sha256 = crypto$1.createHash("sha256").update(gz).digest("hex");
469
- const outDir = path.join(os.tmpdir(), `prisma-composer-compute-${String(os.userInfo().uid)}`, sha256.slice(0, 16));
470
- fs.mkdirSync(outDir, { recursive: true });
471
- const outPath = path.join(outDir, `${opts.id}.tar.gz`);
472
- const tmpPath = path.join(outDir, `.${opts.id}.${crypto$1.randomUUID()}.tmp`);
473
- fs.writeFileSync(tmpPath, gz);
474
- fs.renameSync(tmpPath, outPath);
475
- return {
476
- path: outPath,
477
- sha256
478
- };
479
- }
480
- /**
481
- * The `ServiceKey` Alchemy resource (ADR-0030) — mints a random 256-bit key
482
- * ONCE at create and keeps it STABLE across deploys, so an unchanged edge
483
- * no-ops on redeploy. Same mint-once-stable lifecycle as `S3Credentials`
484
- * (`packages/1-prisma-cloud/1-extensions/target/src/s3-credentials-resource.ts`):
485
- * Web Crypto only (`crypto.getRandomValues` — no `node:` import), persisted in
486
- * Alchemy state; on every later apply the provider returns the persisted
487
- * attributes (`reconcile`'s `output`) unchanged. One resource per RPC edge;
488
- * rotation is destroy/recreate.
489
- */
490
- /** The `ServiceKey` resource constructor — `yield* Prisma.ServiceKey(id, {})` in the lowering. */
491
- const ServiceKey = Resource("PrismaCloud.ServiceKey");
492
- /** A fresh 256-bit key as 64 lowercase hex chars (Web Crypto — no node import). */
493
- function mintServiceKey() {
494
- const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
495
- return { value: Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("") };
496
- }
497
- /**
498
- * The `ServiceKey` provider service. `reconcile` runs for create and update;
499
- * it returns the persisted `output` when present (a redeploy reuses the
500
- * stored key — the no-op property) and mints a fresh key only on first
501
- * create. Nothing to enumerate (`list` → `[]`) or tear down (`delete` →
502
- * no-op; the key lives only in state).
503
- */
504
- const serviceKeyProviderService = {
505
- list: () => Effect.succeed([]),
506
- reconcile: ({ output }) => Effect.sync(() => output ?? mintServiceKey()),
507
- delete: () => Effect.void
508
- };
509
- /** The `ServiceKey` provider layer — merged into the Prisma Cloud extension's `providers()`. */
510
- const ServiceKeyProvider = () => Provider.effect(ServiceKey, Effect.succeed(serviceKeyProviderService));
511
- //#endregion
512
- //#region ../../1-prisma-cloud/0-lowering/lowering/dist/postgres.mjs
513
- /** A **connection** to a Prisma Postgres database — yields the connection string. */
514
- const Connection = Resource("Prisma.Connection");
515
- const ConnectionProvider = () => Provider.effect(Connection, Effect.gen(function* () {
516
- const client = yield* ManagementClient;
517
- return {
518
- stables: ["id", "connectionString"],
519
- list: () => Effect.succeed([]),
520
- reconcile: Effect.fn(function* ({ news, output }) {
521
- if (output?.id) return output;
522
- const created = yield* call(() => client.POST("/v1/databases/{databaseId}/connections", {
523
- params: { path: { databaseId: news.databaseId } },
524
- body: { name: news.name }
525
- }));
526
- const endpoints = created.data.endpoints;
527
- const dsn = endpoints?.direct?.connectionString ?? endpoints?.pooled?.connectionString;
528
- if (dsn === void 0) return yield* Effect.fail(new PrismaApiError({
529
- status: 0,
530
- message: `connection ${created.data.id} returned no direct/pooled connection string`
531
- }));
532
- return {
533
- id: created.data.id,
534
- connectionString: Redacted.make(dsn)
535
- };
536
- }),
537
- delete: Effect.fn(function* ({ output }) {
538
- yield* callVoid(() => client.DELETE("/v1/connections/{id}", { params: { path: { id: output.id } } }));
539
- })
540
- };
541
- }));
542
- /** A Prisma **Postgres database** inside a project. */
543
- const Database = Resource("Prisma.Database");
544
- const DatabaseProvider = () => Provider.effect(Database, Effect.gen(function* () {
545
- const client = yield* ManagementClient;
546
- return {
547
- stables: ["id"],
548
- list: () => Effect.succeed([]),
549
- reconcile: Effect.fn(function* ({ news, output }) {
550
- const observed = output?.id ? yield* callOptional(() => client.GET("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } })) : void 0;
551
- if (!observed) {
552
- const created = yield* call(() => client.POST("/v1/databases", { body: {
553
- projectId: news.projectId,
554
- name: news.name,
555
- region: news.region,
556
- ...news.isDefault !== void 0 && { isDefault: news.isDefault },
557
- ...news.branchId !== void 0 && { branchId: news.branchId }
558
- } }));
559
- return {
560
- id: created.data.id,
561
- name: created.data.name
562
- };
563
- }
564
- const result = {
565
- id: observed.data.id,
566
- name: observed.data.name
567
- };
568
- if (news.branchId !== void 0) {
569
- const branchId = news.branchId;
570
- yield* call(() => client.PATCH("/v1/databases/{databaseId}", {
571
- params: { path: { databaseId: result.id } },
572
- body: { branchId }
573
- }));
574
- }
575
- return result;
576
- }),
577
- delete: Effect.fn(function* ({ output }) {
578
- yield* callVoid(() => client.DELETE("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } }));
579
- }),
580
- read: Effect.fn(function* ({ output }) {
581
- if (!output?.id) return void 0;
582
- const d = yield* callOptional(() => client.GET("/v1/databases/{databaseId}", { params: { path: { databaseId: output.id } } }));
583
- return d ? {
584
- id: d.data.id,
585
- name: d.data.name
586
- } : void 0;
587
- })
588
- };
589
- }));
590
- /** A Prisma Developer Platform **Project** — the container for databases and compute services. */
591
- const Project = Resource("Prisma.Project");
592
- const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
593
- const client = yield* ManagementClient;
594
- return {
595
- stables: ["id"],
596
- list: () => Effect.succeed([]),
597
- reconcile: Effect.fn(function* ({ news, output }) {
598
- const observed = output?.id ? yield* callOptional(() => client.GET("/v1/projects/{id}", { params: { path: { id: output.id } } })) : void 0;
599
- if (observed) return {
600
- id: observed.data.id,
601
- name: observed.data.name
602
- };
603
- const created = yield* call(() => client.POST("/v1/projects", { body: {
604
- name: news.name,
605
- workspaceId: news.workspaceId
606
- } }));
607
- return {
608
- id: created.data.id,
609
- name: created.data.name
610
- };
611
- }),
612
- delete: Effect.fn(function* ({ output }) {
613
- yield* callVoid(() => client.DELETE("/v1/projects/{id}", { params: { path: { id: output.id } } }));
614
- }),
615
- read: Effect.fn(function* ({ output }) {
616
- if (!output?.id) return void 0;
617
- const p = yield* callOptional(() => client.GET("/v1/projects/{id}", { params: { path: { id: output.id } } }));
618
- return p ? {
619
- id: p.data.id,
620
- name: p.data.name
621
- } : void 0;
622
- })
623
- };
624
- }));
625
- //#endregion
626
- //#region ../../1-prisma-cloud/0-lowering/lowering/dist/index.mjs
627
- /** Raised with `ensure: false` when the app's Project (or a named stage's Branch) doesn't exist. */
628
- var ContainerNotFoundError = class extends Data.TaggedError("ContainerNotFoundError") {};
629
- const listAllProjects = (client) => Effect.gen(function* () {
630
- const projects = [];
631
- let cursor;
632
- for (;;) {
633
- const query = cursor === void 0 ? {} : { cursor };
634
- const page = yield* call(() => client.GET("/v1/projects", { params: { query } }));
635
- projects.push(...page.data);
636
- if (!page.pagination.hasMore || page.pagination.nextCursor === null) break;
637
- cursor = page.pagination.nextCursor;
638
- }
639
- return projects;
640
- });
641
- /**
642
- * Workspace ids circulate in two shapes: `wksp_`-prefixed and bare. Compare
643
- * bare-to-bare so a `wksp_`-prefixed API id still matches a bare configured
644
- * one (the same normalization `state/bootstrap.ts` applies to the same
645
- * `/v1/projects` listing).
646
- */
647
- const bareWorkspaceId = (id) => id.startsWith("wksp_") ? id.slice(5) : id;
648
- /**
649
- * Finds the app's Project by name in the workspace — PDP allows duplicate
650
- * project names, so more than one can match; the oldest wins. Creates one
651
- * if none match, unless `ensure` is `false` (find-only — `destroy`), in
652
- * which case an absent Project fails with `ContainerNotFoundError`. No
653
- * ownership marker and no `--project` override (both deferred — see
654
- * ADR-0019).
655
- */
656
- const resolveProject = (client, workspaceId, appName, ensure) => Effect.gen(function* () {
657
- const oldest = (yield* listAllProjects(client)).filter((p) => bareWorkspaceId(p.workspace.id) === bareWorkspaceId(workspaceId) && p.name === appName).sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
658
- if (oldest !== void 0) return oldest.id;
659
- if (!ensure) return yield* Effect.fail(new ContainerNotFoundError({ appName }));
660
- return (yield* call(() => client.POST("/v1/projects", { body: {
661
- name: appName,
662
- workspaceId
663
- } }))).data.id;
664
- });
665
- const findBranchId = (client, projectId, gitName) => call(() => client.GET("/v1/projects/{projectId}/branches", { params: {
666
- path: { projectId },
667
- query: { gitName }
668
- } })).pipe(Effect.map((page) => page.data[0]?.id));
669
- /**
670
- * Finds the stage's Branch by its exact `gitName`, creating it if absent
671
- * unless `ensure` is `false` (find-only — `destroy`), in which case an
672
- * absent Branch fails with `ContainerNotFoundError`. The Management API has
673
- * no server-side "create-or-return" idempotency (`POST
674
- * /v1/projects/:id/branches` 409s on a duplicate `gitName`, with no request
675
- * field to make that a no-op), so idempotency is client-side: observe
676
- * first, and on a racing 409 from create, re-observe rather than fail.
677
- */
678
- const resolveBranch = (client, projectId, gitName, appName, ensure) => Effect.gen(function* () {
679
- const existing = yield* findBranchId(client, projectId, gitName);
680
- if (existing !== void 0) return existing;
681
- if (!ensure) return yield* Effect.fail(new ContainerNotFoundError({
682
- appName,
683
- stage: gitName
684
- }));
685
- return yield* call(() => client.POST("/v1/projects/{projectId}/branches", {
686
- params: { path: { projectId } },
687
- body: { gitName }
688
- })).pipe(Effect.map((r) => r.data.id), Effect.catch((err) => err.status === 409 ? findBranchId(client, projectId, gitName).pipe(Effect.flatMap((id) => id === void 0 ? Effect.fail(err) : Effect.succeed(id))) : Effect.fail(err)));
689
- });
690
- /**
691
- * Resolves the two containers a stage's deploy runs into (ADR-0019): the
692
- * app's **Project**, found-or-created by name, and — for a named stage
693
- * only — its **Branch**, found-or-created by `gitName`. The default stage
694
- * (no `stage`) creates no Branch; `branchId` is omitted. With `ensure:
695
- * false` (`destroy`), nothing is created — an absent Project or Branch
696
- * fails with `ContainerNotFoundError` instead.
697
- */
698
- const resolveContainer = (opts) => Effect.gen(function* () {
699
- const client = yield* ManagementClient;
700
- const ensure = opts.ensure ?? true;
701
- const projectId = yield* resolveProject(client, opts.workspaceId, opts.appName, ensure);
702
- if (opts.stage === void 0) return { projectId };
703
- return {
704
- projectId,
705
- branchId: yield* resolveBranch(client, projectId, opts.stage, opts.appName, ensure)
706
- };
707
- });
708
- /**
709
- * Soft-deletes a Branch. Tolerates a 404 (already gone). The API refuses if
710
- * the Branch still has live members or is the production/default Branch —
711
- * that surfaces as a `PrismaApiError`.
712
- */
713
- const deleteBranch = (branchId) => Effect.gen(function* () {
714
- const client = yield* ManagementClient;
715
- yield* callVoid(() => client.DELETE("/v1/branches/{branchId}", { params: { path: { branchId } } }));
716
- });
717
- /**
718
- * Deletes a Project. Tolerates a 404 (already gone). The API refuses with a
719
- * 400 if the Project still has live dependencies (e.g. another stage's
720
- * Branch/resources) — that surfaces as a `PrismaApiError`.
721
- */
722
- const deleteProject = (projectId) => Effect.gen(function* () {
723
- const client = yield* ManagementClient;
724
- yield* callVoid(() => client.DELETE("/v1/projects/{id}", { params: { path: { id: projectId } } }));
725
- });
726
- /** The collection of Prisma resource providers. */
727
- var Providers = class extends Provider.ProviderCollection()("Prisma") {};
728
- /**
729
- * The Prisma provider bundle: every resource provider, the Management API
730
- * client, and env-based credentials. Plug into a stack with
731
- * `{ providers: Prisma.providers() }`.
732
- */
733
- const providers = () => Layer.effect(Providers, Provider.collection([
734
- Project,
735
- Database,
736
- Connection,
737
- ComputeService,
738
- Deployment,
739
- EnvironmentVariable,
740
- Bucket,
741
- BucketKey
742
- ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DatabaseProvider(), ConnectionProvider(), ComputeServiceProvider(), DeploymentProvider(), EnvironmentVariableProvider(), BucketProvider(), BucketKeyProvider())), Layer.provideMerge(layer()), Layer.provideMerge(fromEnv()), Layer.orDie);
743
- //#endregion
744
20
  //#region ../../1-prisma-cloud/0-lowering/lowering/dist/state.mjs
745
21
  /** The framework-owned database a stage's deploy state lives in — a child of that stage's Branch (ADR-0034). */
746
22
  const STATE_DATABASE_NAME = "prisma-composer-state";
@@ -1403,193 +679,7 @@ const prismaStateLayer = (ids) => {
1403
679
  })).pipe(Layer.orDie);
1404
680
  };
1405
681
  //#endregion
1406
- //#region ../../1-prisma-cloud/0-lowering/s3-protocol/dist/index.mjs
1407
- /**
1408
- * AWS SigV4 verification for the S3 wire protocol (spec § 2 auth). The payload
1409
- * hash comes from the client — `x-amz-content-sha256` (a real hash or
1410
- * `UNSIGNED-PAYLOAD`) for header auth, `UNSIGNED-PAYLOAD` for presign — and is
1411
- * never re-hashed; the verifier trusts what was signed, like a real S3 endpoint.
1412
- * Runtime engine code (`node:crypto`); not re-exported from the authoring barrel.
1413
- *
1414
- * Also owns `mintKeyPair` (local-dev spec § 1) — the one key-pair generator
1415
- * both the deploy-time `S3Credentials` resource and the local dev bucket
1416
- * emulator's credential provisioning use.
1417
- */
1418
- function randomBytes(n) {
1419
- return crypto.getRandomValues(new Uint8Array(n));
1420
- }
1421
- function toHexUpper(bytes) {
1422
- return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
1423
- }
1424
- /** A fresh SigV4 key pair: an AKIA-prefixed id and a 40-char base64 secret. */
1425
- function mintKeyPair() {
1426
- return {
1427
- accessKeyId: `AKIA${toHexUpper(randomBytes(8))}`,
1428
- secretAccessKey: btoa(String.fromCharCode(...randomBytes(30)))
1429
- };
1430
- }
1431
- //#endregion
1432
682
  //#region ../../1-prisma-cloud/1-extensions/target/dist/control.mjs
1433
- const PRISMA_CLOUD_EXTENSION_ID = "@prisma/composer-prisma-cloud";
1434
- var PrismaCloudContainer = class {
1435
- input;
1436
- projectId;
1437
- branchId;
1438
- constructor(input, projectId, branchId) {
1439
- this.input = input;
1440
- this.projectId = projectId;
1441
- this.branchId = branchId;
1442
- }
1443
- serialize() {
1444
- return JSON.stringify({
1445
- input: this.input,
1446
- projectId: this.projectId,
1447
- ...this.branchId !== void 0 ? { branchId: this.branchId } : {}
1448
- });
1449
- }
1450
- };
1451
- /** `instanceof` — parent-side instances and child-side deserialized instances are both constructed by this module. */
1452
- function isPrismaCloudContainer(value) {
1453
- return value instanceof PrismaCloudContainer;
1454
- }
1455
- /** Narrow-or-throw for hook inputs. */
1456
- function prismaCloudContainerOf(value) {
1457
- if (!isPrismaCloudContainer(value)) throw new Error("the Prisma Cloud container was not resolved — the extension's container descriptor did not run.");
1458
- return value;
1459
- }
1460
- function isRecord(value) {
1461
- return typeof value === "object" && value !== null;
1462
- }
1463
- function invalidPayloadError(reason) {
1464
- return /* @__PURE__ */ new Error(`${PRISMA_CLOUD_EXTENSION_ID}: invalid container transport payload — ${reason}.`);
1465
- }
1466
- /** Reconstructs a `PrismaCloudContainer` from `serialize()`'s JSON output — real narrowing, no casts. */
1467
- function deserialize(serialized) {
1468
- let parsed;
1469
- try {
1470
- parsed = JSON.parse(serialized);
1471
- } catch (error) {
1472
- throw invalidPayloadError(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
1473
- }
1474
- if (!isRecord(parsed)) throw invalidPayloadError("not an object");
1475
- const input = parsed["input"];
1476
- if (!isRecord(input)) throw invalidPayloadError("\"input\" is not an object");
1477
- const appName = input["appName"];
1478
- if (typeof appName !== "string") throw invalidPayloadError("\"input.appName\" is not a string");
1479
- const stage = input["stage"];
1480
- if (stage !== void 0 && typeof stage !== "string") throw invalidPayloadError("\"input.stage\" is not a string or absent");
1481
- const projectId = parsed["projectId"];
1482
- if (typeof projectId !== "string") throw invalidPayloadError("\"projectId\" is not a string");
1483
- const branchId = parsed["branchId"];
1484
- if (branchId !== void 0 && typeof branchId !== "string") throw invalidPayloadError("\"branchId\" is not a string or absent");
1485
- return new PrismaCloudContainer({
1486
- appName,
1487
- stage
1488
- }, projectId, branchId);
1489
- }
1490
- const workspaceRequiredError = () => /* @__PURE__ */ new Error("environment variable PRISMA_WORKSPACE_ID is required.");
1491
- const tokenRequiredError$2 = () => /* @__PURE__ */ new Error("environment variable PRISMA_SERVICE_TOKEN is required.");
1492
- function requireWorkspaceId() {
1493
- const workspaceId = process.env["PRISMA_WORKSPACE_ID"];
1494
- if (workspaceId === void 0 || workspaceId.length === 0) throw workspaceRequiredError();
1495
- return workspaceId;
1496
- }
1497
- function requireTokenUnlessInjected(deps) {
1498
- if (deps?.client === void 0 && (process.env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) throw tokenRequiredError$2();
1499
- }
1500
- async function ensureContainer(input, deps) {
1501
- const workspaceId = requireWorkspaceId();
1502
- requireTokenUnlessInjected(deps);
1503
- const program = resolveContainer({
1504
- workspaceId,
1505
- appName: input.appName,
1506
- ...input.stage !== void 0 ? { stage: input.stage } : {},
1507
- ensure: true
1508
- }).pipe(Effect.map((c) => ({
1509
- ok: true,
1510
- container: c
1511
- })), Effect.catchTag("PrismaApiError", (e) => Effect.succeed({
1512
- ok: false,
1513
- message: `Prisma Management API error resolving containers: ${e.message}.`
1514
- })));
1515
- const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
1516
- const outcome = await Effect.runPromise(provided);
1517
- if (!outcome.ok) throw new Error(outcome.message);
1518
- return new PrismaCloudContainer(input, outcome.container.projectId, outcome.container.branchId);
1519
- }
1520
- async function locateContainer(input, deps) {
1521
- const workspaceId = requireWorkspaceId();
1522
- requireTokenUnlessInjected(deps);
1523
- const program = resolveContainer({
1524
- workspaceId,
1525
- appName: input.appName,
1526
- ...input.stage !== void 0 ? { stage: input.stage } : {},
1527
- ensure: false
1528
- }).pipe(Effect.map((c) => ({
1529
- ok: true,
1530
- container: c
1531
- })), Effect.catchTag("ContainerNotFoundError", () => Effect.succeed({ ok: false })), Effect.catchTag("PrismaApiError", (e) => Effect.fail(/* @__PURE__ */ new Error(`Prisma Management API error resolving containers: ${e.message}.`))));
1532
- const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
1533
- const outcome = await Effect.runPromise(provided);
1534
- if (!outcome.ok) return void 0;
1535
- return new PrismaCloudContainer(input, outcome.container.projectId, outcome.container.branchId);
1536
- }
1537
- /**
1538
- * Soft-deletes a named stage's Branch after a successful `alchemy destroy`
1539
- * has removed its members — the Management API refuses to delete a Branch
1540
- * that still has live members.
1541
- */
1542
- async function removeStageBranch(branchId, deps) {
1543
- requireTokenUnlessInjected(deps);
1544
- const program = deleteBranch(branchId).pipe(Effect.map(() => ({ ok: true })), Effect.catchTag("PrismaApiError", (e) => Effect.succeed({
1545
- ok: false,
1546
- message: `Failed to delete the stage Branch: ${e.message}.`
1547
- })));
1548
- const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
1549
- const outcome = await Effect.runPromise(provided);
1550
- if (!outcome.ok) throw new Error(outcome.message);
1551
- }
1552
- /**
1553
- * Best-effort cleanup after a successful `--production` destroy: removes
1554
- * the app's Project so hand-run stacks don't accumulate as empty Projects
1555
- * (they eventually hit the workspace's plan limit). Unlike `removeStageBranch`,
1556
- * this never throws: the destroy itself already succeeded, and the API's own
1557
- * 400 ("still has dependencies") is the only check that matters — failing
1558
- * the command over a cleanup step would be worse than leaving a Project shell.
1559
- */
1560
- async function removeAppProject(projectId, deps) {
1561
- if (deps?.client === void 0 && (process.env["PRISMA_SERVICE_TOKEN"] ?? "").length === 0) {
1562
- console.warn(`Skipped removing the Project (${projectId}): PRISMA_SERVICE_TOKEN is not set.`);
1563
- return;
1564
- }
1565
- const program = deleteProject(projectId).pipe(Effect.map(() => ({ ok: true })), Effect.catchTag("PrismaApiError", (e) => Effect.succeed({
1566
- ok: false,
1567
- error: e
1568
- })));
1569
- const provided = deps?.client !== void 0 ? program.pipe(Effect.provideService(ManagementClient, deps.client)) : program.pipe(Effect.provide(layer().pipe(Layer.provide(fromEnv()))));
1570
- const outcome = await Effect.runPromise(provided);
1571
- if (outcome.ok) {
1572
- console.log(`Removed the Project (${projectId}) — nothing was left in it.`);
1573
- return;
1574
- }
1575
- if (outcome.error.status === 400) {
1576
- console.log(`Kept the Project (${projectId}) — it still has another stage's resources.`);
1577
- return;
1578
- }
1579
- console.warn(`Could not remove the Project (${projectId}) after destroy: ${outcome.error.message}.`);
1580
- }
1581
- function containerDescriptor(deps) {
1582
- return {
1583
- ensure: (input) => ensureContainer(input, deps),
1584
- locate: (input) => locateContainer(input, deps),
1585
- remove: (instance) => instance.input.stage !== void 0 ? removeStageBranch(instance.branchId ?? missingBranchId(instance), deps) : removeAppProject(instance.projectId, deps),
1586
- deserialize
1587
- };
1588
- }
1589
- /** Defensive: a named-stage container always resolves a Branch together with its stage — `ensure`/`locate`/`deserialize` never produce one without the other. */
1590
- function missingBranchId(instance) {
1591
- throw new Error(`${PRISMA_CLOUD_EXTENSION_ID}: a named-stage ("${instance.input.stage}") container instance is missing its branchId — this is a bug in ensure/locate/deserialize.`);
1592
- }
1593
683
  const PRISMA_NAME_MIN = 3;
1594
684
  const PRISMA_NAME_MAX = 65;
1595
685
  function validateName(value, source) {
@@ -1660,7 +750,7 @@ function computeDescriptor(o) {
1660
750
  const svc = yield* ComputeService(`${id}-svc`, {
1661
751
  projectId,
1662
752
  name: id,
1663
- region: o.region ?? "us-east-1",
753
+ region: o().region ?? "us-east-1",
1664
754
  ...branchId !== void 0 ? { branchId } : {}
1665
755
  });
1666
756
  return {
@@ -1707,7 +797,7 @@ function computeDescriptor(o) {
1707
797
  refs.push(ref);
1708
798
  refsByBrand.set(edge.brand, refs);
1709
799
  }
1710
- for (const [brand, entry] of o.providerParams) {
800
+ for (const [brand, entry] of o().providerParams) {
1711
801
  const raw = "valueForService" in entry ? entry.valueForService(provisioned, address) : exposes ? entry.value(refsByBrand.get(brand) ?? []) : void 0;
1712
802
  if (raw === void 0) continue;
1713
803
  const key = configKey(address, {
@@ -1757,54 +847,6 @@ function computeDescriptor(o) {
1757
847
  };
1758
848
  }
1759
849
  /**
1760
- * The `PgWarm` Alchemy resource (slice 3, FT-5226) — warm a freshly-provisioned
1761
- * Prisma Postgres database at apply-time so it is ready by deploy-end, and the
1762
- * first real connection (a service's runtime client, or the migration) doesn't
1763
- * eat the cold-start reject.
1764
- *
1765
- * The DB `url` is a lazy `Output` at lowering time, so warming must be an
1766
- * apply-time tracked resource (same pattern as `PnMigration`): its `reconcile`
1767
- * receives the RESOLVED url and connects with `withConnectionRetry` + `select 1`,
1768
- * riding out the cold-start. Shared by BOTH the bare-`postgres` and the
1769
- * `prisma-next` lowerings; keyed on the connection `url`, so an unchanged
1770
- * redeploy is a no-op (warming is idempotent anyway).
1771
- *
1772
- * Deploy-time only: imports `pg` directly + `alchemy`. Imported by `control.ts`
1773
- * and tests, never by `index.ts` / the `./prisma-next` authoring entry — the
1774
- * isolation invariants hold.
1775
- */
1776
- /** The `PgWarm` resource constructor — `yield* PgWarm(id, { url })` in a lowering. */
1777
- const PgWarm = Resource("PrismaCloud.PgWarm");
1778
- /** Connect (retrying the cold-start) and run `select 1`, then release the connection. */
1779
- async function warmDatabase(url) {
1780
- await withConnectionRetry(async () => {
1781
- const client = new pg.Client({ connectionString: normalizeSslMode(url) });
1782
- await client.connect();
1783
- try {
1784
- await client.query("select 1");
1785
- } finally {
1786
- await client.end();
1787
- }
1788
- });
1789
- }
1790
- /**
1791
- * The `PgWarm` provider service. `reconcile` warms the DB (retrying the
1792
- * cold-start) and echoes the `url` so a downstream resource that reads
1793
- * `warm.url` runs only after the DB is warm. Idempotent — safe on redeploy;
1794
- * nothing to enumerate (`list` → `[]`) or tear down (`delete` → no-op; the DB's
1795
- * own deletion handles teardown). Exported so tests can drive it directly.
1796
- */
1797
- const pgWarmProviderService = {
1798
- list: () => Effect.succeed([]),
1799
- reconcile: ({ news }) => Effect.tryPromise({
1800
- try: () => warmDatabase(news.url),
1801
- catch: (error) => error
1802
- }).pipe(Effect.map(() => ({ url: news.url }))),
1803
- delete: () => Effect.void
1804
- };
1805
- /** The `PgWarm` provider layer — merged into the extension descriptor's `providers()`. */
1806
- const PgWarmProvider = () => Provider.effect(PgWarm, Effect.succeed(pgWarmProviderService));
1807
- /**
1808
850
  * One Database per module-provisioned postgres resource — `id` is the
1809
851
  * module provision id, so a resource shared by several consumers is created
1810
852
  * exactly once.
@@ -1816,7 +858,7 @@ function postgresDescriptor(o) {
1816
858
  const db = yield* Database(`${id}-db`, {
1817
859
  projectId: projectIdOf(application),
1818
860
  name: id,
1819
- region: o.region ?? "us-east-1",
861
+ region: o().region ?? "us-east-1",
1820
862
  ...branchId !== void 0 ? { branchId } : {}
1821
863
  });
1822
864
  const conn = yield* Connection(`${id}-conn`, {
@@ -1852,228 +894,6 @@ async function resolveMigrationsDir(configPath) {
1852
894
  return resolve(configPath, "..", (await loadConfig(configPath)).migrations?.dir ?? "migrations");
1853
895
  }
1854
896
  /**
1855
- * The Prisma Next migration step of the deploy lowering (ADR-0022, slice 2) —
1856
- * the safety-critical decision that brings a live database to a target REF
1857
- * using ONLY Prisma Next's authored migrations.
1858
- *
1859
- * Deploy-time only: this module imports `@prisma-next/postgres/control` (which
1860
- * transitively pulls PN's control/migration machinery + `pg`). It is imported
1861
- * by the deploy descriptors and this package's tests, NEVER by `index.ts` / the
1862
- * `./prisma-next` authoring entry — so it never lands in an app runtime bundle
1863
- * (the index-isolation invariant holds).
1864
- *
1865
- * The target is a ref `{ hash, invariants }` — not a bare `storageHash`. A
1866
- * ref's `invariants` are named postconditions established by `data`-class
1867
- * migration steps (e.g. a backfill), recorded monotonically on the live
1868
- * marker. Keying on the hash alone would make a pure data-invariant change an
1869
- * A→A self-edge the deploy wrongly skips. The decision, given the live marker
1870
- * and the target ref (see {@link decideMigrationAction}):
1871
- * - marker at ref.hash AND ref.invariants ⊆ marker.invariants → no-op
1872
- * - no marker (fresh DB) AND no required invariants → `dbInit`
1873
- * - otherwise → `migrate`
1874
- *
1875
- * `dbInit` is additive-only synthesis — it NEVER runs app-space data steps —
1876
- * so it is only correct when the ref requires no invariants; a fresh DB whose
1877
- * target carries invariants goes through `migrate`, which walks the AUTHORED
1878
- * graph (including the invariant-bearing data migrations) from empty.
1879
- *
1880
- * Never `dbUpdate`: synthesized diff-and-apply plans are never run against a
1881
- * deployed database. A no-authored-path (`MIGRATION_PATH_NOT_FOUND`) or a
1882
- * runner failure fails the deploy as a typed `PnMigrationError` (not swallowed).
1883
- * PN applies each migration in its own transaction, so a failed apply is atomic
1884
- * and resume-safe — the marker and schema are left as the last committed step.
1885
- */
1886
- /** A deploy-failing migration error — surfaced, never swallowed. */
1887
- var PnMigrationError = class extends Error {
1888
- code;
1889
- /** PN's structured explanation, when present. */
1890
- why;
1891
- constructor(code, summary, why) {
1892
- super(`prisma-next migrate (${code}): ${summary}`);
1893
- this.name = "PnMigrationError";
1894
- this.code = code;
1895
- this.why = why;
1896
- }
1897
- };
1898
- /**
1899
- * The target `storageHash` a contract heads to — `contractJson.storage.storageHash`.
1900
- * Read defensively: `contractJson` crosses the boundary as `unknown`.
1901
- */
1902
- function targetStorageHash(contractJson) {
1903
- if (typeof contractJson === "object" && contractJson !== null && "storage" in contractJson) {
1904
- const storage = contractJson.storage;
1905
- if (typeof storage === "object" && storage !== null && "storageHash" in storage) {
1906
- const hash = storage.storageHash;
1907
- if (typeof hash === "string" && hash.length > 0) return hash;
1908
- }
1909
- }
1910
- throw new PnMigrationError("INIT_FAILED", "the contract has no storage.storageHash — cannot determine the target schema version");
1911
- }
1912
- /**
1913
- * Resolve the deploy's target ref from the migrations dir.
1914
- *
1915
- * - `targetRef` named: read `migrations/app/refs/<name>.json` — fail loudly
1916
- * (`TARGET_REF_NOT_FOUND`) when the ref doesn't exist or can't be parsed.
1917
- * - Default: the app space's head. PN synthesizes the app head from the
1918
- * emitted contract — `{ hash: contract.storage.storageHash, invariants: [] }`
1919
- * (`contract emit` writes no app-space `refs/head.json` today; extension
1920
- * spaces have one on disk). When a future PN version does emit one, the
1921
- * on-disk `head.json` wins — read via `readContractSpaceHeadRef`, exactly
1922
- * the loader PN's own migrate uses.
1923
- */
1924
- async function resolveTargetRef(migrationsDir, contractJson, targetRef) {
1925
- if (targetRef !== void 0) {
1926
- const refsDir = spaceRefsDirectory(spaceMigrationDirectory(migrationsDir, APP_SPACE_ID));
1927
- try {
1928
- const ref = await readRef(refsDir, targetRef);
1929
- return {
1930
- hash: ref.hash,
1931
- invariants: ref.invariants
1932
- };
1933
- } catch (error) {
1934
- throw new PnMigrationError("TARGET_REF_NOT_FOUND", `targetRef "${targetRef}" could not be read from ${refsDir}`, error instanceof Error ? error.message : String(error));
1935
- }
1936
- }
1937
- const head = await readContractSpaceHeadRef(migrationsDir, APP_SPACE_ID);
1938
- if (head !== null) return {
1939
- hash: head.hash,
1940
- invariants: head.invariants
1941
- };
1942
- return {
1943
- hash: targetStorageHash(contractJson),
1944
- invariants: []
1945
- };
1946
- }
1947
- /**
1948
- * The pure migration decision, mirroring PN's own verifier: the database is
1949
- * AT the target when the marker's hash equals the ref's hash AND every ref
1950
- * invariant is on the marker (marker invariants are monotonic). `dbInit` is
1951
- * additive-only synthesis, so it is chosen only for a fresh DB whose
1952
- * effective required invariants (`ref.invariants − marker.invariants`) are
1953
- * empty; anything else — different hash, missing invariant (the A→A
1954
- * data-only self-edge), or a fresh DB with required invariants — walks the
1955
- * authored graph via `migrate`.
1956
- */
1957
- function decideMigrationAction(marker, ref) {
1958
- const markerInvariants = new Set(marker?.invariants ?? []);
1959
- const missing = ref.invariants.filter((id) => !markerInvariants.has(id));
1960
- if (marker !== null && marker.storageHash === ref.hash && missing.length === 0) return "noop";
1961
- if (marker === null && missing.length === 0) return "init";
1962
- return "migrate";
1963
- }
1964
- /**
1965
- * Bring the database at `url` to the target ref via PN's authored migrations.
1966
- * Reads the live marker, decides no-op / init / migrate
1967
- * ({@link decideMigrationAction}), applies, and throws a typed
1968
- * {@link PnMigrationError} on a no-path or runner failure. `migrationsDir` is
1969
- * the on-disk migrations root and `ref` the resolved target
1970
- * ({@link resolveTargetRef} — both resolved by the lowering, which also keys
1971
- * the PnMigration resource on them). `refName` (the resource's `targetRef`,
1972
- * when set) is threaded into `migrate` so PN targets the named ref's hash and
1973
- * plans an invariant-bearing path.
1974
- */
1975
- async function applyPnMigration(opts) {
1976
- const connection = normalizeSslMode(opts.url);
1977
- return withConnectionRetry(() => runMigration(connection, opts.contractJson, opts.migrationsDir, opts.ref, opts.refName), { shouldRetry: (error) => !(error instanceof PnMigrationError) });
1978
- }
1979
- async function runMigration(connection, contractJson, migrationsDir, ref, refName) {
1980
- const client = createPostgresControlClient({ connection });
1981
- await client.connect();
1982
- try {
1983
- const marker = await client.readMarker();
1984
- const markerHashBefore = marker?.storageHash ?? null;
1985
- const action = decideMigrationAction(marker, ref);
1986
- if (action === "noop") return {
1987
- action,
1988
- targetHash: ref.hash,
1989
- markerHashBefore
1990
- };
1991
- if (action === "init") {
1992
- const result = await client.dbInit({
1993
- contract: contractJson,
1994
- mode: "apply",
1995
- migrationsDir
1996
- });
1997
- if (!result.ok) throw new PnMigrationError("INIT_FAILED", result.failure.summary, result.failure.why);
1998
- return {
1999
- action,
2000
- targetHash: ref.hash,
2001
- markerHashBefore
2002
- };
2003
- }
2004
- const result = await client.migrate({
2005
- contract: contractJson,
2006
- migrationsDir,
2007
- ...refName !== void 0 ? {
2008
- refHash: ref.hash,
2009
- refInvariants: ref.invariants,
2010
- refName
2011
- } : {}
2012
- });
2013
- 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);
2014
- return {
2015
- action,
2016
- targetHash: ref.hash,
2017
- markerHashBefore
2018
- };
2019
- } finally {
2020
- await client.close();
2021
- }
2022
- }
2023
- /**
2024
- * The `PnMigration` Alchemy resource (ADR-0022, slice 2 D2) — the migration
2025
- * step modeled as a tracked resource so it participates in deploy state: keyed
2026
- * on the target REF identity (`targetHash` + sorted `invariants`), an
2027
- * unchanged redeploy is an Alchemy-level no-op (on top of the marker read),
2028
- * and a contract change — or a DATA-ONLY change that adds a ref invariant at
2029
- * the same hash — re-runs the migration.
2030
- *
2031
- * Its provider's `reconcile` receives the RESOLVED props at apply-time — in
2032
- * particular the concrete DB `url` (a lazy `Output` until the Connection
2033
- * provisions) — and delegates to the proven `applyPnMigration` decision. The
2034
- * provider is a standalone `Provider<PnMigration>` layer; the extension
2035
- * descriptor merges it into its `providers()` (`Layer.merge(Prisma.providers(),
2036
- * PnMigrationProvider())`), and Alchemy resolves it at apply via a direct
2037
- * provider-tag lookup (`tryFindProviderByType`) — no change to `@internal/lowering`.
2038
- *
2039
- * Deploy-time only: imports `@prisma-next/postgres/control` (via the helper) +
2040
- * `alchemy`. Imported by `control.ts` and tests, never by `index.ts` / the
2041
- * `./prisma-next` authoring entry — index isolation holds.
2042
- */
2043
- /** The `PnMigration` resource constructor — `yield* PnMigration(id, props)` in the lowering. */
2044
- const PnMigration = Resource("PrismaNext.Migration");
2045
- /**
2046
- * The `PnMigration` provider service. `reconcile` runs for both create and
2047
- * update (Alchemy's unified lifecycle); `applyPnMigration` is idempotent via
2048
- * the live marker read, so it is safe to run for either — the marker decides
2049
- * no-op / init / migrate. A migration has nothing to enumerate (`list` → `[]`)
2050
- * and nothing to tear down on its own (`delete` → no-op; the DB's own deletion
2051
- * handles teardown). Exported so tests can drive `reconcile` directly, without
2052
- * building an Effect layer.
2053
- */
2054
- const pnMigrationProviderService = {
2055
- list: () => Effect.succeed([]),
2056
- reconcile: ({ news }) => Effect.tryPromise({
2057
- try: () => applyPnMigration({
2058
- url: news.url,
2059
- contractJson: news.contractJson,
2060
- migrationsDir: news.migrationsDir,
2061
- ref: {
2062
- hash: news.targetHash,
2063
- invariants: news.invariants
2064
- },
2065
- ...news.refName !== void 0 ? { refName: news.refName } : {}
2066
- }),
2067
- catch: (error) => error
2068
- }).pipe(Effect.map((outcome) => ({
2069
- storageHash: outcome.targetHash,
2070
- invariants: news.invariants
2071
- }))),
2072
- delete: () => Effect.void
2073
- };
2074
- /** The `PnMigration` provider layer — merged into the extension descriptor's `providers()`. */
2075
- const PnMigrationProvider = () => Provider.effect(PnMigration, Effect.succeed(pnMigrationProviderService));
2076
- /**
2077
897
  * The migration is a tracked `PnMigration` Alchemy resource keyed on the
2078
898
  * target REF identity (hash + sorted invariants): unchanged redeploy is a
2079
899
  * no-op, a contract or ref-invariant change re-migrates.
@@ -2085,7 +905,7 @@ function prismaNextDescriptor(o) {
2085
905
  const db = yield* Database(`${id}-db`, {
2086
906
  projectId: projectIdOf(application),
2087
907
  name: id,
2088
- region: o.region ?? "us-east-1",
908
+ region: o().region ?? "us-east-1",
2089
909
  ...branchId !== void 0 ? { branchId } : {}
2090
910
  });
2091
911
  const conn = yield* Connection(`${id}-conn`, {
@@ -2117,36 +937,6 @@ function prismaNextDescriptor(o) {
2117
937
  return Object.assign(lowering, { kind: "resource" });
2118
938
  }
2119
939
  /**
2120
- * The `S3Credentials` Alchemy resource (S5) — mints a random SigV4 key pair
2121
- * ONCE at create and keeps it STABLE across deploys, so an unchanged module
2122
- * no-ops on redeploy. The pair is generated by `@internal/s3-protocol`'s
2123
- * `mintKeyPair` (moved there per the local-dev spec § 1, so deploy and local
2124
- * dev credential minting share one implementation) and persisted in Alchemy
2125
- * state; on every later apply the provider returns the persisted attributes
2126
- * (`reconcile`'s `output`) unchanged — the same way the postgres resource
2127
- * keeps a Connection stable. Rotation is destroy/recreate (a platform ask,
2128
- * not solved here).
2129
- *
2130
- * Deploy-time only: imports `alchemy`. Imported by `control.ts` and tests,
2131
- * never by `index.ts` / the authoring entry.
2132
- */
2133
- /** The `S3Credentials` resource constructor — `yield* S3Credentials(id, {})` in the lowering. */
2134
- const S3Credentials = Resource("PrismaCloud.S3Credentials");
2135
- /**
2136
- * The `S3Credentials` provider service. `reconcile` runs for create and update;
2137
- * it returns the persisted `output` when present (a redeploy reuses the stored
2138
- * pair — the no-op property) and mints a fresh pair only on first create.
2139
- * Nothing to enumerate (`list` → `[]`) or tear down (`delete` → no-op; the pair
2140
- * lives only in state). Exported so tests can drive it directly.
2141
- */
2142
- const s3CredentialsProviderService = {
2143
- list: () => Effect.succeed([]),
2144
- reconcile: ({ output }) => Effect.sync(() => output ?? mintKeyPair()),
2145
- delete: () => Effect.void
2146
- };
2147
- /** The `S3Credentials` provider layer — merged into the extension descriptor's `providers()`. */
2148
- const S3CredentialsProvider = () => Provider.effect(S3Credentials, Effect.succeed(s3CredentialsProviderService));
2149
- /**
2150
940
  * One `S3Credentials` resource per provisioned credentials node — `id` is the
2151
941
  * module provision id, so a pair shared by the storage service is minted once
2152
942
  * and kept stable across deploys (the resource's provider preserves it).
@@ -2198,21 +988,6 @@ function s3StoreDescriptor(o) {
2198
988
  })
2199
989
  };
2200
990
  }
2201
- /**
2202
- * Deploy preflight (ADR-0029, extended for env-sourced params): before Alchemy
2203
- * runs, verify every secret binding AND every env-sourced param binding in the
2204
- * app's manifests (each a platform env-var NAME) exists on Prisma Cloud for
2205
- * the target stage. A literal-bound param never touches the platform — only
2206
- * `envParam(...)` sources are checked here.
2207
- * A name absent on the platform but present in the deploy shell is provisioned
2208
- * via a direct Management API POST — NEVER an Alchemy resource, so the value
2209
- * never lands in hosted deploy state. A name absent from both fails the deploy,
2210
- * listing exactly what is missing and where to set it.
2211
- *
2212
- * Control-plane only (imported by control.ts → prisma-composer.config.ts); runs
2213
- * in the CLI parent, so it builds its own Management API client from env — the
2214
- * same credential path `container.ts`'s `ensure`/`locate` use.
2215
- */
2216
991
  /** production for the default stage; preview for a named stage — matching how the pack writes config rows. */
2217
992
  const classFor = (branchId) => branchId === void 0 ? "production" : "preview";
2218
993
  /**
@@ -2288,22 +1063,9 @@ async function managementClient$1() {
2288
1063
  */
2289
1064
  async function runPreflight(input, deps) {
2290
1065
  const { projectId, branchId } = prismaCloudContainerOf(input.container);
1066
+ const collected = collectPreflightNames(input.graph);
2291
1067
  const names = /* @__PURE__ */ new Map();
2292
- for (const binding of provisionManifest(input.graph)) {
2293
- const name = secretName(binding);
2294
- if (!names.has(name)) names.set(name, {
2295
- name,
2296
- serviceAddress: binding.serviceAddress
2297
- });
2298
- }
2299
- for (const binding of paramManifest(input.graph)) {
2300
- if (!isEnvParamSource(binding.binding)) continue;
2301
- const name = paramName(binding);
2302
- if (!names.has(name)) names.set(name, {
2303
- name,
2304
- serviceAddress: binding.serviceAddress
2305
- });
2306
- }
1068
+ for (const meta of [...collected.secrets, ...collected.envParams]) if (!names.has(meta.name)) names.set(meta.name, meta);
2307
1069
  if (names.size === 0) return;
2308
1070
  const client = deps?.client ?? await managementClient$1();
2309
1071
  const missing = [];
@@ -2509,12 +1271,18 @@ function buildProviderParams(entries, values) {
2509
1271
  }
2510
1272
  const PROVIDER_PARAMS = buildProviderParams(RESERVED_PROVIDER_PARAMS, PROVIDER_PARAM_VALUES);
2511
1273
  /**
2512
- * Resolves the factory's env-or-option inputs, failing fast with the exact
2513
- * variable name.
1274
+ * Resolves the factory's env-or-option inputs. Deliberately does NOT require
1275
+ * `PRISMA_WORKSPACE_ID`: nothing in this file reads `ResolvedCloudOptions.workspaceId`
1276
+ * downstream — it exists only so a caller MAY pin an explicit workspace, and
1277
+ * the real workspace check for a real deploy lives where the value actually
1278
+ * matters, `container.ts`'s `ensureContainer`/`locateContainer`. Region
1279
+ * validation stays eager-on-call (a garbage `PRISMA_REGION` still fails
1280
+ * loudly), but an ABSENT one resolves to `undefined` without touching
1281
+ * anything else — required for `prisma-composer dev`, which never sets
1282
+ * `PRISMA_REGION` and must not fail on its absence (local-dev spec § 5).
2514
1283
  */
2515
1284
  function resolveOptions(opts) {
2516
- const workspaceId = opts.workspaceId ?? process.env["PRISMA_WORKSPACE_ID"];
2517
- if (workspaceId === void 0 || workspaceId.length === 0) throw new Error("prismaCloud(): environment variable PRISMA_WORKSPACE_ID is required.");
1285
+ const workspaceId = opts.workspaceId ?? process.env["PRISMA_WORKSPACE_ID"] ?? "";
2518
1286
  if (opts.region !== void 0) return {
2519
1287
  workspaceId,
2520
1288
  region: opts.region,
@@ -2532,9 +1300,24 @@ function resolveOptions(opts) {
2532
1300
  providerParams: PROVIDER_PARAMS
2533
1301
  };
2534
1302
  }
1303
+ /**
1304
+ * A memoized thunk over `resolveOptions` — evaluated at FIRST LOWERING USE
1305
+ * (inside a node descriptor's `provision`/`serialize`), never at `prismaCloud()`
1306
+ * construction. The node descriptors take this thunk, not a resolved value
1307
+ * (local-dev spec § 5): `prismaCloud()` itself must construct with no
1308
+ * environment present, since it also builds the `localTarget` descriptor, which must
1309
+ * never require `PRISMA_WORKSPACE_ID`/`PRISMA_REGION`/`PRISMA_SERVICE_TOKEN`.
1310
+ */
1311
+ function lazyOptions(opts) {
1312
+ let cached;
1313
+ return () => {
1314
+ cached ??= resolveOptions(opts);
1315
+ return cached;
1316
+ };
1317
+ }
2535
1318
  /** The Prisma Cloud extension descriptor — `prisma-composer.config.ts` lists it under `extensions`. */
2536
1319
  const prismaCloud = (opts = {}) => {
2537
- const o = resolveOptions(opts);
1320
+ const o = lazyOptions(opts);
2538
1321
  return {
2539
1322
  id: PRISMA_CLOUD_EXTENSION_ID,
2540
1323
  container: containerDescriptor(),
@@ -2563,7 +1346,8 @@ const prismaCloud = (opts = {}) => {
2563
1346
  credentials: s3CredentialsDescriptor(o),
2564
1347
  "s3-store": s3StoreDescriptor(o),
2565
1348
  s3: bucketDescriptor(o)
2566
- }
1349
+ },
1350
+ localTarget: () => import("@prisma/composer-prisma-cloud/local-target").then((m) => m.localTargetDescriptor())
2567
1351
  };
2568
1352
  };
2569
1353
  //#endregion