@prisma/composer-cli 0.25.0 → 0.26.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 (56) hide show
  1. package/dist/composer-config-CY9fET8H-KpGjlYgO.mjs +432 -0
  2. package/dist/composer-config-CY9fET8H-KpGjlYgO.mjs.map +1 -0
  3. package/dist/{pipeline-C7gNjMzJ-CMqZQxqM.mjs → container-transport-HcvNOGZL-CHqecFc7.mjs} +109 -322
  4. package/dist/container-transport-HcvNOGZL-CHqecFc7.mjs.map +1 -0
  5. package/dist/{execute-deploy-destroy-CvKCwVkD-B3vcxYJF.mjs → execute-deploy-destroy-c0eko3AO-9npuGXd3.mjs} +108 -85
  6. package/dist/execute-deploy-destroy-c0eko3AO-9npuGXd3.mjs.map +1 -0
  7. package/dist/{execute-dev-BLCK5wF7-CuzMSK7T.mjs → execute-dev-BICPaq1g-CSoZJuhB.mjs} +162 -132
  8. package/dist/execute-dev-BICPaq1g-CSoZJuhB.mjs.map +1 -0
  9. package/dist/{family-B1RaH4f8-ChoTnv3A.d.mts → family-CgeZQdNg-gH8LuqqL.d.mts} +136 -172
  10. package/dist/family-CgeZQdNg-gH8LuqqL.d.mts.map +1 -0
  11. package/dist/family.d.mts +4 -39
  12. package/dist/family.d.mts.map +1 -1
  13. package/dist/family.mjs +49 -551
  14. package/dist/family.mjs.map +1 -1
  15. package/dist/generate-dev-stack-BUadNY_w-DF_lHVaP.mjs +87 -0
  16. package/dist/generate-dev-stack-BUadNY_w-DF_lHVaP.mjs.map +1 -0
  17. package/dist/run-alchemy-BEvB2sYQ-BgV2deuO.mjs +154 -0
  18. package/dist/run-alchemy-BEvB2sYQ-BgV2deuO.mjs.map +1 -0
  19. package/dist/testing.d.mts +24 -24
  20. package/dist/testing.d.mts.map +1 -1
  21. package/dist/testing.mjs +17 -45
  22. package/dist/testing.mjs.map +1 -1
  23. package/package.json +7 -11
  24. package/src/exports/testing.ts +5 -3
  25. package/dist/bin.mjs +0 -1040
  26. package/dist/bin.mjs.map +0 -1
  27. package/dist/container-transport-HcvNOGZL-CIoZc7Rs.mjs +0 -34
  28. package/dist/container-transport-HcvNOGZL-CIoZc7Rs.mjs.map +0 -1
  29. package/dist/execute-deploy-destroy-CvKCwVkD-B3vcxYJF.mjs.map +0 -1
  30. package/dist/execute-deploy-destroy-CvKCwVkD-DCufHnkW.mjs +0 -528
  31. package/dist/execute-deploy-destroy-CvKCwVkD-DCufHnkW.mjs.map +0 -1
  32. package/dist/execute-dev-BLCK5wF7-B-fG_E31.mjs +0 -2011
  33. package/dist/execute-dev-BLCK5wF7-B-fG_E31.mjs.map +0 -1
  34. package/dist/execute-dev-BLCK5wF7-CuzMSK7T.mjs.map +0 -1
  35. package/dist/execute-log-B_zCJ17b-BrLUt7vo.mjs +0 -157
  36. package/dist/execute-log-B_zCJ17b-BrLUt7vo.mjs.map +0 -1
  37. package/dist/execute-log-B_zCJ17b-C4a0uxJj.mjs +0 -158
  38. package/dist/execute-log-B_zCJ17b-C4a0uxJj.mjs.map +0 -1
  39. package/dist/family-B1RaH4f8-ChoTnv3A.d.mts.map +0 -1
  40. package/dist/local-target-BOGjATc2.mjs +0 -68
  41. package/dist/local-target-BOGjATc2.mjs.map +0 -1
  42. package/dist/local-target-hoEGqgVA.mjs +0 -68
  43. package/dist/local-target-hoEGqgVA.mjs.map +0 -1
  44. package/dist/pipeline-C7gNjMzJ-CMqZQxqM.mjs.map +0 -1
  45. package/dist/pipeline-C7gNjMzJ-CixaMvnR.mjs +0 -1205
  46. package/dist/pipeline-C7gNjMzJ-CixaMvnR.mjs.map +0 -1
  47. package/dist/result-B874OKwb.mjs +0 -383
  48. package/dist/result-B874OKwb.mjs.map +0 -1
  49. package/dist/result-sR7PBi61.mjs +0 -229
  50. package/dist/result-sR7PBi61.mjs.map +0 -1
  51. package/dist/run-alchemy-pANK8XNX-BH1wC0r6.mjs +0 -99
  52. package/dist/run-alchemy-pANK8XNX-BH1wC0r6.mjs.map +0 -1
  53. package/dist/run-alchemy-pANK8XNX-XcCQncKN.mjs +0 -99
  54. package/dist/run-alchemy-pANK8XNX-XcCQncKN.mjs.map +0 -1
  55. package/dist/shared-BTnATsqm-BH4axbJg.mjs +0 -158
  56. package/dist/shared-BTnATsqm-BH4axbJg.mjs.map +0 -1
