@prisma/composer-prisma-cloud 0.2.0 → 0.3.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.
- package/dist/buckets-main.mjs +795 -0
- package/dist/buckets-main.mjs.map +1 -0
- package/dist/compute-main.mjs +559 -0
- package/dist/compute-main.mjs.map +1 -0
- package/dist/control.d.mts +34 -5
- package/dist/control.d.mts.map +1 -0
- package/dist/control.mjs +98 -1280
- package/dist/control.mjs.map +1 -1
- package/dist/cron/index.d.mts +54 -4
- package/dist/cron/index.d.mts.map +1 -0
- package/dist/cron/index.mjs +145 -42
- package/dist/cron/index.mjs.map +1 -1
- package/dist/cron/scheduler-entrypoint.mjs +637 -529
- package/dist/cron/scheduler-entrypoint.mjs.map +1 -1
- package/dist/cron/scheduler-service.mjs +145 -42
- package/dist/cron/scheduler-service.mjs.map +1 -1
- package/dist/email/email-entrypoint.mjs +19738 -0
- package/dist/email/email-entrypoint.mjs.map +1 -0
- package/dist/email/email-service.mjs +565 -0
- package/dist/email/email-service.mjs.map +1 -0
- package/dist/email/index.d.mts +282 -0
- package/dist/email/index.d.mts.map +1 -0
- package/dist/email/index.mjs +652 -0
- package/dist/email/index.mjs.map +1 -0
- package/dist/email/testing.d.mts +22 -0
- package/dist/email/testing.d.mts.map +1 -0
- package/dist/email/testing.mjs +1321 -0
- package/dist/email/testing.mjs.map +1 -0
- package/dist/get-port-BYnpbW5H.mjs +111 -0
- package/dist/get-port-BYnpbW5H.mjs.map +1 -0
- package/dist/index.d.mts +37 -6
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +70 -45
- package/dist/index.mjs.map +1 -1
- package/dist/local-target.d.mts +12 -0
- package/dist/local-target.d.mts.map +1 -0
- package/dist/local-target.mjs +6185 -0
- package/dist/local-target.mjs.map +1 -0
- package/dist/param-BTzY0ne5-CW6ojZ3E.mjs +66 -0
- package/dist/param-BTzY0ne5-CW6ojZ3E.mjs.map +1 -0
- package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs +79 -0
- package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs.map +1 -0
- package/dist/postgres-main.mjs +602 -0
- package/dist/postgres-main.mjs.map +1 -0
- package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs +1252 -0
- package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs.map +1 -0
- package/dist/{prisma-next-DlU01kXJ-2sP5mQb6.mjs → prisma-next-BvBwGCIt-DssgnctU.mjs} +21 -80
- package/dist/prisma-next-BvBwGCIt-DssgnctU.mjs.map +1 -0
- package/dist/prisma-next.d.mts +14 -5
- package/dist/prisma-next.d.mts.map +1 -0
- package/dist/prisma-next.mjs +1 -1
- package/dist/provisioned-edges-C1wSO3cx-YC5C19f9.mjs +151 -0
- package/dist/provisioned-edges-C1wSO3cx-YC5C19f9.mjs.map +1 -0
- package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs +47 -0
- package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs.map +1 -0
- package/dist/segments-NpKN-46R-C_LQ2urs.mjs +1454 -0
- package/dist/segments-NpKN-46R-C_LQ2urs.mjs.map +1 -0
- package/dist/{serializer-CX4VYdf_-KKGoAxfx.mjs → serializer-CJiOhF2d-DJUjQj1i.mjs} +34 -44
- package/dist/serializer-CJiOhF2d-DJUjQj1i.mjs.map +1 -0
- package/dist/serializer-Cx5slrV4-xJfH6EWS.d.mts.map +1 -0
- package/dist/storage/index.d.mts +52 -5
- package/dist/storage/index.d.mts.map +1 -0
- package/dist/storage/index.mjs +158 -47
- package/dist/storage/index.mjs.map +1 -1
- package/dist/storage/storage-entrypoint.mjs +370 -271
- package/dist/storage/storage-entrypoint.mjs.map +1 -1
- package/dist/storage/storage-service.mjs +158 -47
- package/dist/storage/storage-service.mjs.map +1 -1
- package/dist/storage/testing.d.mts +7 -6
- package/dist/storage/testing.d.mts.map +1 -0
- package/dist/storage/testing.mjs +4 -21
- package/dist/storage/testing.mjs.map +1 -1
- package/dist/streams/index.d.mts +56 -84
- package/dist/streams/index.d.mts.map +1 -0
- package/dist/streams/index.mjs +158 -47
- package/dist/streams/index.mjs.map +1 -1
- package/dist/streams/streams-entrypoint.mjs +366 -250
- package/dist/streams/streams-entrypoint.mjs.map +1 -1
- package/dist/streams/streams-service.mjs +158 -47
- package/dist/streams/streams-service.mjs.map +1 -1
- package/dist/streams/testing.d.mts.map +1 -0
- package/dist/testing.d.mts.map +1 -0
- package/dist/testing.mjs +1 -1
- package/dist/testing.mjs.map +1 -1
- package/package.json +34 -20
- package/src/exports/control.ts +1 -0
- package/src/exports/cron.ts +1 -0
- package/src/exports/email-testing.ts +1 -0
- package/src/exports/email.ts +1 -0
- package/src/exports/index.ts +1 -0
- package/src/exports/local-target.ts +1 -0
- package/src/exports/prisma-next.ts +1 -0
- package/src/exports/storage-testing.ts +1 -0
- package/src/exports/storage.ts +1 -0
- package/src/exports/streams-testing.ts +1 -0
- package/src/exports/streams.ts +1 -0
- package/src/exports/testing.ts +1 -0
- package/dist/prisma-next-DlU01kXJ-2sP5mQb6.mjs.map +0 -1
- package/dist/provisioned-edges-DIQAR4q4-Bn9op-JG.mjs +0 -151
- package/dist/provisioned-edges-DIQAR4q4-Bn9op-JG.mjs.map +0 -1
- package/dist/serializer-CX4VYdf_-KKGoAxfx.mjs.map +0 -1
|
@@ -0,0 +1,1321 @@
|
|
|
1
|
+
import { type } from "arktype";
|
|
2
|
+
//#region ../../1-prisma-cloud/2-shared-modules/email/dist/testing.mjs
|
|
3
|
+
const nodeBuild = (opts) => ({
|
|
4
|
+
extension: "@prisma/composer/node",
|
|
5
|
+
type: "node",
|
|
6
|
+
module: opts.module,
|
|
7
|
+
entry: opts.entry,
|
|
8
|
+
...opts.dir === void 0 ? {} : { dir: opts.dir }
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**
|
|
12
|
+
*
|
|
13
|
+
* Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes
|
|
14
|
+
* unnecessary**: tighten an input type, add a runtime check that narrows via a type
|
|
15
|
+
* predicate, restructure a generic so the compiler can see the relationship you're
|
|
16
|
+
* asserting, or use {@link castAs} when the value already satisfies the target type.
|
|
17
|
+
* Only when no rewrite is feasible does `blindCast` become the right answer — and at
|
|
18
|
+
* that point, the `Reason` literal you supply must articulate the compromise in
|
|
19
|
+
* language a reviewer can evaluate.
|
|
20
|
+
*
|
|
21
|
+
* The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,
|
|
22
|
+
* that is not a signal to soften the reason; it is a signal to go back and solve the
|
|
23
|
+
* underlying type-system problem properly. An unconvincing justification is rework,
|
|
24
|
+
* not a free pass.
|
|
25
|
+
*
|
|
26
|
+
* `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses
|
|
27
|
+
* the compiler's checks (the input type is `unknown`, the output type is whatever the
|
|
28
|
+
* caller asks for), but it forces the unsafety to be named at the call site instead of
|
|
29
|
+
* smuggled in via a bare `as`. The `Reason` type parameter exists only at compile
|
|
30
|
+
* time — it is not present in the emitted JavaScript — but it is grep-able and
|
|
31
|
+
* visible to future readers.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* const stringValue = blindCast<
|
|
36
|
+
* string,
|
|
37
|
+
* "JSON.parse returns `unknown`; this field is documented to be a string in the API contract"
|
|
38
|
+
* >(parsed[key]);
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @typeParam TargetType - The type the caller is asserting the input has.
|
|
42
|
+
* @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.
|
|
43
|
+
* Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.
|
|
44
|
+
*/
|
|
45
|
+
function blindCast(input) {
|
|
46
|
+
return input;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Core model: node types and the factories that construct them, plain frozen
|
|
50
|
+
* data objects. A node's `extension` + `type` form its deploy-time registry key (ADR-0017).
|
|
51
|
+
*/
|
|
52
|
+
const NODE = Symbol.for("prisma:node");
|
|
53
|
+
const PROVISION_NEED = blindCast(Symbol.for("prisma:provision-need"));
|
|
54
|
+
/** Builds an opaque provisioning need — the declaring package's own brand plus whatever payload its provisioner reads back. */
|
|
55
|
+
function provisionNeed(brand, payload) {
|
|
56
|
+
return blindCast(Object.freeze({
|
|
57
|
+
[PROVISION_NEED]: true,
|
|
58
|
+
brand,
|
|
59
|
+
payload
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
function requireType(type, factory) {
|
|
63
|
+
if (typeof type !== "string" || type.length === 0) throw new Error(`${factory}() requires a non-empty node type.`);
|
|
64
|
+
}
|
|
65
|
+
function requireName(name, factory) {
|
|
66
|
+
if (typeof name !== "string" || name.length === 0) throw new Error(`${factory}() requires a non-empty name.`);
|
|
67
|
+
}
|
|
68
|
+
function requireExtension(extension, factory) {
|
|
69
|
+
if (typeof extension !== "string" || extension.length === 0) throw new Error(`${factory}() requires a non-empty extension (the authoring extension's package name).`);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Core's grammar for every name that becomes a config-key segment —
|
|
73
|
+
* addresses, input/param/secret names: ASCII letters and digits only.
|
|
74
|
+
* Conservative by design so any target medium — POSIX env-var keys
|
|
75
|
+
* included — can uppercase and "_"-join segments without escaping.
|
|
76
|
+
*/
|
|
77
|
+
function isConfigKeySegment(name) {
|
|
78
|
+
return /^[A-Za-z0-9]+$/.test(name);
|
|
79
|
+
}
|
|
80
|
+
function requireConfigKeySegmentName(name, kind, factory) {
|
|
81
|
+
if (!isConfigKeySegment(name)) throw new Error(`${factory}() ${kind} name "${name}" must contain only ASCII letters and digits ([A-Za-z0-9]) — declared names derive deterministic config keys, uppercased and joined with "_" (an input "db"'s param "url" becomes config key "DB_URL"), so an underscore inside a name collides with that separator and any other character has no place in a config key. "${name}" would put "${name.toUpperCase()}" inside the derived key.`);
|
|
82
|
+
}
|
|
83
|
+
function requireConfigKeySegmentNames(names, kind, factory) {
|
|
84
|
+
for (const name of names) requireConfigKeySegmentName(name, kind, factory);
|
|
85
|
+
}
|
|
86
|
+
function freezeParams(params) {
|
|
87
|
+
const frozen = {};
|
|
88
|
+
for (const [name, param] of Object.entries(params)) frozen[name] = Object.freeze({ ...param });
|
|
89
|
+
return Object.freeze(frozen);
|
|
90
|
+
}
|
|
91
|
+
function freezeSecrets(secrets) {
|
|
92
|
+
const frozen = {};
|
|
93
|
+
for (const [name, need] of Object.entries(secrets)) frozen[name] = Object.freeze({ ...need });
|
|
94
|
+
return blindCast(Object.freeze(frozen));
|
|
95
|
+
}
|
|
96
|
+
/** A frozen shallow copy that keeps the caller's declared type. */
|
|
97
|
+
function frozenShallowCopy(obj) {
|
|
98
|
+
return blindCast(Object.freeze({ ...obj }));
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Constructs a branded, frozen Service node — declarations only (inputs,
|
|
102
|
+
* params, build adapter, and the ports it exposes). Pure; carries no runtime behavior.
|
|
103
|
+
*/
|
|
104
|
+
function service(def) {
|
|
105
|
+
requireName(def.name, "service");
|
|
106
|
+
requireExtension(def.extension, "service");
|
|
107
|
+
requireType(def.type, "service");
|
|
108
|
+
requireConfigKeySegmentNames(Object.keys(def.inputs), "input", "service");
|
|
109
|
+
requireConfigKeySegmentNames(Object.keys(def.params), "param", "service");
|
|
110
|
+
requireConfigKeySegmentNames(Object.keys(def.secrets ?? {}), "secret", "service");
|
|
111
|
+
for (const slot of Object.keys(def.secrets ?? {})) if (Object.hasOwn(def.params, slot)) throw new Error(`service() secret slot "${slot}" collides with a param of the same name — a secret slot and a service param derive the same config key (COMPOSER_<addr>_${slot.toUpperCase()}); rename one.`);
|
|
112
|
+
return Object.freeze({
|
|
113
|
+
[NODE]: true,
|
|
114
|
+
kind: "service",
|
|
115
|
+
name: def.name,
|
|
116
|
+
extension: def.extension,
|
|
117
|
+
type: def.type,
|
|
118
|
+
inputs: frozenShallowCopy(def.inputs),
|
|
119
|
+
params: freezeParams(def.params),
|
|
120
|
+
secretSlots: freezeSecrets(def.secrets ?? blindCast({})),
|
|
121
|
+
build: Object.freeze({ ...def.build }),
|
|
122
|
+
expose: def.expose !== void 0 ? frozenShallowCopy(def.expose) : void 0
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Constructs a branded, frozen DependencyEnd. `required` (if given) is the
|
|
127
|
+
* contract Load compares a wired ref against via `satisfies()`; an unnamed
|
|
128
|
+
* end's diagnostic `name` falls back to its `type`.
|
|
129
|
+
*/
|
|
130
|
+
function dependency(def) {
|
|
131
|
+
requireType(def.type, "dependency");
|
|
132
|
+
requireConfigKeySegmentNames(Object.keys(def.connection.params), "param", "dependency");
|
|
133
|
+
const connection = Object.freeze({
|
|
134
|
+
params: freezeParams(def.connection.params),
|
|
135
|
+
hydrate: def.connection.hydrate
|
|
136
|
+
});
|
|
137
|
+
return Object.freeze({
|
|
138
|
+
[NODE]: true,
|
|
139
|
+
kind: "dependency",
|
|
140
|
+
name: def.name !== void 0 && def.name.length > 0 ? def.name : def.type,
|
|
141
|
+
type: def.type,
|
|
142
|
+
connection,
|
|
143
|
+
required: def.required
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* A value wrapper that redacts everywhere except the one explicit reader,
|
|
148
|
+
* `expose()`. Sensitivity is carried by the TYPE (`SecretBox<T>`), not a flag a
|
|
149
|
+
* sink must remember to check: `String(box)`, template interpolation,
|
|
150
|
+
* `JSON.stringify`, and `console.log`/`util.inspect` all print `[REDACTED]`, so
|
|
151
|
+
* a secret can't leak through an accidental log or serialization.
|
|
152
|
+
*
|
|
153
|
+
* Shape matches the platform's own `secrecy` type (pdp-control-plane). The class
|
|
154
|
+
* is nominal enough on its own — no phantom brand.
|
|
155
|
+
*/
|
|
156
|
+
const REDACTED = "[REDACTED]";
|
|
157
|
+
var SecretBox = class {
|
|
158
|
+
#value;
|
|
159
|
+
constructor(value) {
|
|
160
|
+
this.#value = value;
|
|
161
|
+
}
|
|
162
|
+
/** The sole explicit door to the wrapped value. */
|
|
163
|
+
expose() {
|
|
164
|
+
return this.#value;
|
|
165
|
+
}
|
|
166
|
+
toString() {
|
|
167
|
+
return REDACTED;
|
|
168
|
+
}
|
|
169
|
+
toJSON() {
|
|
170
|
+
return REDACTED;
|
|
171
|
+
}
|
|
172
|
+
valueOf() {
|
|
173
|
+
return REDACTED;
|
|
174
|
+
}
|
|
175
|
+
[Symbol.toPrimitive]() {
|
|
176
|
+
return REDACTED;
|
|
177
|
+
}
|
|
178
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
179
|
+
return REDACTED;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
function scalarSchema(name, check) {
|
|
183
|
+
return { "~standard": {
|
|
184
|
+
version: 1,
|
|
185
|
+
vendor: "@prisma/composer",
|
|
186
|
+
validate: (value) => check(value) ? { value } : { issues: [{ message: `expected ${name}, got ${typeof value}` }] }
|
|
187
|
+
} };
|
|
188
|
+
}
|
|
189
|
+
const stringSchema = scalarSchema("string", (v) => typeof v === "string");
|
|
190
|
+
const numberSchema = scalarSchema("number", (v) => typeof v === "number" && Number.isFinite(v));
|
|
191
|
+
function withFacets(schema, opts) {
|
|
192
|
+
return {
|
|
193
|
+
schema,
|
|
194
|
+
...opts.optional !== void 0 ? { optional: opts.optional } : {},
|
|
195
|
+
...opts.default !== void 0 ? { default: opts.default } : {},
|
|
196
|
+
...opts.provision !== void 0 ? { provision: opts.provision } : {}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** A string-valued param. */
|
|
200
|
+
function string(opts = {}) {
|
|
201
|
+
return withFacets(stringSchema, opts);
|
|
202
|
+
}
|
|
203
|
+
/** A number-valued param. */
|
|
204
|
+
function number(opts = {}) {
|
|
205
|
+
return withFacets(numberSchema, opts);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Synchronous hydrate — what the node's `load()` uses so
|
|
209
|
+
* `const { db } = service.load()` reads without `await`. Requires every
|
|
210
|
+
* connection.hydrate to return synchronously; a Promise return is a loud error
|
|
211
|
+
* naming the input (an async client factory must use the async `hydrate` path).
|
|
212
|
+
*/
|
|
213
|
+
function hydrateSync(root, config) {
|
|
214
|
+
const deps = {};
|
|
215
|
+
for (const [name, inputNode] of Object.entries(root.inputs)) {
|
|
216
|
+
const values = config.inputs[name] ?? {};
|
|
217
|
+
const client = inputNode.connection.hydrate(values);
|
|
218
|
+
if (client instanceof Promise) throw new Error(`Connection hydrate for input "${name}" returned a Promise; load() requires a synchronous client factory.`);
|
|
219
|
+
deps[name] = client;
|
|
220
|
+
}
|
|
221
|
+
return deps;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Wraps each of a service's resolved secret values in a redacting `SecretBox`
|
|
225
|
+
* — what the node's `secrets()` accessor returns (ADR-0021, sibling to
|
|
226
|
+
* `load()`/`config()`). The RESOLUTION of a secret's value (the boot
|
|
227
|
+
* double-lookup that reads the platform var the pointer names) is the target
|
|
228
|
+
* pack's job; core is handed the already-resolved strings and only boxes them,
|
|
229
|
+
* so a secret is redacted by TYPE from here on. A declared slot missing from
|
|
230
|
+
* `values` is a target contract violation, named loudly.
|
|
231
|
+
*/
|
|
232
|
+
function hydrateSecrets(root, values) {
|
|
233
|
+
const boxed = {};
|
|
234
|
+
for (const slot of Object.keys(root.secretSlots)) {
|
|
235
|
+
const value = values[slot];
|
|
236
|
+
if (value === void 0) throw new Error(`secret slot "${slot}" has no resolved value — the target must resolve every declared secret before hydrateSecrets().`);
|
|
237
|
+
boxed[slot] = new SecretBox(value);
|
|
238
|
+
}
|
|
239
|
+
return blindCast(boxed);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Walks a node's own params, then each dependency input's connection params —
|
|
243
|
+
* the same enumeration order `configOf` uses, but carrying the raw
|
|
244
|
+
* `ConfigParam` (with its `serialize`/`deserialize`) instead of a pure-data
|
|
245
|
+
* projection.
|
|
246
|
+
*/
|
|
247
|
+
function paramEntries(node) {
|
|
248
|
+
const entries = [];
|
|
249
|
+
for (const [input, value] of Object.entries(node.inputs)) {
|
|
250
|
+
if (typeof value !== "object" || value === null) continue;
|
|
251
|
+
const params = blindCast(value).connection.params;
|
|
252
|
+
for (const [name, param] of Object.entries(params)) entries.push({
|
|
253
|
+
owner: { input },
|
|
254
|
+
name,
|
|
255
|
+
param
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
for (const [name, param] of Object.entries(node.params)) entries.push({
|
|
259
|
+
owner: "service",
|
|
260
|
+
name,
|
|
261
|
+
param
|
|
262
|
+
});
|
|
263
|
+
return entries;
|
|
264
|
+
}
|
|
265
|
+
const configKey = (address, d) => {
|
|
266
|
+
const segments = address.split(".").filter((s) => s.length > 0);
|
|
267
|
+
const owner = d.owner === "service" ? [] : [d.owner.input];
|
|
268
|
+
return [
|
|
269
|
+
"COMPOSER",
|
|
270
|
+
...segments,
|
|
271
|
+
...owner,
|
|
272
|
+
d.name
|
|
273
|
+
].join("_").toUpperCase();
|
|
274
|
+
};
|
|
275
|
+
/**
|
|
276
|
+
* Typed value → its stored string. Service-own literals are JSON-encoded; a
|
|
277
|
+
* dependency-input value is a provisioning ref at deploy (and a resolved
|
|
278
|
+
* string at boot) and passes through untouched — LANDMINE: JSON-encoding it
|
|
279
|
+
* would break the ordering edge Alchemy resolves through it.
|
|
280
|
+
*/
|
|
281
|
+
function encode(owner, value) {
|
|
282
|
+
return owner === "service" ? JSON.stringify(value) : blindCast(value);
|
|
283
|
+
}
|
|
284
|
+
/** Reverses `encode`: JSON-parse a service-own value, take a dependency-input value raw. */
|
|
285
|
+
function decode(owner, raw) {
|
|
286
|
+
return owner === "service" ? JSON.parse(raw) : raw;
|
|
287
|
+
}
|
|
288
|
+
const PARAM_POINTER_PREFIX = "@composer-param-pointer:";
|
|
289
|
+
/** True iff `raw` is a param pointer row (as opposed to a JSON-encoded literal). */
|
|
290
|
+
const isParamPointerRow = (raw) => raw.startsWith(PARAM_POINTER_PREFIX);
|
|
291
|
+
/** Reverses `encodeParamPointer`: the platform var NAME a pointer row points to. */
|
|
292
|
+
const decodeParamPointer = (raw) => raw.slice(24);
|
|
293
|
+
function coerce(raw, d, key) {
|
|
294
|
+
if (!(raw !== void 0 && raw !== "")) {
|
|
295
|
+
if (d.param.default !== void 0) return d.param.default;
|
|
296
|
+
if (d.param.optional === true) return void 0;
|
|
297
|
+
throw new Error(`missing required config param "${d.name}" (env ${key})`);
|
|
298
|
+
}
|
|
299
|
+
if (d.owner === "service" && isParamPointerRow(raw)) return coerceEnvSourcedParam(raw, d, key);
|
|
300
|
+
try {
|
|
301
|
+
return standardValidateSync(d.param.schema, decode(d.owner, raw));
|
|
302
|
+
} catch (cause) {
|
|
303
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
304
|
+
throw new Error(`invalid value for config param "${d.name}" (env ${key}): ${message}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Boot resolution for an env-sourced param: double-lookup (pointer → platform
|
|
309
|
+
* var), then the param's own schema on the raw string — no JSON decode, and
|
|
310
|
+
* no redaction (it's config, not a secret). An UNSET platform var is a loud
|
|
311
|
+
* boot failure naming both the param and the platform var; an EMPTY string is
|
|
312
|
+
* not special-cased here — it reaches the schema like any other value, so it
|
|
313
|
+
* passes iff the schema accepts it (deliberately unlike a literal param's own
|
|
314
|
+
* ""-means-absent rule, and unlike a secret's non-empty requirement).
|
|
315
|
+
*/
|
|
316
|
+
function coerceEnvSourcedParam(raw, d, key) {
|
|
317
|
+
const platformVar = decodeParamPointer(raw);
|
|
318
|
+
const value = process.env[platformVar];
|
|
319
|
+
if (value === void 0) throw new Error(`env-sourced config param "${d.name}" (env ${key} → ${platformVar}) is unset: the platform variable "${platformVar}" was not injected — the deploy did not provision it.`);
|
|
320
|
+
try {
|
|
321
|
+
return standardValidateSync(d.param.schema, value);
|
|
322
|
+
} catch (cause) {
|
|
323
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
324
|
+
throw new Error(`invalid value for env-sourced config param "${d.name}" (env ${key} → ${platformVar}): ${message}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Boot: read each declared param from env by its key, reverse the param's own
|
|
329
|
+
* serialization (missing/invalid fails loudly), assemble the typed Config.
|
|
330
|
+
* Secrets ride a separate channel (deserializeSecrets), not this one.
|
|
331
|
+
*/
|
|
332
|
+
const deserialize = (node, address) => {
|
|
333
|
+
const service = {};
|
|
334
|
+
const inputs = {};
|
|
335
|
+
for (const d of paramEntries(node)) {
|
|
336
|
+
const key = configKey(address, d);
|
|
337
|
+
const value = coerce(process.env[key], d, key);
|
|
338
|
+
if (d.owner === "service") service[d.name] = value;
|
|
339
|
+
else {
|
|
340
|
+
let bucket = inputs[d.owner.input];
|
|
341
|
+
if (bucket === void 0) {
|
|
342
|
+
bucket = {};
|
|
343
|
+
inputs[d.owner.input] = bucket;
|
|
344
|
+
}
|
|
345
|
+
bucket[d.name] = value;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
service,
|
|
350
|
+
inputs
|
|
351
|
+
};
|
|
352
|
+
};
|
|
353
|
+
/**
|
|
354
|
+
* run()'s setup step: write the resolved config to the environment under
|
|
355
|
+
* address-free keys (configKey("", d) + each serialize suffix), which load()
|
|
356
|
+
* reads back with no address. Uses env, not a module variable, because a
|
|
357
|
+
* framework may fork worker processes that inherit env but not memory.
|
|
358
|
+
* Writes only these keys; nothing else is touched.
|
|
359
|
+
*/
|
|
360
|
+
const stash = (node, config) => {
|
|
361
|
+
for (const d of paramEntries(node)) {
|
|
362
|
+
const value = d.owner === "service" ? config.service[d.name] : config.inputs[d.owner.input]?.[d.name];
|
|
363
|
+
if (value === void 0) continue;
|
|
364
|
+
process.env[configKey("", d)] = encode(d.owner, value);
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
/** The pointer-row key for a secret slot: COMPOSER_<addr>_<slot> (secrets are service-level). */
|
|
368
|
+
const secretKey = (address, slot) => configKey(address, {
|
|
369
|
+
owner: "service",
|
|
370
|
+
name: slot
|
|
371
|
+
});
|
|
372
|
+
/**
|
|
373
|
+
* Boot: resolve every secret slot to its value by double-lookup — read the
|
|
374
|
+
* pointer key (the platform NAME), then read that platform var. A missing
|
|
375
|
+
* pointer or a missing/empty platform value is a loud failure naming both keys.
|
|
376
|
+
* Returns a plain Record for core's `hydrateSecrets` to box.
|
|
377
|
+
*/
|
|
378
|
+
const deserializeSecrets = (node, address) => {
|
|
379
|
+
const values = {};
|
|
380
|
+
for (const slot of Object.keys(node.secretSlots)) {
|
|
381
|
+
const key = secretKey(address, slot);
|
|
382
|
+
const name = process.env[key];
|
|
383
|
+
if (name === void 0 || name === "") throw new Error(`missing secret pointer for slot "${slot}" (env ${key}) — the deploy did not write it.`);
|
|
384
|
+
const value = process.env[name];
|
|
385
|
+
if (value === void 0 || value === "") throw new Error(`secret "${slot}" is not provisioned (env ${key} → ${name}): the platform var "${name}" is unset or empty.`);
|
|
386
|
+
values[slot] = value;
|
|
387
|
+
}
|
|
388
|
+
return values;
|
|
389
|
+
};
|
|
390
|
+
/**
|
|
391
|
+
* run()'s setup step for secrets: re-emit each slot's pointer NAME under its
|
|
392
|
+
* address-free key, so the address-free `deserializeSecrets` double-looks-up
|
|
393
|
+
* identically. Never the value — the value stays only in the platform var.
|
|
394
|
+
*/
|
|
395
|
+
const stashSecrets = (node, address) => {
|
|
396
|
+
for (const slot of Object.keys(node.secretSlots)) {
|
|
397
|
+
const name = process.env[secretKey(address, slot)];
|
|
398
|
+
if (name === void 0) continue;
|
|
399
|
+
process.env[secretKey("", slot)] = name;
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
/**
|
|
403
|
+
* Boot: for each reserved provider param, read its address-scoped row through
|
|
404
|
+
* the same `coerce` a declared param uses (JSON-decode, schema-validate), and
|
|
405
|
+
* re-emit it address-free — `stash`'s counterpart for this separate
|
|
406
|
+
* declaration space. A param is declared optional here unconditionally: an
|
|
407
|
+
* absent row means "never provisioned" (local dev, tests, a provider with no
|
|
408
|
+
* registered value for this deploy), never a boot failure, so nothing is
|
|
409
|
+
* stashed and the runtime reader that owns this slot falls back to its own
|
|
410
|
+
* pass-through behavior.
|
|
411
|
+
*/
|
|
412
|
+
function stashProviderParams(entries, address) {
|
|
413
|
+
for (const entry of entries) {
|
|
414
|
+
const d = {
|
|
415
|
+
owner: "service",
|
|
416
|
+
name: entry.name,
|
|
417
|
+
param: {
|
|
418
|
+
schema: entry.schema,
|
|
419
|
+
optional: true
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
const key = configKey(address, d);
|
|
423
|
+
const value = coerce(process.env[key], d, key);
|
|
424
|
+
if (value === void 0) continue;
|
|
425
|
+
process.env[configKey("", d)] = encode("service", value);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/** The framework-resolved origin row: COMPOSER_<addr>_ORIGIN. Written per
|
|
429
|
+
* compute service at serialize — the service's own provisioned endpoint URL,
|
|
430
|
+
* riding the reserved-provider-param machinery (`origin-key.ts`'s
|
|
431
|
+
* `ORIGIN_PARAM`); never a declared param, never in config(). A harness with
|
|
432
|
+
* no deploy behind it supplies it by setting `COMPOSER_ORIGIN` to the
|
|
433
|
+
* JSON-encoded origin URL — exactly how the existing entrypoint tests supply
|
|
434
|
+
* their other `COMPOSER_*` rows. */
|
|
435
|
+
const ORIGIN_KEY_NAME = "ORIGIN";
|
|
436
|
+
/**
|
|
437
|
+
* Reads this service's origin back out of the address-free stash
|
|
438
|
+
* `stashProviderParams` wrote for the ORIGIN entry. `COMPOSER_ORIGIN` unset is
|
|
439
|
+
* a loud failure — a deployed environment always writes it, so an unset row
|
|
440
|
+
* means either a local harness that hasn't supplied it or a boot() called
|
|
441
|
+
* before run().
|
|
442
|
+
*/
|
|
443
|
+
function readOrigin() {
|
|
444
|
+
const d = {
|
|
445
|
+
owner: "service",
|
|
446
|
+
name: ORIGIN_KEY_NAME,
|
|
447
|
+
param: {
|
|
448
|
+
schema: type("string"),
|
|
449
|
+
optional: true
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
const key = configKey("", d);
|
|
453
|
+
const value = coerce(process.env[key], d, key);
|
|
454
|
+
if (value === void 0) throw new Error("this service's origin is not available (env COMPOSER_ORIGIN is unset) — a deployed environment writes it automatically; a local harness must supply it like any other config value (set COMPOSER_ORIGIN to the JSON-encoded origin URL).");
|
|
455
|
+
return blindCast(value);
|
|
456
|
+
}
|
|
457
|
+
/** Synchronous Standard Schema validation — see the matching note in core's `config.ts`. */
|
|
458
|
+
function standardValidateSync(schema, value) {
|
|
459
|
+
const result = schema["~standard"].validate(value);
|
|
460
|
+
if (result instanceof Promise) throw new Error("config param schema validation must be synchronous — async Standard Schema validators are not supported for config params");
|
|
461
|
+
if (result.issues !== void 0) throw new Error(`config param validation failed: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
462
|
+
return result.value;
|
|
463
|
+
}
|
|
464
|
+
/** Bounded jittered backoff for retrying a dropped call. `maxRetries` is retries after the first attempt. */
|
|
465
|
+
const RETRY = {
|
|
466
|
+
initialDelayMs: 250,
|
|
467
|
+
multiplier: 2,
|
|
468
|
+
maxDelayMs: 5e3,
|
|
469
|
+
maxRetries: 5
|
|
470
|
+
};
|
|
471
|
+
const IDEMPOTENCY_KEY_HEADER$1 = "Idempotency-Key";
|
|
472
|
+
function sleep(ms) {
|
|
473
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
474
|
+
}
|
|
475
|
+
/** Whether a non-OK response is safe to retry: 429 or any 5xx, never another 4xx. */
|
|
476
|
+
function isRetryableStatus(status) {
|
|
477
|
+
return status === 429 || status >= 500;
|
|
478
|
+
}
|
|
479
|
+
/** The server's `{ error }` body, if the response has one — undefined otherwise. */
|
|
480
|
+
async function errorDetail(res) {
|
|
481
|
+
try {
|
|
482
|
+
const body = await res.json();
|
|
483
|
+
return typeof body === "object" && body !== null && "error" in body ? String(body.error) : void 0;
|
|
484
|
+
} catch {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/** `<base>/rpc/<method>`, preserving a base URL's own path (e.g. a mount point). */
|
|
489
|
+
function methodUrl(base, method) {
|
|
490
|
+
const normalizedBase = base.endsWith("/") ? base : `${base}/`;
|
|
491
|
+
return new URL(`rpc/${method}`, normalizedBase).toString();
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Sends one call over `send`, retrying a thrown error, 429, or 5xx with
|
|
495
|
+
* full-jitter backoff. `buildRequest` runs per attempt but carries the same
|
|
496
|
+
* idempotency key each time — only the transport call repeats, not the key.
|
|
497
|
+
*/
|
|
498
|
+
async function callWithRetry(send, buildRequest, method) {
|
|
499
|
+
let delay = RETRY.initialDelayMs;
|
|
500
|
+
let retries = 0;
|
|
501
|
+
for (;;) {
|
|
502
|
+
let res;
|
|
503
|
+
try {
|
|
504
|
+
res = await send(buildRequest());
|
|
505
|
+
} catch (err) {
|
|
506
|
+
if (retries >= RETRY.maxRetries) throw err;
|
|
507
|
+
retries += 1;
|
|
508
|
+
await sleep(Math.random() * delay);
|
|
509
|
+
delay = Math.min(delay * RETRY.multiplier, RETRY.maxDelayMs);
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (res.ok) return res.json();
|
|
513
|
+
if (!isRetryableStatus(res.status) || retries >= RETRY.maxRetries) {
|
|
514
|
+
const detail = await errorDetail(res);
|
|
515
|
+
throw new Error(`RPC call "${method}" failed: ${res.status} ${res.statusText}` + (detail !== void 0 ? ` — ${detail}` : ""));
|
|
516
|
+
}
|
|
517
|
+
retries += 1;
|
|
518
|
+
await sleep(Math.random() * delay);
|
|
519
|
+
delay = Math.min(delay * RETRY.multiplier, RETRY.maxDelayMs);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
function makeClient(contract, url, opts) {
|
|
523
|
+
const send = opts?.fetch ?? fetch;
|
|
524
|
+
const baseHeaders = { "content-type": "application/json" };
|
|
525
|
+
if (opts?.serviceKey !== void 0) baseHeaders["Authorization"] = `Bearer ${opts.serviceKey}`;
|
|
526
|
+
const client = {};
|
|
527
|
+
for (const method of Object.keys(contract.__cmp)) client[method] = async (input) => {
|
|
528
|
+
const idempotencyKey = crypto.randomUUID();
|
|
529
|
+
const body = JSON.stringify(input);
|
|
530
|
+
return callWithRetry(send, () => new Request(methodUrl(url, method), {
|
|
531
|
+
method: "POST",
|
|
532
|
+
headers: {
|
|
533
|
+
...baseHeaders,
|
|
534
|
+
[IDEMPOTENCY_KEY_HEADER$1]: idempotencyKey
|
|
535
|
+
},
|
|
536
|
+
body
|
|
537
|
+
}), method);
|
|
538
|
+
};
|
|
539
|
+
return blindCast(client);
|
|
540
|
+
}
|
|
541
|
+
function contract(fns) {
|
|
542
|
+
const value = {
|
|
543
|
+
kind: "rpc",
|
|
544
|
+
__cmp: fns,
|
|
545
|
+
satisfies: (required) => value === required
|
|
546
|
+
};
|
|
547
|
+
return Object.freeze(value);
|
|
548
|
+
}
|
|
549
|
+
/** ADR-0031's need brand for RPC's per-binding service key — the target registers a provisioner under this. */
|
|
550
|
+
const RPC_PEER_KEY = Symbol.for("prisma:rpc/per-binding-key");
|
|
551
|
+
/** The provisioning need `rpc()`'s `serviceKey` param declares (ADR-0030): a shared, unguessable value the target mints per consumer edge. */
|
|
552
|
+
const perBindingToken = () => provisionNeed(RPC_PEER_KEY);
|
|
553
|
+
function rpc(arg) {
|
|
554
|
+
if (!isRpcContract(arg)) return arg;
|
|
555
|
+
return dependency({
|
|
556
|
+
type: "rpc",
|
|
557
|
+
connection: {
|
|
558
|
+
params: {
|
|
559
|
+
url: string(),
|
|
560
|
+
serviceKey: string({
|
|
561
|
+
optional: true,
|
|
562
|
+
provision: perBindingToken()
|
|
563
|
+
})
|
|
564
|
+
},
|
|
565
|
+
hydrate: ({ url, serviceKey }) => makeClient(arg, url, { serviceKey })
|
|
566
|
+
},
|
|
567
|
+
required: arg
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
function isRpcContract(value) {
|
|
571
|
+
return typeof value === "object" && value !== null && "kind" in value && value.kind === "rpc" && "__cmp" in value && "satisfies" in value;
|
|
572
|
+
}
|
|
573
|
+
async function standardValidate(schema, value) {
|
|
574
|
+
const result = await schema["~standard"].validate(value);
|
|
575
|
+
if (result.issues !== void 0) throw new Error(`Schema validation failed: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
576
|
+
return result.value;
|
|
577
|
+
}
|
|
578
|
+
/** The reserved env var the target (slice 2) writes the accepted key set to. */
|
|
579
|
+
const RPC_ACCEPTED_KEYS_ENV = "COMPOSER_RPC_ACCEPTED_KEYS";
|
|
580
|
+
function outcome(body, status = 200) {
|
|
581
|
+
return {
|
|
582
|
+
status,
|
|
583
|
+
bodyText: JSON.stringify(body)
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function toResponse(o) {
|
|
587
|
+
return new Response(o.bodyText, {
|
|
588
|
+
status: o.status,
|
|
589
|
+
headers: { "content-type": "application/json" }
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/** The generic message every caller-facing 500 carries — the real error goes to `console.error` instead. */
|
|
593
|
+
const INTERNAL_ERROR_MESSAGE = "Internal server error";
|
|
594
|
+
/** Request body cap. Internal RPC payloads are small records, not uploads; 1 MiB bounds a slow request's memory. */
|
|
595
|
+
const MAX_BODY_BYTES = 1048576;
|
|
596
|
+
var RequestBodyTooLargeError = class extends Error {};
|
|
597
|
+
/** Reads the body as text, aborting past `maxBytes` of bytes actually read — `content-length` is caller-supplied, so untrusted. */
|
|
598
|
+
async function readBoundedBody(req, maxBytes) {
|
|
599
|
+
const reader = req.body?.getReader();
|
|
600
|
+
if (reader === void 0) return "";
|
|
601
|
+
const decoder = new TextDecoder();
|
|
602
|
+
let text = "";
|
|
603
|
+
let total = 0;
|
|
604
|
+
for (;;) {
|
|
605
|
+
const { done, value } = await reader.read();
|
|
606
|
+
if (done) break;
|
|
607
|
+
total += value.byteLength;
|
|
608
|
+
if (total > maxBytes) {
|
|
609
|
+
await reader.cancel();
|
|
610
|
+
throw new RequestBodyTooLargeError();
|
|
611
|
+
}
|
|
612
|
+
text += decoder.decode(value, { stream: true });
|
|
613
|
+
}
|
|
614
|
+
text += decoder.decode();
|
|
615
|
+
return text;
|
|
616
|
+
}
|
|
617
|
+
/** How long a completed 2xx/4xx answer stays replayable for a repeated key. */
|
|
618
|
+
const REPLAY_TTL_MS = 6e4;
|
|
619
|
+
/**
|
|
620
|
+
* Per-method, per-key deduplication. A duplicate arriving mid-execution
|
|
621
|
+
* single-flights onto the same promise; a completed 2xx/4xx replays for
|
|
622
|
+
* REPLAY_TTL_MS; a 5xx is never kept, since that is what a retry re-executes.
|
|
623
|
+
* Keyed by method first, so a replay can never answer a different method.
|
|
624
|
+
*/
|
|
625
|
+
var IdempotencyStore = class {
|
|
626
|
+
byMethod = /* @__PURE__ */ new Map();
|
|
627
|
+
lru = /* @__PURE__ */ new Set();
|
|
628
|
+
async dispatch(method, key, run) {
|
|
629
|
+
const bucket = this.bucketFor(method);
|
|
630
|
+
const existing = bucket.get(key);
|
|
631
|
+
if (existing?.kind === "pending") return existing.promise;
|
|
632
|
+
if (existing?.kind === "completed") {
|
|
633
|
+
if (Date.now() - existing.completedAt < REPLAY_TTL_MS) {
|
|
634
|
+
this.lru.delete(existing);
|
|
635
|
+
this.lru.add(existing);
|
|
636
|
+
return existing.outcome;
|
|
637
|
+
}
|
|
638
|
+
bucket.delete(key);
|
|
639
|
+
this.lru.delete(existing);
|
|
640
|
+
}
|
|
641
|
+
const promise = run();
|
|
642
|
+
bucket.set(key, {
|
|
643
|
+
kind: "pending",
|
|
644
|
+
promise
|
|
645
|
+
});
|
|
646
|
+
let result;
|
|
647
|
+
try {
|
|
648
|
+
result = await promise;
|
|
649
|
+
} catch (err) {
|
|
650
|
+
bucket.delete(key);
|
|
651
|
+
throw err;
|
|
652
|
+
}
|
|
653
|
+
if (result.status >= 500) bucket.delete(key);
|
|
654
|
+
else {
|
|
655
|
+
const entry = {
|
|
656
|
+
kind: "completed",
|
|
657
|
+
outcome: result,
|
|
658
|
+
completedAt: Date.now(),
|
|
659
|
+
method,
|
|
660
|
+
key
|
|
661
|
+
};
|
|
662
|
+
bucket.set(key, entry);
|
|
663
|
+
this.lru.add(entry);
|
|
664
|
+
this.evictOverflow();
|
|
665
|
+
}
|
|
666
|
+
return result;
|
|
667
|
+
}
|
|
668
|
+
bucketFor(method) {
|
|
669
|
+
let bucket = this.byMethod.get(method);
|
|
670
|
+
if (bucket === void 0) {
|
|
671
|
+
bucket = /* @__PURE__ */ new Map();
|
|
672
|
+
this.byMethod.set(method, bucket);
|
|
673
|
+
}
|
|
674
|
+
return bucket;
|
|
675
|
+
}
|
|
676
|
+
evictOverflow() {
|
|
677
|
+
if (this.lru.size <= 1e3) return;
|
|
678
|
+
const oldest = this.lru.values().next().value;
|
|
679
|
+
if (oldest !== void 0) {
|
|
680
|
+
this.lru.delete(oldest);
|
|
681
|
+
this.byMethod.get(oldest.method)?.delete(oldest.key);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
/** The provisioned accepted key set, or undefined when the deploy never provisioned one (local/test — enforcement off). */
|
|
686
|
+
function acceptedKeys() {
|
|
687
|
+
const raw = process.env[RPC_ACCEPTED_KEYS_ENV];
|
|
688
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
689
|
+
let parsed;
|
|
690
|
+
try {
|
|
691
|
+
parsed = JSON.parse(raw);
|
|
692
|
+
} catch {
|
|
693
|
+
return [];
|
|
694
|
+
}
|
|
695
|
+
return Array.isArray(parsed) && parsed.every((key) => typeof key === "string") ? parsed : [];
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Length-independent constant-time string equality — no early exit on the
|
|
699
|
+
* first mismatched character or on a length difference, so a caller cannot
|
|
700
|
+
* time its way toward a valid key. No `node:crypto`, to keep this module
|
|
701
|
+
* runtime-agnostic.
|
|
702
|
+
*/
|
|
703
|
+
function constantTimeEquals(a, b) {
|
|
704
|
+
const length = Math.max(a.length, b.length);
|
|
705
|
+
let diff = a.length ^ b.length;
|
|
706
|
+
for (let i = 0; i < length; i++) diff |= (i < a.length ? a.charCodeAt(i) : 0) ^ (i < b.length ? b.charCodeAt(i) : 0);
|
|
707
|
+
return diff === 0;
|
|
708
|
+
}
|
|
709
|
+
/** Whether `presented` is a member of `accepted` — always compares against every key. */
|
|
710
|
+
function isAcceptedKey(presented, accepted) {
|
|
711
|
+
let matched = false;
|
|
712
|
+
for (const key of accepted) matched = constantTimeEquals(presented, key) || matched;
|
|
713
|
+
return matched;
|
|
714
|
+
}
|
|
715
|
+
const BEARER_PREFIX = "Bearer ";
|
|
716
|
+
/** The bearer token on `Authorization`, or `''` if the header is missing or malformed. */
|
|
717
|
+
function bearerToken(req) {
|
|
718
|
+
const header = req.headers.get("authorization");
|
|
719
|
+
return header?.startsWith(BEARER_PREFIX) ? header.slice(7) : "";
|
|
720
|
+
}
|
|
721
|
+
const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
|
|
722
|
+
/**
|
|
723
|
+
* Flattens every exposed port's methods into one method → {schemas, handler}
|
|
724
|
+
* table. RPC dispatch is flat (`/rpc/<method>`), so a method name exposed by
|
|
725
|
+
* more than one port is a construction-time error, as is a missing handler.
|
|
726
|
+
*/
|
|
727
|
+
function methodTable(expose, handlers) {
|
|
728
|
+
const table = /* @__PURE__ */ new Map();
|
|
729
|
+
for (const [port, contract] of Object.entries(expose)) {
|
|
730
|
+
const portHandlers = handlers[port] ?? {};
|
|
731
|
+
for (const [method, fn] of Object.entries(contract.__cmp)) {
|
|
732
|
+
if (table.has(method)) throw new Error(`serve(): method "${method}" is exposed by more than one port — RPC dispatch is flat (POST /rpc/<method>), so method names must be unique across a service's exposed ports.`);
|
|
733
|
+
const handler = portHandlers[method];
|
|
734
|
+
if (handler === void 0) throw new Error(`serve(): no handler supplied for exposed method "${port}.${method}".`);
|
|
735
|
+
const { input, output } = blindCast(fn);
|
|
736
|
+
table.set(method, {
|
|
737
|
+
input,
|
|
738
|
+
output,
|
|
739
|
+
handler
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return table;
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Routes `POST /rpc/<method>`: checks the service key, requires an
|
|
747
|
+
* Idempotency-Key, single-flights/replays through `IdempotencyStore`, and —
|
|
748
|
+
* per call — parses JSON within the body cap, validates input, calls the
|
|
749
|
+
* handler with `service.load()`'s deps plus `{ idempotencyKey }`, validates
|
|
750
|
+
* the output, and responds JSON. A handler or output-validation failure
|
|
751
|
+
* masks its message behind a generic 500 and logs the real error; an
|
|
752
|
+
* unknown method or invalid input is a 4xx. `load()` is called exactly
|
|
753
|
+
* once, here, before the handler ever runs.
|
|
754
|
+
*/
|
|
755
|
+
function serve(service, handlers) {
|
|
756
|
+
const table = methodTable(service.expose ?? {}, blindCast(handlers));
|
|
757
|
+
const deps = service.load();
|
|
758
|
+
const idempotency = new IdempotencyStore();
|
|
759
|
+
return async (req) => {
|
|
760
|
+
const accepted = acceptedKeys();
|
|
761
|
+
if (accepted !== void 0 && !isAcceptedKey(bearerToken(req), accepted)) return toResponse(outcome({ error: "Unauthorized: missing or invalid service key" }, 401));
|
|
762
|
+
const { pathname } = new URL(req.url);
|
|
763
|
+
const methodName = /^\/rpc\/([^/]+)$/.exec(pathname)?.[1];
|
|
764
|
+
if (methodName === void 0) return toResponse(outcome({ error: `Not found: ${pathname}` }, 404));
|
|
765
|
+
const method = table.get(methodName);
|
|
766
|
+
if (method === void 0) return toResponse(outcome({ error: `Unknown RPC method "${methodName}"` }, 404));
|
|
767
|
+
if (req.method !== "POST") return toResponse(outcome({ error: `Method "${methodName}" requires POST` }, 405));
|
|
768
|
+
const idempotencyKey = req.headers.get(IDEMPOTENCY_KEY_HEADER.toLowerCase()) || void 0;
|
|
769
|
+
const ctx = { idempotencyKey };
|
|
770
|
+
const run = async () => {
|
|
771
|
+
let bodyText;
|
|
772
|
+
try {
|
|
773
|
+
bodyText = await readBoundedBody(req, MAX_BODY_BYTES);
|
|
774
|
+
} catch (err) {
|
|
775
|
+
if (err instanceof RequestBodyTooLargeError) return outcome({ error: `Request body exceeds the ${MAX_BODY_BYTES}-byte limit` }, 413);
|
|
776
|
+
console.error(`serve(): reading the request body for "${methodName}" failed:`, err);
|
|
777
|
+
return outcome({ error: INTERNAL_ERROR_MESSAGE }, 500);
|
|
778
|
+
}
|
|
779
|
+
let body;
|
|
780
|
+
try {
|
|
781
|
+
body = JSON.parse(bodyText);
|
|
782
|
+
} catch {
|
|
783
|
+
return outcome({ error: "Request body must be JSON" }, 400);
|
|
784
|
+
}
|
|
785
|
+
let input;
|
|
786
|
+
try {
|
|
787
|
+
input = await standardValidate(method.input, body);
|
|
788
|
+
} catch (err) {
|
|
789
|
+
return outcome({ error: err instanceof Error ? err.message : String(err) }, 400);
|
|
790
|
+
}
|
|
791
|
+
try {
|
|
792
|
+
const result = await method.handler(input, deps, ctx);
|
|
793
|
+
let output;
|
|
794
|
+
try {
|
|
795
|
+
output = await standardValidate(method.output, result);
|
|
796
|
+
} catch (err) {
|
|
797
|
+
console.error(`serve(): handler for "${methodName}" returned output that failed schema validation — this is a provider bug:`, err);
|
|
798
|
+
return outcome({ error: INTERNAL_ERROR_MESSAGE }, 500);
|
|
799
|
+
}
|
|
800
|
+
return outcome(output);
|
|
801
|
+
} catch (err) {
|
|
802
|
+
console.error(`serve(): handler for "${methodName}" threw:`, err);
|
|
803
|
+
return outcome({ error: INTERNAL_ERROR_MESSAGE }, 500);
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
return toResponse(idempotencyKey === void 0 ? await run() : await idempotency.dispatch(methodName, idempotencyKey, run));
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* The service's own origin as a reserved provider param (ADR-0031): the ONE
|
|
811
|
+
* brand and the ONE entry — shared by control.ts (which registers the
|
|
812
|
+
* deploy-side value function that resolves the provisioned service's
|
|
813
|
+
* `endpointDomain` — see its `selfOriginValue`) and compute.ts (which
|
|
814
|
+
* validates and stashes the row at boot through the generic
|
|
815
|
+
* `stashProviderParams` loop), so writer and reader cannot drift.
|
|
816
|
+
*
|
|
817
|
+
* Unlike the key-minting brands (`service-keys.ts`, `streams-keys.ts`) this
|
|
818
|
+
* brand has no provisioner and no consumer edges: the value derives from the
|
|
819
|
+
* service's OWN provisioned attributes, so control.ts registers it as a
|
|
820
|
+
* service-derived provider param (`descriptors/shared.ts`'s
|
|
821
|
+
* `ServiceProviderParam`) and the descriptor writes it for EVERY compute
|
|
822
|
+
* service, exposing or not.
|
|
823
|
+
*
|
|
824
|
+
* This module is reachable from the RUNTIME/authoring side — it must never
|
|
825
|
+
* import `@internal/lowering` or `effect`, or those tokens leak into a user
|
|
826
|
+
* service's bundle (the deploy-side value function lives in control.ts, the
|
|
827
|
+
* control-plane-only entry).
|
|
828
|
+
*/
|
|
829
|
+
/** ADR-0031's brand for the service's own origin — control.ts registers the deploy-side value function under this. */
|
|
830
|
+
const SELF_ORIGIN = Symbol.for("prisma:self-origin");
|
|
831
|
+
/**
|
|
832
|
+
* The reserved provider param for the origin row: the var name is `ORIGIN`,
|
|
833
|
+
* derived through `configKey` at both ends (`configKey(address, …)` at
|
|
834
|
+
* deploy, `configKey('', …)` — `COMPOSER_ORIGIN` — at boot, where
|
|
835
|
+
* `readOrigin` reads it back). `brand` is `SELF_ORIGIN` — control.ts looks
|
|
836
|
+
* its deploy-side value function up by this field.
|
|
837
|
+
*/
|
|
838
|
+
const ORIGIN_PARAM = {
|
|
839
|
+
name: ORIGIN_KEY_NAME,
|
|
840
|
+
schema: type("string"),
|
|
841
|
+
brand: SELF_ORIGIN
|
|
842
|
+
};
|
|
843
|
+
/**
|
|
844
|
+
* RPC's reserved provider param (ADR-0030/ADR-0031): the declaration —
|
|
845
|
+
* name + schema + brand — for the accepted-keys set a provider stores, shared
|
|
846
|
+
* by `control.ts` (which registers the deploy-side `value(refs)` that mints
|
|
847
|
+
* and aggregates it — see its `rpcAcceptedKeysValue`) and `compute.ts` (which
|
|
848
|
+
* validates and stashes it at boot), so writer and reader cannot drift.
|
|
849
|
+
* Finding the edges themselves is `provisioned-edges.ts`'s generic,
|
|
850
|
+
* brand-blind scan — RPC is not special-cased anywhere in this target.
|
|
851
|
+
*
|
|
852
|
+
* This module is reachable from the RUNTIME/authoring side — it must never
|
|
853
|
+
* import `@internal/lowering` or `effect`, or those tokens leak into a user
|
|
854
|
+
* service's bundle (the deploy-side `value(refs)` lives in control.ts, the
|
|
855
|
+
* control-plane-only entry).
|
|
856
|
+
*/
|
|
857
|
+
/**
|
|
858
|
+
* The reserved provider param for RPC's accepted-keys set: the var name is
|
|
859
|
+
* `RPC_ACCEPTED_KEYS`, derived through `configKey` at both ends
|
|
860
|
+
* (`configKey(address, …)` at deploy, `configKey('', …)` at boot — the
|
|
861
|
+
* address-free form is `@internal/service-rpc`'s `RPC_ACCEPTED_KEYS_ENV`). `brand` is
|
|
862
|
+
* `RPC_PEER_KEY`, the same brand `perBindingToken()`'s need carries — control.ts
|
|
863
|
+
* looks its `value(refs)` up by this field.
|
|
864
|
+
*/
|
|
865
|
+
const RPC_ACCEPTED_KEYS_PARAM = {
|
|
866
|
+
name: "RPC_ACCEPTED_KEYS",
|
|
867
|
+
schema: type("string[]"),
|
|
868
|
+
brand: RPC_PEER_KEY
|
|
869
|
+
};
|
|
870
|
+
/** ADR-0031's need brand for the streams module's bearer key — control.ts registers the provisioner under this. */
|
|
871
|
+
const STREAMS_API_KEY = Symbol.for("prisma:streams/api-key");
|
|
872
|
+
/**
|
|
873
|
+
* The reserved provider param for the streams bearer key: the var name is
|
|
874
|
+
* `STREAMS_API_KEY`. `brand` is `STREAMS_API_KEY` itself (the same symbol
|
|
875
|
+
* `streamsApiKeyNeed()`'s need carries) — control.ts looks its `value(refs)`
|
|
876
|
+
* up by this field.
|
|
877
|
+
*/
|
|
878
|
+
const STREAMS_API_KEY_PARAM = {
|
|
879
|
+
name: "STREAMS_API_KEY",
|
|
880
|
+
schema: type("string"),
|
|
881
|
+
brand: STREAMS_API_KEY
|
|
882
|
+
};
|
|
883
|
+
configKey("", {
|
|
884
|
+
owner: "service",
|
|
885
|
+
name: STREAMS_API_KEY_PARAM.name
|
|
886
|
+
});
|
|
887
|
+
/**
|
|
888
|
+
* The list of provider-side reserved params the boot path validates and
|
|
889
|
+
* stashes (ADR-0031): every brand's `{name, schema, brand}` declaration,
|
|
890
|
+
* collected from that brand's own module (`service-keys.ts`,
|
|
891
|
+
* `streams-keys.ts`, `origin-key.ts`) so `compute.ts` names no brand itself.
|
|
892
|
+
*
|
|
893
|
+
* This list exists separately from `control.ts`'s deploy-side registry
|
|
894
|
+
* (`PROVIDER_PARAMS`) because `control.ts` is deploy-only code — it imports
|
|
895
|
+
* `@internal/lowering` and `effect` to mint values — and a booted service
|
|
896
|
+
* must never import it. This module is reachable from a user service's
|
|
897
|
+
* bundle through `compute.ts`, so it must never import `@internal/lowering`,
|
|
898
|
+
* `effect`, `alchemy`, or `control.ts`.
|
|
899
|
+
*
|
|
900
|
+
* This is the single source of which reserved provider params exist:
|
|
901
|
+
* control.ts builds `PROVIDER_PARAMS` by mapping over this list and looking
|
|
902
|
+
* up each entry's deploy-side value function (edge-derived `value(refs)` or
|
|
903
|
+
* service-derived `valueForService(provisioned, address)`) by its `brand`,
|
|
904
|
+
* throwing at module load if one is missing. Adding a brand means adding its
|
|
905
|
+
* entry here, plus its deploy-side value function in control.ts — a brand
|
|
906
|
+
* registered for deploy but absent here is no longer expressible, because
|
|
907
|
+
* deploy no longer names its own param set independently.
|
|
908
|
+
*/
|
|
909
|
+
const RESERVED_PROVIDER_PARAMS = [
|
|
910
|
+
RPC_ACCEPTED_KEYS_PARAM,
|
|
911
|
+
STREAMS_API_KEY_PARAM,
|
|
912
|
+
ORIGIN_PARAM
|
|
913
|
+
];
|
|
914
|
+
Object.freeze({
|
|
915
|
+
kind: "s3",
|
|
916
|
+
__cmp: {
|
|
917
|
+
url: "",
|
|
918
|
+
bucket: "",
|
|
919
|
+
accessKeyId: "",
|
|
920
|
+
secretAccessKey: ""
|
|
921
|
+
},
|
|
922
|
+
satisfies: (required) => required.kind === "s3"
|
|
923
|
+
});
|
|
924
|
+
const reservedParams = { port: number({ default: 3e3 }) };
|
|
925
|
+
/**
|
|
926
|
+
* A Prisma Compute service — declarations only (deps + params + build + the
|
|
927
|
+
* ports it exposes), no descriptor. `params` merges with the reserved
|
|
928
|
+
* `ReservedParams` (`port`); a user param whose name collides with a reserved
|
|
929
|
+
* one fails at authoring, the same way a colliding dependency name does.
|
|
930
|
+
*
|
|
931
|
+
* · run(address, boot) — the process controller: deserialize the platform
|
|
932
|
+
* environment (keyed off `address`, the extension's ONE env read) into a
|
|
933
|
+
* typed Config, re-emit it under address-free process-local stash keys,
|
|
934
|
+
* then call boot() to start the app's entry.
|
|
935
|
+
* · load() / config() — called from inside the app's entry: read the stash;
|
|
936
|
+
* load() hydrates + memoizes the deps, config() returns the typed params.
|
|
937
|
+
* Separate accessors so a dep and a param never share a namespace (ADR-0021).
|
|
938
|
+
* · origin() — this service's platform-assigned public origin, read from the
|
|
939
|
+
* stash `run()` populates; memoized per process.
|
|
940
|
+
*
|
|
941
|
+
* The underlying node carries `extension: '@prisma/composer-prisma-cloud'` —
|
|
942
|
+
* the control-plane registry key `prisma-composer deploy` resolves through the
|
|
943
|
+
* app's `prisma-composer.config.ts` (ADR-0017). This module loads nothing at
|
|
944
|
+
* deploy time; nodes are pure data until run() or load() is called.
|
|
945
|
+
*/
|
|
946
|
+
var ComputeService = class {
|
|
947
|
+
#resolved;
|
|
948
|
+
#loadedDeps;
|
|
949
|
+
#loadedParams;
|
|
950
|
+
#loadedSecrets;
|
|
951
|
+
#origin;
|
|
952
|
+
constructor(node) {
|
|
953
|
+
Object.assign(this, node);
|
|
954
|
+
}
|
|
955
|
+
#processConfig() {
|
|
956
|
+
if (this.#resolved === void 0) this.#resolved = deserialize(this, "");
|
|
957
|
+
return this.#resolved;
|
|
958
|
+
}
|
|
959
|
+
async run(address, boot) {
|
|
960
|
+
const config = deserialize(this, address);
|
|
961
|
+
stash(this, config);
|
|
962
|
+
stashProviderParams(RESERVED_PROVIDER_PARAMS, address);
|
|
963
|
+
stashSecrets(this, address);
|
|
964
|
+
const port = config.service["port"];
|
|
965
|
+
if (typeof port === "number") process.env["PORT"] = String(port);
|
|
966
|
+
return boot();
|
|
967
|
+
}
|
|
968
|
+
load() {
|
|
969
|
+
if (this.#loadedDeps === void 0) this.#loadedDeps = blindCast(hydrateSync(this, this.#processConfig()));
|
|
970
|
+
return this.#loadedDeps;
|
|
971
|
+
}
|
|
972
|
+
config() {
|
|
973
|
+
if (this.#loadedParams === void 0) this.#loadedParams = blindCast(this.#processConfig().service);
|
|
974
|
+
return this.#loadedParams;
|
|
975
|
+
}
|
|
976
|
+
secrets() {
|
|
977
|
+
if (this.#loadedSecrets === void 0) this.#loadedSecrets = blindCast(hydrateSecrets(this, deserializeSecrets(this, "")));
|
|
978
|
+
return this.#loadedSecrets;
|
|
979
|
+
}
|
|
980
|
+
/** This service's platform-assigned public origin — read from the stash
|
|
981
|
+
* run() populates and memoized per process. Throws if called before run()
|
|
982
|
+
* has stashed it (readOrigin's pinned message). */
|
|
983
|
+
origin() {
|
|
984
|
+
this.#origin ??= readOrigin();
|
|
985
|
+
return this.#origin;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
const compute = (def) => {
|
|
989
|
+
const userParams = def.params ?? blindCast({});
|
|
990
|
+
for (const reserved of Object.keys(reservedParams)) {
|
|
991
|
+
if (reserved in def.deps) throw new Error(`compute(): dependency "${reserved}" collides with the reserved service param of the same name — rename the dependency.`);
|
|
992
|
+
if (reserved in userParams) throw new Error(`compute(): param "${reserved}" collides with the reserved service param of the same name — rename the param.`);
|
|
993
|
+
}
|
|
994
|
+
for (const name of Object.keys(userParams)) if (name.toUpperCase() === "ORIGIN") throw new Error(`compute(): param "${name}" collides with the framework-written origin row — rename the param.`);
|
|
995
|
+
for (const name of Object.keys(def.secrets ?? {})) if (name.toUpperCase() === "ORIGIN") throw new Error(`compute(): secret "${name}" collides with the framework-written origin row — rename the secret.`);
|
|
996
|
+
const params = blindCast({
|
|
997
|
+
...userParams,
|
|
998
|
+
...reservedParams
|
|
999
|
+
});
|
|
1000
|
+
const instance = new ComputeService(service({
|
|
1001
|
+
name: def.name,
|
|
1002
|
+
extension: "@prisma/composer-prisma-cloud",
|
|
1003
|
+
type: "compute",
|
|
1004
|
+
inputs: def.deps,
|
|
1005
|
+
params,
|
|
1006
|
+
...def.secrets !== void 0 ? { secrets: def.secrets } : {},
|
|
1007
|
+
build: def.build,
|
|
1008
|
+
...def.expose !== void 0 ? { expose: def.expose } : {}
|
|
1009
|
+
}));
|
|
1010
|
+
Object.freeze(instance);
|
|
1011
|
+
return instance;
|
|
1012
|
+
};
|
|
1013
|
+
Object.freeze({
|
|
1014
|
+
kind: "postgres",
|
|
1015
|
+
__cmp: { url: "" },
|
|
1016
|
+
satisfies: (required) => required.kind === "postgres"
|
|
1017
|
+
});
|
|
1018
|
+
Object.freeze({
|
|
1019
|
+
kind: "credentials",
|
|
1020
|
+
__cmp: {
|
|
1021
|
+
accessKeyId: "",
|
|
1022
|
+
secretAccessKey: ""
|
|
1023
|
+
},
|
|
1024
|
+
satisfies: (required) => required.kind === "credentials"
|
|
1025
|
+
});
|
|
1026
|
+
const emailStatus = type("'stored'|'queued'|'sent'|'failed'");
|
|
1027
|
+
const emailSendContract = contract({ send: rpc({
|
|
1028
|
+
input: type({
|
|
1029
|
+
templateId: "string",
|
|
1030
|
+
to: "1<=string[]<=50",
|
|
1031
|
+
"cc?": "string[]",
|
|
1032
|
+
"bcc?": "string[]",
|
|
1033
|
+
"replyTo?": "string",
|
|
1034
|
+
subject: "string",
|
|
1035
|
+
html: "string",
|
|
1036
|
+
"text?": "string",
|
|
1037
|
+
idempotencyKey: "1<=string<=256"
|
|
1038
|
+
}),
|
|
1039
|
+
output: type({
|
|
1040
|
+
id: "string",
|
|
1041
|
+
status: emailStatus,
|
|
1042
|
+
"error?": "string"
|
|
1043
|
+
})
|
|
1044
|
+
}) });
|
|
1045
|
+
const emailRecord = type({
|
|
1046
|
+
id: "string",
|
|
1047
|
+
templateId: "string",
|
|
1048
|
+
to: "string[]",
|
|
1049
|
+
cc: "string[]",
|
|
1050
|
+
bcc: "string[]",
|
|
1051
|
+
replyTo: "string | null",
|
|
1052
|
+
from: "string",
|
|
1053
|
+
subject: "string",
|
|
1054
|
+
html: "string",
|
|
1055
|
+
text: "string | null",
|
|
1056
|
+
status: emailStatus,
|
|
1057
|
+
providerMessageId: "string | null",
|
|
1058
|
+
error: "string | null",
|
|
1059
|
+
attempts: "number",
|
|
1060
|
+
createdAt: "string",
|
|
1061
|
+
updatedAt: "string"
|
|
1062
|
+
});
|
|
1063
|
+
const emailOutboxContract = contract({
|
|
1064
|
+
getEmail: rpc({
|
|
1065
|
+
input: type({ id: "string" }),
|
|
1066
|
+
output: type({ email: emailRecord.or("null") })
|
|
1067
|
+
}),
|
|
1068
|
+
listEmails: rpc({
|
|
1069
|
+
input: type({
|
|
1070
|
+
"to?": "string",
|
|
1071
|
+
"templateId?": "string",
|
|
1072
|
+
"status?": emailStatus,
|
|
1073
|
+
"cursor?": "string",
|
|
1074
|
+
"limit?": "1<=number.integer<=200"
|
|
1075
|
+
}),
|
|
1076
|
+
output: type({
|
|
1077
|
+
emails: emailRecord.array(),
|
|
1078
|
+
"nextCursor?": "string"
|
|
1079
|
+
})
|
|
1080
|
+
})
|
|
1081
|
+
});
|
|
1082
|
+
/** Mode `none` never calls `Delivery` (`handlers.ts`'s `send` returns before it) — this placeholder satisfies the required config slot in the entrypoint and the local test server without a real backing. */
|
|
1083
|
+
const noneDelivery = { deliver: () => {
|
|
1084
|
+
throw new Error("unreachable: deliveryMode \"none\" never calls Delivery.deliver");
|
|
1085
|
+
} };
|
|
1086
|
+
/** Not documented to consumers as parseable (spec) — treat the string as opaque outside this pair. */
|
|
1087
|
+
function encodeCursor(cursor) {
|
|
1088
|
+
return Buffer.from(`${cursor.createdAt}|${cursor.id}`, "utf-8").toString("base64");
|
|
1089
|
+
}
|
|
1090
|
+
function decodeCursor(value) {
|
|
1091
|
+
const decoded = Buffer.from(value, "base64").toString("utf-8");
|
|
1092
|
+
const separatorIndex = decoded.indexOf("|");
|
|
1093
|
+
if (separatorIndex === -1) throw new Error(`invalid outbox cursor: ${value}`);
|
|
1094
|
+
return {
|
|
1095
|
+
createdAt: decoded.slice(0, separatorIndex),
|
|
1096
|
+
id: decoded.slice(separatorIndex + 1)
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
const DEFAULT_LIST_LIMIT = 50;
|
|
1100
|
+
function toEmailRecord(row) {
|
|
1101
|
+
return {
|
|
1102
|
+
id: row.id,
|
|
1103
|
+
templateId: row.templateId,
|
|
1104
|
+
to: [...row.to],
|
|
1105
|
+
cc: [...row.cc],
|
|
1106
|
+
bcc: [...row.bcc],
|
|
1107
|
+
replyTo: row.replyTo,
|
|
1108
|
+
from: row.from,
|
|
1109
|
+
subject: row.subject,
|
|
1110
|
+
html: row.html,
|
|
1111
|
+
text: row.text,
|
|
1112
|
+
status: row.status,
|
|
1113
|
+
providerMessageId: row.providerMessageId,
|
|
1114
|
+
error: row.error,
|
|
1115
|
+
attempts: row.attempts,
|
|
1116
|
+
createdAt: row.createdAt,
|
|
1117
|
+
updatedAt: row.updatedAt
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
function toSendResult(row) {
|
|
1121
|
+
return row.error === null ? {
|
|
1122
|
+
id: row.id,
|
|
1123
|
+
status: row.status
|
|
1124
|
+
} : {
|
|
1125
|
+
id: row.id,
|
|
1126
|
+
status: row.status,
|
|
1127
|
+
error: row.error
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
function createHandlers(config) {
|
|
1131
|
+
const { store, delivery, deliveryMode, from } = config;
|
|
1132
|
+
async function send(input) {
|
|
1133
|
+
const status = deliveryMode === "none" ? "stored" : "queued";
|
|
1134
|
+
const outcome = await store.insert({
|
|
1135
|
+
id: crypto.randomUUID(),
|
|
1136
|
+
templateId: input.templateId,
|
|
1137
|
+
to: input.to,
|
|
1138
|
+
cc: input.cc ?? [],
|
|
1139
|
+
bcc: input.bcc ?? [],
|
|
1140
|
+
replyTo: input.replyTo ?? null,
|
|
1141
|
+
from,
|
|
1142
|
+
subject: input.subject,
|
|
1143
|
+
html: input.html,
|
|
1144
|
+
text: input.text ?? null,
|
|
1145
|
+
status,
|
|
1146
|
+
idempotencyKey: input.idempotencyKey
|
|
1147
|
+
});
|
|
1148
|
+
if (!outcome.inserted || deliveryMode === "none") return toSendResult(outcome.row);
|
|
1149
|
+
const result = await delivery.deliver(outcome.row).catch((caught) => ({
|
|
1150
|
+
ok: false,
|
|
1151
|
+
error: caught instanceof Error ? caught.message : String(caught),
|
|
1152
|
+
attempts: 1
|
|
1153
|
+
}));
|
|
1154
|
+
return toSendResult(await store.updateDelivery(outcome.row.id, result.ok ? {
|
|
1155
|
+
status: "sent",
|
|
1156
|
+
providerMessageId: result.providerMessageId,
|
|
1157
|
+
attempts: result.attempts
|
|
1158
|
+
} : {
|
|
1159
|
+
status: "failed",
|
|
1160
|
+
error: result.error,
|
|
1161
|
+
attempts: result.attempts
|
|
1162
|
+
}));
|
|
1163
|
+
}
|
|
1164
|
+
async function getEmail(input) {
|
|
1165
|
+
const row = await store.getById(input.id);
|
|
1166
|
+
return { email: row === null ? null : toEmailRecord(row) };
|
|
1167
|
+
}
|
|
1168
|
+
async function listEmails(input) {
|
|
1169
|
+
const limit = input.limit ?? DEFAULT_LIST_LIMIT;
|
|
1170
|
+
const after = input.cursor === void 0 ? void 0 : decodeCursor(input.cursor);
|
|
1171
|
+
const page = await store.list({
|
|
1172
|
+
...input.to !== void 0 ? { to: input.to } : {},
|
|
1173
|
+
...input.templateId !== void 0 ? { templateId: input.templateId } : {},
|
|
1174
|
+
...input.status !== void 0 ? { status: input.status } : {},
|
|
1175
|
+
...after !== void 0 ? { after } : {},
|
|
1176
|
+
limit
|
|
1177
|
+
});
|
|
1178
|
+
const last = page.rows.at(-1);
|
|
1179
|
+
return {
|
|
1180
|
+
emails: page.rows.map(toEmailRecord),
|
|
1181
|
+
...page.hasMore && last !== void 0 ? { nextCursor: encodeCursor({
|
|
1182
|
+
createdAt: last.createdAt,
|
|
1183
|
+
id: last.id
|
|
1184
|
+
}) } : {}
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
return {
|
|
1188
|
+
send,
|
|
1189
|
+
getEmail,
|
|
1190
|
+
listEmails
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
var MemoryOutboxStore = class {
|
|
1194
|
+
rowsById = /* @__PURE__ */ new Map();
|
|
1195
|
+
idByIdempotencyKey = /* @__PURE__ */ new Map();
|
|
1196
|
+
async insert(row) {
|
|
1197
|
+
const existingId = this.idByIdempotencyKey.get(row.idempotencyKey);
|
|
1198
|
+
if (existingId !== void 0) {
|
|
1199
|
+
const existing = this.rowsById.get(existingId);
|
|
1200
|
+
if (existing === void 0) throw new Error(`outbox insert: idempotency index pointed at a missing row ${existingId}`);
|
|
1201
|
+
return {
|
|
1202
|
+
row: existing,
|
|
1203
|
+
inserted: false
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1207
|
+
const inserted = {
|
|
1208
|
+
id: row.id,
|
|
1209
|
+
templateId: row.templateId,
|
|
1210
|
+
to: [...row.to],
|
|
1211
|
+
cc: [...row.cc],
|
|
1212
|
+
bcc: [...row.bcc],
|
|
1213
|
+
replyTo: row.replyTo,
|
|
1214
|
+
from: row.from,
|
|
1215
|
+
subject: row.subject,
|
|
1216
|
+
html: row.html,
|
|
1217
|
+
text: row.text,
|
|
1218
|
+
status: row.status,
|
|
1219
|
+
providerMessageId: null,
|
|
1220
|
+
error: null,
|
|
1221
|
+
idempotencyKey: row.idempotencyKey,
|
|
1222
|
+
attempts: 0,
|
|
1223
|
+
createdAt: now,
|
|
1224
|
+
updatedAt: now
|
|
1225
|
+
};
|
|
1226
|
+
this.rowsById.set(row.id, inserted);
|
|
1227
|
+
this.idByIdempotencyKey.set(row.idempotencyKey, row.id);
|
|
1228
|
+
return {
|
|
1229
|
+
row: inserted,
|
|
1230
|
+
inserted: true
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
async updateDelivery(id, update) {
|
|
1234
|
+
const existing = this.rowsById.get(id);
|
|
1235
|
+
if (existing === void 0) throw new Error(`outbox updateDelivery: no row found for id ${id}`);
|
|
1236
|
+
const updated = {
|
|
1237
|
+
...existing,
|
|
1238
|
+
status: update.status,
|
|
1239
|
+
providerMessageId: update.status === "sent" ? update.providerMessageId : null,
|
|
1240
|
+
error: update.status === "failed" ? update.error : null,
|
|
1241
|
+
attempts: existing.attempts + update.attempts,
|
|
1242
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1243
|
+
};
|
|
1244
|
+
this.rowsById.set(id, updated);
|
|
1245
|
+
return updated;
|
|
1246
|
+
}
|
|
1247
|
+
async getById(id) {
|
|
1248
|
+
return this.rowsById.get(id) ?? null;
|
|
1249
|
+
}
|
|
1250
|
+
async list(filters) {
|
|
1251
|
+
const matches = [...this.rowsById.values()].filter((row) => filters.to === void 0 || row.to.includes(filters.to)).filter((row) => filters.templateId === void 0 || row.templateId === filters.templateId).filter((row) => filters.status === void 0 || row.status === filters.status).sort((a, b) => {
|
|
1252
|
+
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
|
|
1253
|
+
return a.id < b.id ? 1 : -1;
|
|
1254
|
+
}).filter((row) => {
|
|
1255
|
+
const after = filters.after;
|
|
1256
|
+
if (after === void 0) return true;
|
|
1257
|
+
if (row.createdAt !== after.createdAt) return row.createdAt < after.createdAt;
|
|
1258
|
+
return row.id < after.id;
|
|
1259
|
+
});
|
|
1260
|
+
const hasMore = matches.length > filters.limit;
|
|
1261
|
+
return {
|
|
1262
|
+
rows: hasMore ? matches.slice(0, filters.limit) : matches,
|
|
1263
|
+
hasMore
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
function createMemoryOutboxStore() {
|
|
1268
|
+
return new MemoryOutboxStore();
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* The local stand-in: boots `handlers.ts` over the in-memory store with
|
|
1272
|
+
* `deliveryMode: 'none'`, loopback only, no auth (`serve()`'s accepted-keys
|
|
1273
|
+
* pass-through when the env set is absent — the same as any un-deployed
|
|
1274
|
+
* service). `serve()` needs a service node with the right `expose`, so this
|
|
1275
|
+
* wraps a bare `compute()` whose `build` is inert (never assembled or
|
|
1276
|
+
* deployed) — mirrors the auth module's test fake
|
|
1277
|
+
* (`examples/storefront-auth/modules/auth/testing/fake.ts`), promoted here
|
|
1278
|
+
* to the module's own official local-dev surface.
|
|
1279
|
+
*/
|
|
1280
|
+
async function startLocalEmailServer(opts) {
|
|
1281
|
+
const localService = compute({
|
|
1282
|
+
name: "emailLocal",
|
|
1283
|
+
deps: {},
|
|
1284
|
+
build: nodeBuild({
|
|
1285
|
+
module: import.meta.url,
|
|
1286
|
+
entry: "testing.ts"
|
|
1287
|
+
}),
|
|
1288
|
+
expose: {
|
|
1289
|
+
send: emailSendContract,
|
|
1290
|
+
outbox: emailOutboxContract
|
|
1291
|
+
}
|
|
1292
|
+
});
|
|
1293
|
+
const handlers = createHandlers({
|
|
1294
|
+
store: createMemoryOutboxStore(),
|
|
1295
|
+
delivery: noneDelivery,
|
|
1296
|
+
deliveryMode: "none",
|
|
1297
|
+
from: "local@example.com"
|
|
1298
|
+
});
|
|
1299
|
+
const fetchHandler = serve(localService, {
|
|
1300
|
+
send: { send: handlers.send },
|
|
1301
|
+
outbox: {
|
|
1302
|
+
getEmail: handlers.getEmail,
|
|
1303
|
+
listEmails: handlers.listEmails
|
|
1304
|
+
}
|
|
1305
|
+
});
|
|
1306
|
+
const server = Bun.serve({
|
|
1307
|
+
port: opts?.port ?? 0,
|
|
1308
|
+
hostname: "127.0.0.1",
|
|
1309
|
+
fetch: fetchHandler
|
|
1310
|
+
});
|
|
1311
|
+
return {
|
|
1312
|
+
url: `http://127.0.0.1:${server.port}`,
|
|
1313
|
+
stop: async () => {
|
|
1314
|
+
server.stop(true);
|
|
1315
|
+
}
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
//#endregion
|
|
1319
|
+
export { startLocalEmailServer };
|
|
1320
|
+
|
|
1321
|
+
//# sourceMappingURL=testing.mjs.map
|