@@ -1,1205 +0,0 @@
1
- import { a as InternalError, i as CliStructuredError, o as blindCast } from "./result-sR7PBi61.mjs";
2
- import { t as effectResolutionDiagnostic } from "./shared-BTnATsqm-BH4axbJg.mjs";
3
- import * as mod from "node:module";
4
- import * as fs from "node:fs";
5
- import { existsSync } from "node:fs";
6
- import * as path from "node:path";
7
- import { fileURLToPath, pathToFileURL } from "node:url";
8
- import * as c12 from "c12";
9
- //#region ../../0-framework/1-core/core/dist/graph-BfKAg2Ap.mjs
10
- /** The reserved name of a resource's single anonymous output port. Rejected as a user-declared port name (node.ts). */
11
- const RESOURCE_OUT_PORT = "$out";
12
- /**
13
- * Thrown by Load when the graph is malformed. Structured at origin
14
- * (base-type rule 6): one type-level code covers every raise site until a
15
- * finer per-site taxonomy is carved out. The `name` stays
16
- * `CliStructuredError` — structural recognition depends on it.
17
- */
18
- var LoadError = class extends CliStructuredError {
19
- constructor(message) {
20
- super("COMPOSE.GRAPH_INVALID", message);
21
- }
22
- };
23
- /**
24
- * Core model: node types and the factories that construct them, plain frozen
25
- * data objects. A node's `extension` + `type` form its deploy-time registry key (ADR-0017).
26
- */
27
- const NODE = Symbol.for("prisma:node");
28
- blindCast(Symbol.for("prisma:secret-need"));
29
- const SECRET_SOURCE = blindCast(Symbol.for("prisma:secret-source"));
30
- /** True if `value` is a secret source (an `envSecret` result or a forwarded ctx.secrets ref). */
31
- function isSecretSource(value) {
32
- return typeof value === "object" && value !== null && blindCast(value)[SECRET_SOURCE] === true;
33
- }
34
- blindCast(Symbol.for("prisma:provision-need"));
35
- const PARAM_SOURCE = blindCast(Symbol.for("prisma:param-source"));
36
- blindCast(Symbol.for("prisma:param-need"));
37
- /** True if `value` is a param source (an `envParam` result or a forwarded ctx.params ref). */
38
- function isParamSource(value) {
39
- return typeof value === "object" && value !== null && blindCast(value)[PARAM_SOURCE] === true;
40
- }
41
- /**
42
- * Core's grammar for every name that becomes a config-key segment —
43
- * addresses, input/param/secret names: ASCII letters and digits only.
44
- * Conservative by design so any target medium — POSIX env-var keys
45
- * included — can uppercase and "_"-join segments without escaping.
46
- */
47
- function isConfigKeySegment(name) {
48
- return /^[A-Za-z0-9]+$/.test(name);
49
- }
50
- /**
51
- * True if `value` was constructed by this module's factories. Checks the
52
- * brand only, never a prototype — a graph may mix nodes from a different
53
- * installed copy of core (dual-package hazard).
54
- */
55
- function isNode(value) {
56
- return typeof value === "object" && value !== null && value[NODE] === true;
57
- }
58
- /**
59
- * Stable topological sort: every edge's `from` precedes its `to` in the
60
- * result. Ties (nodes with no ordering constraint between them) keep their
61
- * relative order from `nodes` — so a graph already authored producer-first
62
- * comes out byte-identical to its pre-sort layout; only a graph that
63
- * genuinely needs reordering (e.g. a module wired via a forged ref pointing at a
64
- * not-yet-provisioned producer) actually moves. A Kahn's-algorithm variant
65
- * that always picks the ready node with the smallest original index. Edges
66
- * whose endpoint falls outside `nodes` (e.g. a service-root's input edges
67
- * targeting the root, which is appended separately) are ignored. Cycles
68
- * cannot reach here: `assertDependencyDag` already rejects them for
69
- * dependency edges, and input edges never cycle.
70
- */
71
- function topoSort(nodes, edges) {
72
- const byId = new Map(nodes.map((n) => [n.id, n]));
73
- const indexOf = new Map(nodes.map((n, i) => [n.id, i]));
74
- const indegree = new Map(nodes.map((n) => [n.id, 0]));
75
- const successors = /* @__PURE__ */ new Map();
76
- for (const edge of edges) {
77
- if (!byId.has(edge.from) || !byId.has(edge.to)) continue;
78
- const targets = successors.get(edge.from) ?? [];
79
- targets.push(edge.to);
80
- successors.set(edge.from, targets);
81
- indegree.set(edge.to, (indegree.get(edge.to) ?? 0) + 1);
82
- }
83
- const ready = new Set(nodes.filter((n) => indegree.get(n.id) === 0).map((n) => n.id));
84
- const order = [];
85
- while (ready.size > 0) {
86
- let next;
87
- let bestIndex = Number.POSITIVE_INFINITY;
88
- for (const id of ready) {
89
- const index = indexOf.get(id) ?? Number.POSITIVE_INFINITY;
90
- if (index < bestIndex) {
91
- bestIndex = index;
92
- next = id;
93
- }
94
- }
95
- if (next === void 0) break;
96
- ready.delete(next);
97
- order.push(next);
98
- for (const target of successors.get(next) ?? []) {
99
- const remaining = (indegree.get(target) ?? 0) - 1;
100
- indegree.set(target, remaining);
101
- if (remaining === 0) ready.add(target);
102
- }
103
- }
104
- if (order.length !== nodes.length) throw new InternalError(`topological sort processed ${order.length} of ${nodes.length} nodes — the graph contains a cycle that slipped past the DAG validation.`);
105
- return order.map((id) => byId.get(id)).filter((n) => n !== void 0);
106
- }
107
- /**
108
- * The declared boundary ports of a module or service node at `id`: dep slots
109
- * as `in` ports (contractKind = the slot's `type`), exposed contracts as
110
- * `out` ports (contractKind = the contract's `kind`). A resource's one
111
- * `$out` port is recorded at its provision site instead (load-module.ts).
112
- */
113
- function boundaryPortsOf(id, node) {
114
- const ports = [];
115
- const slots = node.kind === "module" ? node.deps : node.inputs;
116
- for (const [name, slot] of Object.entries(slots)) {
117
- const type = typeof slot === "object" && slot !== null && "type" in slot && typeof slot.type === "string" ? slot.type : void 0;
118
- ports.push({
119
- node: id,
120
- direction: "in",
121
- name,
122
- contractKind: type
123
- });
124
- }
125
- for (const [name, contract] of Object.entries(node.expose ?? {})) {
126
- const kind = typeof contract === "object" && contract !== null && "kind" in contract && typeof contract.kind === "string" ? contract.kind : void 0;
127
- ports.push({
128
- node: id,
129
- direction: "out",
130
- name,
131
- contractKind: kind
132
- });
133
- }
134
- return ports;
135
- }
136
- function serviceInputs(service, serviceId) {
137
- if (typeof service.inputs !== "object" || service.inputs === null) throw new LoadError(`Service "${serviceId}" has no inputs map.`);
138
- const nodes = [];
139
- const edges = [];
140
- for (const [input, value] of Object.entries(service.inputs)) {
141
- const kind = isNode(value) ? value.kind : void 0;
142
- if (kind === "resource") throw new LoadError(`Input "${input}" of "${serviceId}" is a resource node — a resource is provisioned by the composing module, never created for a service that mentions it. Declare the input as a dependency (the pack's dependency factory) and wire the module-provisioned resource's ref into it.`);
143
- if (kind !== "dependency") throw new LoadError(`Input "${input}" of "${serviceId}" is not a branded dependency end (construct it with the dependency() factory).`);
144
- if (value.type.length === 0) throw new LoadError(`Input "${input}" of "${serviceId}" has an empty node type.`);
145
- const id = `${serviceId}.${input}`;
146
- nodes.push({
147
- id,
148
- parent: serviceId,
149
- node: value
150
- });
151
- edges.push({
152
- from: id,
153
- to: serviceId,
154
- input,
155
- kind: "input"
156
- });
157
- }
158
- return {
159
- nodes,
160
- edges
161
- };
162
- }
163
- function loadService(root, rootId) {
164
- for (const [input, value] of Object.entries(root.inputs)) if (isNode(value) && value.kind === "dependency") throw new LoadError(`Service "${rootId}" has an unwired dependency input "${input}" — this service is composed by a module; deploy the module instead of loading "${rootId}" directly.`);
165
- if (root.inputSchema !== void 0) throw new LoadError(`Service "${rootId}" declares an input schema but is being loaded directly — a lone service has no enclosing scope to bind its input. Compose it inside a module whose provision() call binds \`input: { … }\` (ADR-0042).`);
166
- const rootGraphNode = {
167
- id: rootId,
168
- parent: void 0,
169
- node: root
170
- };
171
- const { nodes, edges } = serviceInputs(root, rootId);
172
- return {
173
- root: rootGraphNode,
174
- nodes: [...topoSort(nodes, edges), rootGraphNode],
175
- edges,
176
- ports: boundaryPortsOf(rootId, root),
177
- authoredEdges: [],
178
- inputBindings: [],
179
- params: []
180
- };
181
- }
182
- /**
183
- * Brands a ref-port with the AUTHORED endpoint it stands for — which port of
184
- * which node the author wired, before any forwarding chain resolves. Read
185
- * only by `authoredSourceOf`; `__providerId` keeps carrying the resolved
186
- * producer for the flat (post-dereference) edges.
187
- */
188
- const AUTHORED_PORT = Symbol("prisma:authored-port");
189
- /** The authored out-port brand carried by `ref`, if any. */
190
- function authoredPortOf(ref) {
191
- if (typeof ref !== "object" || ref === null) return void 0;
192
- const brand = blindCast(ref)[AUTHORED_PORT];
193
- if (typeof brand !== "object" || brand === null) return void 0;
194
- const { node, name } = blindCast(brand);
195
- return typeof node === "string" && typeof name === "string" ? {
196
- node,
197
- name
198
- } : void 0;
199
- }
200
- /**
201
- * Builds the ref a provision() call hands back: the id (so a producer with no
202
- * exposed ports — or an untyped slot — can still be wired wholesale) plus one
203
- * ref-port per exposed contract, each the contract's own runtime value (so
204
- * its `satisfies()` still works) tagged with the provider's id.
205
- */
206
- function refFor(id, service) {
207
- const ports = {};
208
- for (const [port, contract] of Object.entries(service.expose ?? {})) ports[port] = {
209
- ...contract,
210
- __providerId: id,
211
- [AUTHORED_PORT]: {
212
- node: id,
213
- name: port
214
- }
215
- };
216
- return blindCast({
217
- id,
218
- ...ports
219
- });
220
- }
221
- /**
222
- * The resource variant of refFor: a resource has exactly one port — the
223
- * contract it provides — flattened onto the ref itself, tagged with the
224
- * provider id. `id` and the authored brand are written last so a hostile
225
- * contract value cannot clobber them.
226
- */
227
- function refForResource(id, resource) {
228
- return blindCast({
229
- ...resource.provides,
230
- __providerId: id,
231
- id,
232
- [AUTHORED_PORT]: {
233
- node: id,
234
- name: RESOURCE_OUT_PORT
235
- }
236
- });
237
- }
238
- /** A wired value's producer id: a ref-port's `__providerId`, or a bare ref's `id`. */
239
- function producerIdOf(ref) {
240
- if (typeof ref !== "object" || ref === null) return void 0;
241
- if ("__providerId" in ref && typeof ref.__providerId === "string") return ref.__providerId;
242
- if ("id" in ref && typeof ref.id === "string") return ref.id;
243
- }
244
- /**
245
- * Brands each `ctx.inputs` entry with the input key it stands for (see
246
- * flatten): diagnostic only — usage attribution relies on the per-key object
247
- * identity the branding copy creates, never on reading this back.
248
- */
249
- const MODULE_INPUT_KEY = Symbol("prisma:module-input-key");
250
- /** Same per-key identity trick as MODULE_INPUT_KEY, for the parallel `ctx.secrets` forwarding channel. */
251
- const MODULE_SECRET_KEY = Symbol("prisma:module-secret-key");
252
- /** Same per-key identity trick as MODULE_INPUT_KEY, for the parallel `ctx.params` forwarding channel. */
253
- const MODULE_PARAM_KEY = Symbol("prisma:module-param-key");
254
- /** Whether `ref` carries a callable `satisfies` that accepts `required` truthily. */
255
- function satisfiesRequired(ref, required) {
256
- return typeof ref === "object" && ref !== null && "satisfies" in ref && typeof ref.satisfies === "function" && ref.satisfies(required);
257
- }
258
- /**
259
- * Checks one recorded `wiring` object against the Deps it was wired against:
260
- * every named input exists and is a dependency slot, every referenced
261
- * producer is a real (by-now-provisioned) address, and a wired ref whose
262
- * slot declares a required contract must satisfy() it — no producer-kind
263
- * branching, the contract alone determines validity, whether the producer is
264
- * a service port or a resource. Shared by both provisioned kinds so a
265
- * module-as-child gets exactly the checks a service gets, and run once per
266
- * entry against the one `byId` shared by the whole recursive flatten, so a
267
- * forwarded ref resolves through to its real producer address regardless of
268
- * which ancestor scope provisioned it.
269
- */
270
- function validateWiring(pending, byId) {
271
- const { deps, wiring, targetId, targetKind, enclosingModuleName } = pending;
272
- for (const [input, ref] of Object.entries(wiring)) {
273
- const declared = blindCast(deps[input]);
274
- if (declared === void 0 || !isNode(declared) || declared.kind !== "dependency") throw new LoadError(`The deps for "${targetId}" name "${input}", which is not a dependency slot of that ${targetKind}.`);
275
- const producerId = producerIdOf(ref);
276
- const producer = producerId !== void 0 ? byId.get(producerId) : void 0;
277
- if (producerId === void 0 || producer === void 0) throw new LoadError(`The deps for "${targetId}.${input}" reference "${String(producerId)}", which is not provisioned in module "${enclosingModuleName}".`);
278
- const required = declared.required;
279
- if (required !== void 0 && !satisfiesRequired(ref, required)) throw new LoadError(`The deps for "${targetId}.${input}" do not satisfy the slot's required contract.`);
280
- }
281
- for (const [input, rawValue] of Object.entries(deps)) {
282
- const value = blindCast(rawValue);
283
- if (!isNode(value) || wiring[input] !== void 0) continue;
284
- if (value.kind === "dependency") throw new LoadError(`Dependency input "${input}" of provisioned ${targetKind} "${targetId}" is not wired to a producer (module "${enclosingModuleName}").`);
285
- }
286
- }
287
- /**
288
- * Flattens a value into itself plus every nested object/array member value —
289
- * identity fodder for the ctx.secrets/ctx.params usage marking, which must
290
- * see a forwarded source wherever it sits inside an input binding (ADR-0042).
291
- * A secret/param source is an opaque leaf: it is pushed (a forwarded ref IS
292
- * such a source, so identity-matching still needs it) but never descended
293
- * into, so a ref buried in an unrelated source's payload is not falsely seen
294
- * as used. `seen` guards object cycles so a self-referential binding cannot
295
- * recurse forever.
296
- */
297
- function deepValues(value, out, seen = /* @__PURE__ */ new WeakSet()) {
298
- out.push(value);
299
- if (typeof value !== "object" || value === null) return;
300
- if (isSecretSource(value) || isParamSource(value)) return;
301
- if (seen.has(value)) return;
302
- seen.add(value);
303
- const members = Array.isArray(value) ? value : Object.values(value);
304
- for (const member of members) deepValues(member, out, seen);
305
- }
306
- /** The (unvalidated) edges a `wiring` object implies — one dependency edge per entry; `validateWiring` does the real checking. */
307
- function wiringEdges(wiring, targetId) {
308
- return Object.entries(wiring).map(([input, ref]) => ({
309
- from: producerIdOf(ref) ?? "",
310
- to: targetId,
311
- input,
312
- kind: "dependency"
313
- }));
314
- }
315
- /**
316
- * Checks the secrets wired into one provisioned child MODULE: every declared
317
- * forwarding slot is bound to a real secret source (an `envSecret` or a
318
- * forwarded ctx.secrets ref), and no wired key names a slot the module
319
- * doesn't declare — the secret analog of `validateWiring`'s per-input checks,
320
- * but resolved inline (a source carries its own name, so no whole-graph pass
321
- * is needed).
322
- */
323
- function validateSecretBinding(child, id, secretWiring, enclosingModuleName) {
324
- const { kind } = child;
325
- for (const slot of Object.keys(child.secretSlots)) {
326
- const bound = secretWiring[slot];
327
- if (bound === void 0) throw new LoadError(`Secret slot "${slot}" of provisioned ${kind} "${id}" is not bound (module "${enclosingModuleName}") — bind it with envSecret('NAME') or forward ctx.secrets.`);
328
- if (!isSecretSource(bound)) throw new LoadError(`Secret slot "${slot}" of "${id}" (module "${enclosingModuleName}") was wired with a non-secret value — use envSecret('NAME') or a forwarded ctx.secrets ref.`);
329
- }
330
- for (const slot of Object.keys(secretWiring)) if (!Object.hasOwn(child.secretSlots, slot)) throw new LoadError(`The secrets for "${id}" name "${slot}", which is not a secret slot of that ${kind} (module "${enclosingModuleName}").`);
331
- }
332
- /**
333
- * Checks the params wired into a provisioned SERVICE: unlike a secret slot, a
334
- * declared param is never required to be bound here — it may fall back to its
335
- * own `default` (checked later, at `buildConfig`) — so this only rejects a
336
- * wired key that names something other than a real declared param.
337
- */
338
- function validateServiceParamBinding(child, id, paramWiring, enclosingModuleName) {
339
- for (const slot of Object.keys(paramWiring)) if (!Object.hasOwn(child.params, slot)) throw new LoadError(`The params for "${id}" name "${slot}", which is not a param of that service (module "${enclosingModuleName}").`);
340
- }
341
- /**
342
- * Checks the params wired into a provisioned MODULE: every declared
343
- * param-forwarding slot must be bound to a real `ParamSource` — a slot has no
344
- * schema of its own, so (unlike a service param) it cannot fall back to a
345
- * literal or a default; the param analog of `validateSecretBinding`.
346
- */
347
- function validateParamNeedBinding(child, id, paramWiring, enclosingModuleName) {
348
- for (const slot of Object.keys(child.paramSlots)) {
349
- const bound = paramWiring[slot];
350
- if (bound === void 0) throw new LoadError(`Param slot "${slot}" of provisioned module "${id}" is not bound (module "${enclosingModuleName}") — bind it with a param source (e.g. envParam('NAME')) or forward ctx.params.`);
351
- if (!isParamSource(bound)) throw new LoadError(`Param slot "${slot}" of "${id}" (module "${enclosingModuleName}") was wired with a non-source value — a module param-forwarding slot carries no schema to validate a literal against; use envParam('NAME') or a forwarded ctx.params ref.`);
352
- }
353
- for (const slot of Object.keys(paramWiring)) if (!Object.hasOwn(child.paramSlots, slot)) throw new LoadError(`The params for "${id}" name "${slot}", which is not a param slot of that module (module "${enclosingModuleName}").`);
354
- }
355
- /**
356
- * Recursively flattens one module's body into the shared graph state and
357
- * returns its resolved ModuleOutputs (one ref-port per expose key) for the
358
- * caller (the enclosing provision() call, or Load itself for the root) to
359
- * use. `address` is this module's OWN full address, or `undefined` for the root
360
- * scope — its direct children then get bare (unprefixed) addresses, keeping
361
- * a single-level module identical to before nesting existed. `wiring` supplies a
362
- * resolved producer ref-port for each of this module's OWN declared deps (empty
363
- * for the root, which may not declare any — see the root non-empty-deps
364
- * check in loadModule). `nodes`, `edges`, `pending`, and `byId` are shared
365
- * across the ENTIRE recursive flatten, not per scope — a nested module may
366
- * forward in a producer provisioned by an ancestor scope, and it is the
367
- * shared `byId` (keyed by full address) that lets that resolve.
368
- *
369
- * `selfId` is this module's own node id — the root's given id when `address`
370
- * is `undefined`, the full address otherwise. It anchors the authored view:
371
- * children carry it as their `parent`, and this module's own boundary ports
372
- * (and the authored edges touching them) are recorded against it.
373
- */
374
- function flatten(moduleNode, address, selfId, wiring, secretWiring, paramWiring, nodes, edges, pending, inputBindings, paramBindings, byId, ports, authoredEdges) {
375
- ports.push(...boundaryPortsOf(selfId, moduleNode));
376
- const localIds = /* @__PURE__ */ new Set();
377
- const used = /* @__PURE__ */ new Set();
378
- const usedSecrets = /* @__PURE__ */ new Set();
379
- const usedParams = /* @__PURE__ */ new Set();
380
- const ctxInputs = {};
381
- for (const key of Object.keys(moduleNode.deps)) {
382
- const wired = wiring[key];
383
- ctxInputs[key] = typeof wired === "object" && wired !== null ? {
384
- ...wired,
385
- [MODULE_INPUT_KEY]: key
386
- } : wired;
387
- }
388
- const markUsed = (values) => {
389
- for (const value of values) for (const key of Object.keys(ctxInputs)) if (value === ctxInputs[key]) used.add(key);
390
- };
391
- const authoredSourceOf = (value) => {
392
- for (const key of Object.keys(ctxInputs)) if (value === ctxInputs[key]) return {
393
- node: selfId,
394
- direction: "in",
395
- name: key
396
- };
397
- const brand = authoredPortOf(value);
398
- return brand === void 0 ? void 0 : {
399
- node: brand.node,
400
- direction: "out",
401
- name: brand.name
402
- };
403
- };
404
- /** Records the authored edge each wiring entry declares: source port → the target's own `in` port. */
405
- const recordAuthoredWiring = (targetId, targetWiring) => {
406
- for (const [input, ref] of Object.entries(targetWiring)) {
407
- const from = authoredSourceOf(ref);
408
- if (from !== void 0) authoredEdges.push({
409
- from,
410
- to: {
411
- node: targetId,
412
- direction: "in",
413
- name: input
414
- }
415
- });
416
- }
417
- };
418
- const ctxSecrets = {};
419
- for (const key of Object.keys(moduleNode.secretSlots)) {
420
- const bound = secretWiring[key];
421
- ctxSecrets[key] = typeof bound === "object" && bound !== null ? {
422
- ...bound,
423
- [MODULE_SECRET_KEY]: key
424
- } : bound;
425
- }
426
- const markSecretsUsed = (values) => {
427
- for (const value of values) for (const key of Object.keys(ctxSecrets)) if (value === ctxSecrets[key]) usedSecrets.add(key);
428
- };
429
- const ctxParams = {};
430
- for (const key of Object.keys(moduleNode.paramSlots)) {
431
- const bound = paramWiring[key];
432
- ctxParams[key] = typeof bound === "object" && bound !== null ? {
433
- ...bound,
434
- [MODULE_PARAM_KEY]: key
435
- } : bound;
436
- }
437
- const markParamsUsed = (values) => {
438
- for (const value of values) for (const key of Object.keys(ctxParams)) if (value === ctxParams[key]) usedParams.add(key);
439
- };
440
- const provision = (child, opts) => {
441
- const id = opts?.id ?? child.name;
442
- const provisionWiring = opts?.deps;
443
- const provisionSecrets = opts?.secrets;
444
- const provisionInput = opts?.input;
445
- const provisionParams = opts?.params;
446
- if (typeof id !== "string" || id.length === 0) throw new LoadError(`provision() requires a non-empty id (module "${moduleNode.name}").`);
447
- if (!isConfigKeySegment(id)) throw new LoadError(`provision() id "${id}" (module "${moduleNode.name}") must contain only ASCII letters and digits ([A-Za-z0-9]) — the id becomes an address segment, and addresses derive deterministic config keys (segments uppercased and joined with "_"). "${id}" would put "${id.toUpperCase()}" inside the derived key. ("_" collides with the key separator and "." with the address separator.)`);
448
- if (localIds.has(id)) throw new LoadError(`Duplicate provision id "${id}" in module "${moduleNode.name}".`);
449
- const untrusted = child;
450
- if (!isNode(untrusted) || untrusted.kind !== "service" && untrusted.kind !== "resource" && untrusted.kind !== "module") throw new LoadError(`provision("${id}") expects a branded service, resource, or module node (construct it with the service()/resource()/module() factories or a pack's own).`);
451
- localIds.add(id);
452
- const fullAddress = address === void 0 ? id : `${address}.${id}`;
453
- if (child.kind === "resource") {
454
- if (provisionWiring !== void 0) throw new LoadError(`provision("${id}") received deps for a resource — a resource has no dependency slots to satisfy.`);
455
- if (provisionSecrets !== void 0) throw new LoadError(`provision("${id}") received secrets for a resource — a resource has no secret slots to satisfy.`);
456
- if (provisionInput !== void 0) throw new LoadError(`provision("${id}") received an input binding for a resource — a resource declares no input schema.`);
457
- if (provisionParams !== void 0) throw new LoadError(`provision("${id}") received params for a resource — a resource has no params to satisfy.`);
458
- if (child.type.length === 0) throw new LoadError(`provision("${id}") received a resource with an empty node type.`);
459
- byId.set(fullAddress, child);
460
- nodes.push({
461
- id: fullAddress,
462
- parent: selfId,
463
- node: child
464
- });
465
- ports.push({
466
- node: fullAddress,
467
- direction: "out",
468
- name: RESOURCE_OUT_PORT,
469
- contractKind: child.provides.kind
470
- });
471
- return refForResource(fullAddress, child);
472
- }
473
- const localWiring = { ...provisionWiring ?? {} };
474
- markUsed(Object.values(localWiring));
475
- const localSecrets = { ...provisionSecrets ?? {} };
476
- markSecretsUsed(Object.values(localSecrets));
477
- const localParams = { ...provisionParams ?? {} };
478
- markParamsUsed(Object.values(localParams));
479
- if (child.kind === "service") {
480
- if (provisionSecrets !== void 0) throw new LoadError(`provision("${id}") received secrets for a service — a service takes its secrets as envSecret(...) leaves of its \`input\` binding (ADR-0042), not a secrets map.`);
481
- if (child.inputSchema !== void 0 && provisionInput === void 0) throw new LoadError(`Input of provisioned service "${id}" is not bound (module "${moduleNode.name}") — the service declares an input schema; bind it with \`input: { … }\` on its provision() call.`);
482
- if (child.inputSchema === void 0 && provisionInput !== void 0) throw new LoadError(`provision("${id}") received an input binding, but the service declares no input schema (module "${moduleNode.name}").`);
483
- if (provisionInput !== void 0) {
484
- const leaves = [];
485
- deepValues(provisionInput, leaves);
486
- markSecretsUsed(leaves);
487
- markParamsUsed(leaves);
488
- inputBindings.push({
489
- serviceAddress: fullAddress,
490
- binding: blindCast(provisionInput)
491
- });
492
- }
493
- validateServiceParamBinding(child, id, localParams, moduleNode.name);
494
- for (const [slot, binding] of Object.entries(localParams)) paramBindings.push({
495
- serviceAddress: fullAddress,
496
- slot,
497
- binding
498
- });
499
- const inputs = serviceInputs(child, fullAddress);
500
- nodes.push(...inputs.nodes, {
501
- id: fullAddress,
502
- parent: selfId,
503
- node: child
504
- });
505
- edges.push(...inputs.edges, ...wiringEdges(localWiring, fullAddress));
506
- ports.push(...boundaryPortsOf(fullAddress, child));
507
- recordAuthoredWiring(fullAddress, localWiring);
508
- pending.push({
509
- deps: child.inputs,
510
- wiring: localWiring,
511
- targetId: fullAddress,
512
- targetKind: "service",
513
- enclosingModuleName: moduleNode.name
514
- });
515
- byId.set(fullAddress, child);
516
- return refFor(fullAddress, child);
517
- }
518
- if (provisionInput !== void 0) throw new LoadError(`provision("${id}") received an input binding for a module — a module has no input schema; bind the input on the service that declares it.`);
519
- validateSecretBinding(child, id, localSecrets, moduleNode.name);
520
- validateParamNeedBinding(child, id, localParams, moduleNode.name);
521
- edges.push(...wiringEdges(localWiring, fullAddress));
522
- recordAuthoredWiring(fullAddress, localWiring);
523
- pending.push({
524
- deps: child.deps,
525
- wiring: localWiring,
526
- targetId: fullAddress,
527
- targetKind: "module",
528
- enclosingModuleName: moduleNode.name
529
- });
530
- const childOutputs = flatten(child, fullAddress, fullAddress, localWiring, localSecrets, localParams, nodes, edges, pending, inputBindings, paramBindings, byId, ports, authoredEdges);
531
- nodes.push({
532
- id: fullAddress,
533
- parent: selfId,
534
- node: child
535
- });
536
- byId.set(fullAddress, child);
537
- const brandedOutputs = {};
538
- for (const [key, value] of Object.entries(childOutputs)) brandedOutputs[key] = typeof value === "object" && value !== null ? {
539
- ...value,
540
- [AUTHORED_PORT]: {
541
- node: fullAddress,
542
- name: key
543
- }
544
- } : value;
545
- return blindCast({
546
- id: fullAddress,
547
- ...brandedOutputs
548
- });
549
- };
550
- const ctx = blindCast({
551
- inputs: ctxInputs,
552
- secrets: ctxSecrets,
553
- params: ctxParams,
554
- provision: blindCast(provision)
555
- });
556
- const outputs = blindCast(moduleNode.body(ctx) ?? {});
557
- markUsed(Object.values(outputs));
558
- for (const key of Object.keys(moduleNode.deps)) if (!used.has(key)) throw new LoadError(`Module "${moduleNode.name}" declares input "${key}" but never forwards it into a provision nor returns it as an output.`);
559
- for (const key of Object.keys(moduleNode.secretSlots)) if (!usedSecrets.has(key)) throw new LoadError(`Module "${moduleNode.name}" declares secret "${key}" but never forwards it into a provision.`);
560
- for (const key of Object.keys(moduleNode.paramSlots)) if (!usedParams.has(key)) throw new LoadError(`Module "${moduleNode.name}" declares param "${key}" but never forwards it into a provision.`);
561
- for (const [key, contract] of Object.entries(moduleNode.expose)) {
562
- const port = outputs[key];
563
- if (port === void 0) throw new LoadError(`Module "${moduleNode.name}" declares expose "${key}" but its body did not return a port for it.`);
564
- if (!satisfiesRequired(port, contract)) throw new LoadError(`Module "${moduleNode.name}"'s returned port for expose "${key}" does not satisfy its declared contract.`);
565
- const from = authoredSourceOf(port);
566
- if (from !== void 0) authoredEdges.push({
567
- from,
568
- to: {
569
- node: selfId,
570
- direction: "out",
571
- name: key
572
- }
573
- });
574
- }
575
- return outputs;
576
- }
577
- function loadModule(root, opts) {
578
- const rootId = opts?.id ?? root.name;
579
- const rootDepKeys = Object.keys(root.deps);
580
- if (rootDepKeys.length > 0) {
581
- const names = rootDepKeys.map((k) => `"${k}"`).join(", ");
582
- throw new LoadError(`Module "${root.name}" declares input${rootDepKeys.length > 1 ? "s" : ""} ${names} but is being deployed as the root — a root has no enclosing scope to wire them; compose "${root.name}" from another module that provisions and wires it instead.`);
583
- }
584
- const rootSecretKeys = Object.keys(root.secretSlots);
585
- if (rootSecretKeys.length > 0) {
586
- const names = rootSecretKeys.map((k) => `"${k}"`).join(", ");
587
- throw new LoadError(`Module "${root.name}" declares secret${rootSecretKeys.length > 1 ? "s" : ""} ${names} but is being deployed as the root — a root has no enclosing scope to bind them; the root binds secrets with envSecret('NAME'), it does not declare secret slots of its own.`);
588
- }
589
- const rootParamKeys = Object.keys(root.paramSlots);
590
- if (rootParamKeys.length > 0) {
591
- const names = rootParamKeys.map((k) => `"${k}"`).join(", ");
592
- throw new LoadError(`Module "${root.name}" declares param${rootParamKeys.length > 1 ? "s" : ""} ${names} but is being deployed as the root — a root has no enclosing scope to bind them; the root binds params directly on each provision() call, it does not declare param-forwarding slots of its own.`);
593
- }
594
- const nodes = [];
595
- const edges = [];
596
- const pending = [];
597
- const inputBindings = [];
598
- const paramBindings = [];
599
- const byId = /* @__PURE__ */ new Map();
600
- const ports = [];
601
- const authoredEdges = [];
602
- flatten(root, void 0, rootId, {}, {}, {}, nodes, edges, pending, inputBindings, paramBindings, byId, ports, authoredEdges);
603
- for (const entry of pending) validateWiring(entry, byId);
604
- assertDependencyDag(edges);
605
- const rootGraphNode = {
606
- id: rootId,
607
- parent: void 0,
608
- node: root
609
- };
610
- return {
611
- root: rootGraphNode,
612
- nodes: [...topoSort(nodes, edges), rootGraphNode],
613
- edges,
614
- ports,
615
- authoredEdges,
616
- inputBindings,
617
- params: paramBindings
618
- };
619
- }
620
- /**
621
- * The dependency edges must form a DAG — a cycle means neither producer can
622
- * deploy first. Resources take no wiring, so only service/module-to-service/module
623
- * edges can ever participate in a cycle; no special-casing needed.
624
- */
625
- function assertDependencyDag(edges) {
626
- const adjacency = /* @__PURE__ */ new Map();
627
- for (const edge of edges) {
628
- if (edge.kind !== "dependency") continue;
629
- const targets = adjacency.get(edge.from) ?? [];
630
- targets.push(edge.to);
631
- adjacency.set(edge.from, targets);
632
- }
633
- const visiting = /* @__PURE__ */ new Set();
634
- const done = /* @__PURE__ */ new Set();
635
- const stack = [];
636
- const visit = (id) => {
637
- if (done.has(id)) return;
638
- if (visiting.has(id)) throw new LoadError(`Dependency cycle: ${[...stack.slice(stack.indexOf(id)), id].join(" → ")} — no deploy order exists.`);
639
- visiting.add(id);
640
- stack.push(id);
641
- for (const next of adjacency.get(id) ?? []) visit(next);
642
- stack.pop();
643
- visiting.delete(id);
644
- done.add(id);
645
- };
646
- for (const id of adjacency.keys()) visit(id);
647
- }
648
- /**
649
- * Builds the in-memory graph from a root node. A service root walks its own
650
- * `inputs`; a module root executes its body (wiring, not user code — the
651
- * designed exception to imports-run-nothing) and recursively flattens every
652
- * module it provisions into one graph of hierarchical addresses. A malformed
653
- * graph is a `LoadError` that names its fix; the individual validation rules
654
- * live with `loadService` / `loadModule` and are covered by name in the Load
655
- * tests. Executes nothing of the user's own code beyond module bodies.
656
- */
657
- function Load(root, opts) {
658
- if (!isNode(root)) throw new LoadError("Load expects a branded service or module node (construct it with the service()/module() factories).");
659
- if (root.kind === "module") return loadModule(root, opts);
660
- if (root.kind === "service") return loadService(root, opts?.id ?? "root");
661
- throw new LoadError("Load expects a service or module root (received another node kind).");
662
- }
663
- blindCast(Symbol.for("prisma:secret-box"));
664
- //#endregion
665
- //#region ../../0-framework/3-tooling/cli/dist/load-entry-BjRb7YB3.mjs
666
- /**
667
- * Synchronous Node resolve hook so that entry modules may import relative
668
- * files using the specifier forms TypeScript accepts by default —
669
- * extensionless `./service` and `./service.js` for a `.ts` source file —
670
- * without requiring `allowImportingTsExtensions` in every consumer's tsconfig.
671
- *
672
- * Resolution only; uses TypeScript's own documented mapping: for a specifier
673
- * Node could not resolve, strip any JS-family extension and probe the
674
- * corresponding TypeScript source; first candidate that exists on disk wins.
675
- * Format-specific rules: `.mjs` → `.mts`; `.cjs` → `.cts`; `.js` and
676
- * extensionless → `.ts`, `.mts`, `.tsx`, then `./index.ts`. Bare and package
677
- * specifiers are never touched. Existing `./x.ts` imports keep working —
678
- * Node resolves them before the hook fires (ADR-0005: no transform, no
679
- * guessing, deterministic TypeScript rule).
680
- *
681
- * Bun resolves `./x.js` and `./x` to `x.ts` natively, so the hook is a
682
- * no-op under Bun. Nothing is registered there.
683
- */
684
- let registered = false;
685
- /**
686
- * Registers the resolve hook once (idempotent). Call at the start of
687
- * `loadEntry` so every module in the entry graph benefits, including those
688
- * imported lazily after the entry itself loads.
689
- */
690
- function registerEntryResolution() {
691
- if (registered || typeof process.versions.bun === "string") return;
692
- if (typeof mod.registerHooks !== "function") return;
693
- registered = true;
694
- mod.registerHooks({ resolve(specifier, context, nextResolve) {
695
- try {
696
- return nextResolve(specifier, context);
697
- } catch (error) {
698
- if (!isRelativeSpecifier(specifier) || context.parentURL === void 0 || !isModuleNotFoundError(error)) throw error;
699
- for (const candidate of sourceCandidates(new URL(specifier, context.parentURL))) if (existsSync(fileURLToPath(candidate))) return nextResolve(candidate.href, context);
700
- throw error;
701
- }
702
- } });
703
- }
704
- /**
705
- * TypeScript's extension mapping: for a JS-family or extensionless URL,
706
- * produce the source candidates to probe. Format-specific: `.mjs` maps only
707
- * to `.mts`; `.cjs` maps only to `.cts`; `.js` and extensionless probe
708
- * `.ts`, `.mts`, `.tsx` (keeping `.tsx` so the JSX diagnostic fires), then
709
- * `./index.ts`.
710
- */
711
- function sourceCandidates(resolved) {
712
- const href = resolved.href;
713
- if (href.endsWith(".mjs")) {
714
- const base = href.slice(0, -4);
715
- return [new URL(`${base}.mts`)];
716
- }
717
- if (href.endsWith(".cjs")) {
718
- const base = href.slice(0, -4);
719
- return [new URL(`${base}.cts`)];
720
- }
721
- const base = href.endsWith(".js") ? href.slice(0, -3) : href;
722
- return [
723
- new URL(`${base}.ts`),
724
- new URL(`${base}.mts`),
725
- new URL(`${base}.tsx`),
726
- new URL(`${base}/index.ts`)
727
- ];
728
- }
729
- function isRelativeSpecifier(specifier) {
730
- return specifier.startsWith("./") || specifier.startsWith("../");
731
- }
732
- function isModuleNotFoundError(error) {
733
- if (!(error instanceof Error)) return false;
734
- if (!("code" in error)) return false;
735
- return error.code === "ERR_MODULE_NOT_FOUND";
736
- }
737
- /**
738
- * `loadEntry` imports a user's topology with the host runtime's own module
739
- * loader — under node (the CLI's shebang runtime), that loader strips
740
- * TypeScript types but has no JSX transform (ADR-0005: the framework
741
- * doesn't bundle or transform the app's code; deploy loading is no
742
- * exception). A `.tsx`/`.jsx` file anywhere in the topology's import graph
743
- * dies with node's raw `ERR_UNKNOWN_FILE_EXTENSION`, which names the file
744
- * but not the cause or the fix. This turns that one case into structured
745
- * error parts (summary/why/fix) that do — every other load failure (syntax
746
- * errors, missing files, non-JSX unknown extensions) is untouched.
747
- */
748
- const UNKNOWN_EXTENSION_CODE = "ERR_UNKNOWN_FILE_EXTENSION";
749
- const JSX_EXTENSIONS = [".tsx", ".jsx"];
750
- function errorCode(error) {
751
- return "code" in error && typeof error.code === "string" ? error.code : void 0;
752
- }
753
- function unknownExtensionPath(error) {
754
- if (!(error instanceof Error)) return void 0;
755
- if (errorCode(error) !== UNKNOWN_EXTENSION_CODE) return void 0;
756
- return /Unknown file extension "\.\w+" for (.+)$/.exec(error.message)?.[1];
757
- }
758
- /**
759
- * Returns structured error parts when `error` is node's
760
- * `ERR_UNKNOWN_FILE_EXTENSION` for a `.tsx`/`.jsx` file — `undefined` for
761
- * every other error (including unknown-extension failures for some other
762
- * extension), so the caller can fall through to its normal rethrow.
763
- */
764
- function explainJsxLoadError(error, entryPath) {
765
- const offendingPath = unknownExtensionPath(error);
766
- if (offendingPath === void 0) return void 0;
767
- if (!JSX_EXTENSIONS.some((ext) => offendingPath.endsWith(ext))) return void 0;
768
- return {
769
- summary: `"${offendingPath}" can't be loaded.`,
770
- why: `deploy loads "${entryPath}"'s topology with node's own module loader, which strips TypeScript types but has no JSX transform — so a .tsx/.jsx file can't sit anywhere in that import graph.`,
771
- fix: "Precompile that file in your own build (transform the JSX away, keep the real npm packages external) and import the compiled output instead of the raw .tsx/.jsx — see examples/email/scripts/build.ts in the prisma/composer repo for a worked example."
772
- };
773
- }
774
- /**
775
- * Pipeline step 1 (deploy-cli.md § The pipeline): import the entry module
776
- * (resolved against cwd) and require its default export to be a node — a
777
- * service or module, branded by core's factories. Whatever this module exports
778
- * IS the application; nothing else marks a root (ADR-0003).
779
- */
780
- async function loadEntry(entryArg, cwd) {
781
- registerEntryResolution();
782
- const resolvedPath = path.resolve(cwd, entryArg);
783
- let mod;
784
- try {
785
- mod = await import(pathToFileURL(resolvedPath).href);
786
- } catch (error) {
787
- const explained = explainJsxLoadError(error, resolvedPath);
788
- if (explained !== void 0) throw new CliStructuredError("COMPOSE.ENTRY_UNLOADABLE", explained.summary, {
789
- why: explained.why,
790
- fix: explained.fix,
791
- where: { path: resolvedPath },
792
- cause: error
793
- });
794
- throw new CliStructuredError("COMPOSE.ENTRY_UNLOADABLE", `Failed to import entry module "${resolvedPath}": ${error instanceof Error ? error.message : String(error)}`, {
795
- where: { path: resolvedPath },
796
- cause: error
797
- });
798
- }
799
- const root = blindCast(mod).default;
800
- if (!isNode(root) || root.kind === "dependency" || root.kind === "resource") throw new CliStructuredError("COMPOSE.ENTRY_EXPORT_INVALID", `Entry module "${resolvedPath}" must default-export a node (a service or a module).`, {
801
- fix: "Construct it with service() or module() from @prisma/composer.",
802
- where: { path: resolvedPath }
803
- });
804
- return {
805
- path: resolvedPath,
806
- root: blindCast(root)
807
- };
808
- }
809
- //#endregion
810
- //#region ../../0-framework/3-tooling/assemble/dist/index.mjs
811
- /**
812
- * A user-facing assembly failure, structured at origin (base-type rule 6):
813
- * a `CliStructuredError` whose code names which way assembly went wrong.
814
- * This package's second consumer is the programmatic deploy API, not just
815
- * the CLI — hosts branch on `error.code`, the CLI renders the envelope.
816
- */
817
- var AssembleError = class extends CliStructuredError {
818
- constructor(code, summary, options) {
819
- super(code, summary, options);
820
- }
821
- };
822
- /**
823
- * The registry route for one service's build: extension by
824
- * `build.extension`, node descriptor by `build.type`, kind must be "build".
825
- * The CLI's coverage validation reports the same misses earlier with the
826
- * config fix; these errors are the backstop for programmatic callers.
827
- */
828
- function buildDescriptorAssemble(config, node, address, cwd) {
829
- const { extension, type } = node.build;
830
- const extensionDescriptor = config.extensions.find((candidate) => candidate.id === extension);
831
- if (extensionDescriptor === void 0) throw new AssembleError("ASSEMBLE.EXTENSION_MISSING", `No extension "${extension}" is configured (needed by service "${node.name}"'s build).`, { fix: "Add it to prisma-composer.config.ts's `extensions`." });
832
- const nodeDescriptor = extensionDescriptor.nodes[type];
833
- if (nodeDescriptor === void 0) throw new AssembleError("ASSEMBLE.DESCRIPTOR_MISSING", `Extension "${extension}" has no descriptor for build type "${type}".`, { why: `Known types: ${Object.keys(extensionDescriptor.nodes).join(", ")}.` });
834
- if (nodeDescriptor.kind !== "build") throw new AssembleError("ASSEMBLE.DESCRIPTOR_KIND_MISMATCH", `Extension "${extension}"'s descriptor for type "${type}" is a "${nodeDescriptor.kind}" descriptor.`, { why: "Assembling a service build needs a \"build\" descriptor." });
835
- return nodeDescriptor.assemble({
836
- build: node.build,
837
- address,
838
- cwd
839
- });
840
- }
841
- async function assembleServices(graph, config, cwd, run) {
842
- const runAssembler = run ?? ((node, address, nodeCwd) => buildDescriptorAssemble(config, node, address, nodeCwd));
843
- const serviceNodes = graph.nodes.filter((n) => n.node.kind === "service");
844
- if (serviceNodes.length === 0) throw new AssembleError("ASSEMBLE.SERVICE_MISSING", "The loaded graph has no service to assemble.");
845
- const bundles = {};
846
- for (const { id, node } of serviceNodes) try {
847
- bundles[id] = await runAssembler(node, id, cwd);
848
- } catch (error) {
849
- if (CliStructuredError.is(error)) throw error;
850
- throw new AssembleError("ASSEMBLE.BUILD_FAILED", error instanceof Error ? error.message : String(error), {
851
- meta: { address: id },
852
- cause: error
853
- });
854
- }
855
- return { bundles };
856
- }
857
- //#endregion
858
- //#region ../../0-framework/3-tooling/cli/dist/pipeline-C7gNjMzJ.mjs
859
- /**
860
- * Pipeline step: find and load `prisma-composer.config.ts` (ADR-0017) — the ONE
861
- * file that imports control-plane code. Discovery is the standard walk-up
862
- * from the deploy entry's directory (mirrors prisma/orm's config-loader);
863
- * loading is c12 with that explicit path (rc/global/package.json lookups
864
- * disabled), so the config file's own static imports resolve from the app
865
- * root by whatever package manager runs — no specifier construction, no
866
- * anchoring.
867
- *
868
- * Two shapes of the same machinery:
869
- *
870
- * loadAppConfigDiagnostics — returns the evaluated value together with
871
- * EVERY problem found, and never throws. This is the shape the engine
872
- * command family consumes: the engine renders diagnostics itself and
873
- * decides per command whether a broken section is fatal, so a loader that
874
- * threw on the first bad field would both hide the rest and bypass that
875
- * rendering.
876
- *
877
- * loadAppConfig — the same load, throwing its first diagnostic. The
878
- * clipanion CLI still runs on it; it goes when clipanion does.
879
- */
880
- /**
881
- * Accepted config file names, in precedence order: when several sit in one
882
- * directory the first one found wins. The JavaScript spellings exist so a
883
- * project whose own TypeScript build would otherwise compile the config file
884
- * (no `include`, a `rootDir`, `module: commonjs`) can keep it out of that
885
- * build's sight.
886
- */
887
- const CONFIG_FILENAMES = [
888
- "prisma-composer.config.ts",
889
- "prisma-composer.config.mts",
890
- "prisma-composer.config.mjs",
891
- "prisma-composer.config.js"
892
- ];
893
- /** The canonical spelling, used in messages and docs. */
894
- const CONFIG_FILENAME = CONFIG_FILENAMES[0];
895
- /** The accepted spellings as one glob-like string for messages. */
896
- const CONFIG_FILENAME_PATTERN = "prisma-composer.config.{ts,mts,mjs,js}";
897
- /** Walks UP from the entry file's directory looking for one of CONFIG_FILENAMES; undefined when the walk hits the filesystem root. */
898
- function findConfigPathForEntry(entryPath) {
899
- let current = path.dirname(path.resolve(entryPath));
900
- while (true) {
901
- for (const filename of CONFIG_FILENAMES) {
902
- const candidate = path.join(current, filename);
903
- if (fs.existsSync(candidate)) return candidate;
904
- }
905
- const parent = path.dirname(current);
906
- if (parent === current) return void 0;
907
- current = parent;
908
- }
909
- }
910
- function missingConfigError(entryPath) {
911
- const searchedFrom = path.dirname(path.resolve(entryPath));
912
- return new CliStructuredError("CONFIG.FILE_MISSING", `No ${CONFIG_FILENAME_PATTERN} found walking up from "${searchedFrom}".`, {
913
- why: "The deploy needs the app's config file.",
914
- fix: "Create one next to (or above) the entry, default-exporting defineConfig({ extensions: [...], state: ... }) from '@prisma/composer/config'.",
915
- where: { path: searchedFrom }
916
- });
917
- }
918
- function fieldError(configPath, field, requirement) {
919
- return new CliStructuredError("CONFIG.FIELD_INVALID", `${path.basename(configPath)}: \`${field}\` ${requirement}.`, {
920
- fix: "See defineConfig() in '@prisma/composer/config'.",
921
- meta: { field }
922
- });
923
- }
924
- function isRecord(value) {
925
- return typeof value === "object" && value !== null;
926
- }
927
- /**
928
- * Field-by-field validation of the loaded default export — deliberately no
929
- * schema library: each check is a structured error naming the offending field.
930
- *
931
- * Collects rather than throws, so one bad config reports every bad field
932
- * instead of only the first. The `extensions` and `state` checks are
933
- * independent, and within `extensions` each entry is judged on its own; a
934
- * field whose own shape check already failed is not probed further, because
935
- * anything derived from it would be noise rather than a second finding.
936
- */
937
- function configShapeDiagnostics(loaded, configPath) {
938
- if (!isRecord(loaded) || Object.keys(loaded).length === 0) return [new CliStructuredError("CONFIG.EXPORT_INVALID", `"${configPath}" exported no config.`, {
939
- fix: "It must default-export defineConfig({ extensions: [...], state: ... }) from '@prisma/composer/config'.",
940
- where: { path: configPath }
941
- })];
942
- const diagnostics = [];
943
- const extensions = loaded["extensions"];
944
- if (!Array.isArray(extensions)) diagnostics.push(fieldError(configPath, "extensions", "must be an array"));
945
- else {
946
- const seen = /* @__PURE__ */ new Set();
947
- for (const [index, entry] of extensions.entries()) {
948
- if (!isRecord(entry)) {
949
- diagnostics.push(fieldError(configPath, `extensions[${index}]`, "must be an extension descriptor object"));
950
- continue;
951
- }
952
- const id = entry["id"];
953
- if (typeof id !== "string" || id.length === 0) diagnostics.push(fieldError(configPath, `extensions[${index}].id`, "must be a non-empty string (the extension package name)"));
954
- else if (seen.has(id)) diagnostics.push(new CliStructuredError("CONFIG.EXTENSION_DUPLICATE", `${path.basename(configPath)}: extension "${id}" is listed more than once in \`extensions\`.`));
955
- else seen.add(id);
956
- if (!isRecord(entry["nodes"])) diagnostics.push(fieldError(configPath, `extensions[${index}].nodes`, "must be an object (the node-ID → control registry)"));
957
- }
958
- }
959
- const state = loaded["state"];
960
- if (!isRecord(state) || typeof state["extension"] !== "string" || typeof state["create"] !== "function") diagnostics.push(fieldError(configPath, "state", "must be a state descriptor (e.g. prismaState())"));
961
- return diagnostics;
962
- }
963
- /** The throwing form of configShapeDiagnostics: raises the first finding, returns the same object typed. Used by the clipanion pipeline. */
964
- function validateConfigShape(loaded, configPath) {
965
- const [first] = configShapeDiagnostics(loaded, configPath);
966
- if (first !== void 0) throw first;
967
- return blindCast(loaded);
968
- }
969
- /**
970
- * Evaluates `configPath` with c12 (explicit file; rc / global-rc /
971
- * package.json lookups disabled). `verifySamePath` runs the same-file check
972
- * against the discovered path — see loadAppConfigDiagnostics for when it does
973
- * not apply.
974
- */
975
- async function evaluateConfig(configPath, verifySamePath) {
976
- let result;
977
- try {
978
- result = await c12.loadConfig({
979
- name: "prisma-composer",
980
- configFile: configPath,
981
- cwd: path.dirname(configPath),
982
- rcFile: false,
983
- globalRc: false,
984
- packageJson: false
985
- });
986
- } catch (error) {
987
- return {
988
- value: void 0,
989
- diagnostics: [new CliStructuredError("CONFIG.EVALUATION_FAILED", `Evaluating "${configPath}" failed: ${error instanceof Error ? error.message : String(error)}`, {
990
- where: { path: configPath },
991
- cause: error
992
- })]
993
- };
994
- }
995
- const loadedFile = result.configFile;
996
- if (verifySamePath && (typeof loadedFile !== "string" || fs.realpathSync(loadedFile) !== fs.realpathSync(configPath))) return {
997
- value: result.config,
998
- diagnostics: [new CliStructuredError("CONFIG.PATH_MISMATCH", `Config loading resolved "${String(loadedFile)}" instead of the discovered "${configPath}".`, {
999
- why: "Refusing to deploy against a different file.",
1000
- where: { path: configPath }
1001
- })]
1002
- };
1003
- return {
1004
- value: result.config,
1005
- diagnostics: configShapeDiagnostics(result.config, configPath)
1006
- };
1007
- }
1008
- /**
1009
- * The front of every config load, shared by the throwing and the
1010
- * diagnostics-list shapes: verify the installed tree can evaluate a config at
1011
- * all, then settle which file to load — the section's path, or the
1012
- * entry-anchored walk.
1013
- *
1014
- * The effect-resolution check comes first because evaluating a config imports
1015
- * alchemy's provider tree: in a tree where alchemy resolves an `effect` we did
1016
- * not pin, nothing downstream can load, so the dependency conflict is the
1017
- * finding with the fix in it and every later failure is its symptom.
1018
- */
1019
- function configSource(request) {
1020
- const resolvedEntry = path.resolve(request.entryPath);
1021
- const effectConflict = effectResolutionDiagnostic(request.cwd ?? path.dirname(resolvedEntry));
1022
- if (effectConflict !== void 0) return {
1023
- ok: false,
1024
- path: void 0,
1025
- diagnostic: effectConflict
1026
- };
1027
- if (request.configPath === void 0) {
1028
- const discovered = findConfigPathForEntry(resolvedEntry);
1029
- return discovered === void 0 ? {
1030
- ok: false,
1031
- path: void 0,
1032
- diagnostic: missingConfigError(resolvedEntry)
1033
- } : {
1034
- ok: true,
1035
- path: discovered,
1036
- explicit: false
1037
- };
1038
- }
1039
- const configPath = request.configPath;
1040
- if (!path.isAbsolute(configPath)) return {
1041
- ok: false,
1042
- path: configPath,
1043
- diagnostic: new CliStructuredError("CONFIG.PATH_NOT_ABSOLUTE", `The \`composer\` config section's configPath must arrive absolute, and "${configPath}" is relative.`, {
1044
- why: "The section validator resolves a relative configPath against the config file that declared it; a relative value here means that resolution was skipped.",
1045
- fix: "Run the configPath through the composer section validator, or resolve it against its declaring file before constructing the load request.",
1046
- where: { path: configPath }
1047
- })
1048
- };
1049
- if (!fs.existsSync(configPath)) return {
1050
- ok: false,
1051
- path: configPath,
1052
- diagnostic: new CliStructuredError("CONFIG.FILE_MISSING", `The \`composer\` config section points at "${configPath}", which does not exist.`, {
1053
- why: "An explicit configPath is used as given — there is no walk to fall back on.",
1054
- fix: "Correct `configPath` in the `composer` section of prisma.config.ts, or remove it to search upward from the entry.",
1055
- where: { path: configPath }
1056
- })
1057
- };
1058
- return {
1059
- ok: true,
1060
- path: configPath,
1061
- explicit: true
1062
- };
1063
- }
1064
- /**
1065
- * The throwing form of that front, for the pipeline: the file the load will
1066
- * use, or the finding raised. `explicit` says the section named the file,
1067
- * which is what retires the same-file check for that case.
1068
- */
1069
- function resolveConfigFile(request) {
1070
- const source = configSource(request);
1071
- if (!source.ok) throw source.diagnostic;
1072
- return {
1073
- path: source.path,
1074
- explicit: source.explicit
1075
- };
1076
- }
1077
- /**
1078
- * Loads + validates the config at `configPath`, throwing its first diagnostic.
1079
- * The clipanion CLI's pipeline runs on this; it goes when clipanion does.
1080
- */
1081
- async function loadAppConfig(configPath, verifySamePath = true) {
1082
- const { value, diagnostics } = await evaluateConfig(configPath, verifySamePath);
1083
- const [first] = diagnostics;
1084
- if (first !== void 0) throw first;
1085
- return {
1086
- path: configPath,
1087
- config: validateConfigShape(value, configPath)
1088
- };
1089
- }
1090
- function lookup(extensions, extension, type, expectedKind, what) {
1091
- const ext = extensions.get(extension);
1092
- if (ext === void 0) throw new CliStructuredError("CONFIG.EXTENSION_MISSING", `No extension "${extension}" is configured (needed by ${what}).`, {
1093
- fix: `Add it to ${CONFIG_FILENAME}'s \`extensions\` (import its /control entry and list its descriptor).`,
1094
- meta: {
1095
- extension,
1096
- type
1097
- }
1098
- });
1099
- const descriptor = ext.nodes[type];
1100
- if (descriptor === void 0) throw new CliStructuredError("CONFIG.DESCRIPTOR_MISSING", `Extension "${extension}" has no descriptor for node type "${type}" (needed by ${what}).`, {
1101
- why: `Known types: ${Object.keys(ext.nodes).join(", ")}.`,
1102
- meta: {
1103
- extension,
1104
- type
1105
- }
1106
- });
1107
- if (descriptor.kind !== expectedKind) throw new CliStructuredError("CONFIG.DESCRIPTOR_KIND_MISMATCH", `Extension "${extension}"'s descriptor for node type "${type}" is a "${descriptor.kind}" descriptor — ${what} needs a "${expectedKind}" descriptor.`, { meta: {
1108
- extension,
1109
- type,
1110
- kind: descriptor.kind
1111
- } });
1112
- }
1113
- /** Throws a structured CONFIG.* error on the first uncovered `(extension, type)`; silent when the config covers the whole graph. */
1114
- function validateRegistryCoverage(graph, config) {
1115
- const extensions = new Map(config.extensions.map((descriptor) => [descriptor.id, descriptor]));
1116
- for (const { id, node } of graph.nodes) {
1117
- if (node.kind === "resource") {
1118
- lookup(extensions, node.extension, node.type, "resource", `resource node "${id}"`);
1119
- continue;
1120
- }
1121
- if (node.kind !== "service") continue;
1122
- lookup(extensions, node.extension, node.type, "service", `service node "${id}"`);
1123
- lookup(extensions, node.build.extension, node.build.type, "build", `service node "${id}"'s build descriptor`);
1124
- }
1125
- }
1126
- /**
1127
- * The shared prefix of `deploy`/`destroy`/`dev` (deploy-cli.md § The
1128
- * pipeline; local-dev spec § 6): config discovery/load, entry load, Load,
1129
- * registry coverage validation, name resolution, assemble. Deploy and dev
1130
- * diverge after this — deploy resolves containers/preflight/stack file
1131
- * against the hosted providers, dev against the local ones — so everything
1132
- * up to and including assemble lives here once, consumed verbatim by both
1133
- * `run()` (main.ts) and `runDev()` (dev/run-dev.ts), so the two pipelines
1134
- * cannot drift.
1135
- */
1136
- /**
1137
- * The config step both pipelines share: the effect-resolution check and the
1138
- * choice of config file (load-config.ts's shared front), then evaluation —
1139
- * unless the caller substituted a config, which replaces the evaluation and
1140
- * nothing before it.
1141
- */
1142
- async function loadConfigStep(entryPath, cwd, deps) {
1143
- const { path: configPath, explicit } = resolveConfigFile({
1144
- entryPath,
1145
- configPath: deps.configPath,
1146
- cwd
1147
- });
1148
- return {
1149
- configPath,
1150
- config: deps.config ?? (await loadAppConfig(configPath, !explicit)).config
1151
- };
1152
- }
1153
- /**
1154
- * The pipeline's front — config discovery/load, entry load, name resolution —
1155
- * WITHOUT Load, coverage, or assemble. `log` needs only who the app is (its
1156
- * config and resolved name) to reach the already-running local instance; it
1157
- * neither builds nor provisions, so it must not require the user's built
1158
- * output the way the full pipeline does.
1159
- */
1160
- async function resolveAppIdentity(entry, overrideName, cwd, deps = {}) {
1161
- const { configPath, config } = await loadConfigStep(path.resolve(cwd, entry), cwd, deps);
1162
- const entryModule = await loadEntry(entry, cwd);
1163
- const name = overrideName ?? entryModule.root.name;
1164
- if (name.length === 0) throw new CliStructuredError("COMPOSE.NAME_MISSING", "The root node has no name.", { fix: "Name it at authoring, or pass --name." });
1165
- return {
1166
- configPath,
1167
- config,
1168
- name
1169
- };
1170
- }
1171
- /**
1172
- * Runs config discovery/load, entry load, Load, registry coverage, name
1173
- * resolution, and assemble — steps 1–6 of `run()`. `onAssembleError`, when
1174
- * given, lets a caller decorate an assemble failure with command-specific
1175
- * guidance (destroy's "build first" hint) without this shared step knowing
1176
- * about any one command.
1177
- */
1178
- async function runPipeline(entry, overrideName, cwd, deps = {}, onAssembleError) {
1179
- const { configPath, config } = await loadConfigStep(path.resolve(cwd, entry), cwd, deps);
1180
- const entryModule = await loadEntry(entry, cwd);
1181
- const graph = Load(entryModule.root);
1182
- if (graph.root.node.kind !== "module") throw new CliStructuredError("COMPOSE.ROOT_NOT_MODULE", "The deploy root must be a module.", { fix: "Wrap your service, e.g. export default module('name', ({ provision }) => { provision(service); })." });
1183
- validateRegistryCoverage(graph, config);
1184
- const name = overrideName ?? entryModule.root.name;
1185
- if (name.length === 0) throw new CliStructuredError("COMPOSE.NAME_MISSING", "The root node has no name.", { fix: "Name it at authoring, or pass --name." });
1186
- let assembled;
1187
- try {
1188
- assembled = await assembleServices(graph, config, cwd, deps.runAssembler);
1189
- } catch (error) {
1190
- if (onAssembleError !== void 0 && error instanceof Error) throw onAssembleError(error);
1191
- throw error;
1192
- }
1193
- return {
1194
- configPath,
1195
- config,
1196
- entryModule,
1197
- graph,
1198
- name,
1199
- assembled
1200
- };
1201
- }
1202
- //#endregion
1203
- export { runPipeline as n, resolveAppIdentity as t };
1204
-
1205
- //# sourceMappingURL=pipeline-C7gNjMzJ-CixaMvnR.mjs.map