@mandateops/cli-linux-x64 0.0.0-stage → 0.7.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 (68) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +175 -2
  3. package/audit-lab/README.md +194 -0
  4. package/audit-lab/bin/mandateops +0 -0
  5. package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
  6. package/audit-lab/contracts/history-reading.md +185 -0
  7. package/audit-lab/contracts/history-reading.vectors.json +284 -0
  8. package/audit-lab/contracts/profiles.md +161 -0
  9. package/audit-lab/contracts/properties.md +512 -0
  10. package/audit-lab/contracts/sdk-config.md +155 -0
  11. package/audit-lab/contracts/system-under-test.md +385 -0
  12. package/audit-lab/contracts/test-provider.md +350 -0
  13. package/audit-lab/lab/compose.audit.yml +181 -0
  14. package/audit-lab/lab/config/fault-control.json +14 -0
  15. package/audit-lab/lab/examples/agents/Dockerfile +28 -0
  16. package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
  17. package/audit-lab/lab/examples/agents/load.cjs +9 -0
  18. package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
  19. package/audit-lab/lab/examples/agents/package.json +9 -0
  20. package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
  21. package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
  22. package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
  23. package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
  24. package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
  25. package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
  26. package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
  27. package/audit-lab/lab/examples/test-provider/package.json +42 -0
  28. package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
  29. package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
  30. package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
  31. package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
  32. package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
  33. package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
  34. package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
  35. package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
  36. package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
  37. package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
  38. package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
  39. package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
  40. package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
  41. package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
  42. package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
  43. package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
  44. package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
  45. package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
  46. package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
  47. package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
  48. package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
  49. package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
  50. package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
  51. package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
  52. package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
  53. package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
  54. package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
  55. package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
  56. package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
  57. package/audit-lab/lab/images/capture/Dockerfile +15 -0
  58. package/audit-lab/lab/images/capture/LICENSE +201 -0
  59. package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
  60. package/audit-lab/lab/images/fault-control/LICENSE +21 -0
  61. package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
  62. package/audit-lab/lab/images/provider-store/LICENSE +23 -0
  63. package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
  64. package/audit-lab/lab/images/telemetry/LICENSE +201 -0
  65. package/audit-lab/lab/scripts/compose-down.sh +143 -0
  66. package/audit-lab/lab/scripts/compose-lib.sh +632 -0
  67. package/audit-lab/lab/scripts/compose-up.sh +240 -0
  68. package/package.json +16 -4
@@ -0,0 +1,417 @@
1
+ import { z } from "zod";
2
+ import { idSchema, routeSchema } from "./domain.js";
3
+ import { MAX_NOTIFY_COPIES } from "./notify.js";
4
+ import type { PaymentWire, WireReply } from "./wire.js";
5
+
6
+ /**
7
+ * A calibrated provider profile: what a provider's sandbox was observed to do
8
+ * on one date, recorded by one build of the calibration recorder, and the
9
+ * replica behaviour derived from it. Nothing here is invented: a behaviour
10
+ * the recorder could not exercise stays `not_observed` with the reason, and
11
+ * the replica then keeps the declared format's own answer, labelled
12
+ * simulated wherever a run reports it.
13
+ */
14
+
15
+ /** Providers a calibration recorder exists for. */
16
+ export const CALIBRATED_PROVIDERS = ["stripe", "wise"] as const;
17
+ export type CalibratedProvider = (typeof CALIBRATED_PROVIDERS)[number];
18
+
19
+ /** Longest delay a replica imitates; a slower observation is capped. */
20
+ export const MAX_REPLY_DELAY_MS = 30_000;
21
+ /** Most scenarios one profile may carry. */
22
+ export const MAX_PROFILE_SCENARIOS = 64;
23
+ /** Most other outcomes one scenario may record beside its first. */
24
+ export const MAX_ALTERNATIVES = 4;
25
+ /** Most calls one scenario may record. */
26
+ export const MAX_SCENARIO_STEPS = 16;
27
+
28
+ const reasonSchema = z.string().min(1).max(400);
29
+
30
+ /** Where a provider puts an error code: `errors[0].code`, `error.code` or `errorCode`. */
31
+ export const ERROR_SHAPES = ["errors", "error", "flat"] as const;
32
+ export type ErrorShape = (typeof ERROR_SHAPES)[number];
33
+ const statusSchema = z.number().int().min(100).max(599);
34
+
35
+ /** One call as observed, reduced to the facts compared; ids stay out. */
36
+ export const stepSchema = z
37
+ .object({
38
+ call: idSchema,
39
+ /** null when no reply arrived (a network failure after retries). */
40
+ status: statusSchema.nullable(),
41
+ errorCode: z.string().max(120).nullable(),
42
+ /** The reply carried the provider's replay marker. */
43
+ replayed: z.boolean(),
44
+ /** Whether the reply names the object the scenario's first call created. */
45
+ sameObjectAsFirst: z.boolean().nullable(),
46
+ /** The provider's object state the reply named, if any. */
47
+ state: z.string().max(80).nullable(),
48
+ /** The reply arrived within the scenario's client timeout. */
49
+ withinTimeout: z.boolean(),
50
+ /** Where the error code sat in the body; recorded, not compared. */
51
+ errorShape: z.enum(ERROR_SHAPES).nullable(),
52
+ })
53
+ .strict();
54
+ export type Step = z.infer<typeof stepSchema>;
55
+
56
+ /** Notifications as observed for one scenario's object. */
57
+ export const notificationObservationSchema = z
58
+ .object({
59
+ events: z.array(idSchema).max(64),
60
+ duplicates: z.number().int().min(0).max(64),
61
+ /** Milliseconds from the call to the first event, as the provider dated it. */
62
+ firstDelayMs: z.number().int().min(0).nullable(),
63
+ })
64
+ .strict();
65
+ export type NotificationObservation = z.infer<
66
+ typeof notificationObservationSchema
67
+ >;
68
+
69
+ /**
70
+ * What one scenario showed. `blocked` means the provider refused a
71
+ * precondition for this credential and the refusal is the observation;
72
+ * `not_exercised` means nothing was sent, with the reason.
73
+ */
74
+ export const scenarioSchema = z.discriminatedUnion("outcome", [
75
+ z
76
+ .object({
77
+ scenario: idSchema,
78
+ outcome: z.literal("observed"),
79
+ steps: z.array(stepSchema).min(1).max(MAX_SCENARIO_STEPS),
80
+ /** Other outcomes repeats of a racing scenario showed; any is accepted. */
81
+ alternatives: z
82
+ .array(z.array(stepSchema).min(1).max(MAX_SCENARIO_STEPS))
83
+ .max(MAX_ALTERNATIVES)
84
+ .optional(),
85
+ notifications: notificationObservationSchema.optional(),
86
+ })
87
+ .strict(),
88
+ z
89
+ .object({
90
+ scenario: idSchema,
91
+ outcome: z.literal("blocked"),
92
+ reason: reasonSchema,
93
+ steps: z.array(stepSchema).min(1).max(MAX_SCENARIO_STEPS),
94
+ /** Other outcomes repeats of a racing scenario showed; any is accepted. */
95
+ alternatives: z
96
+ .array(z.array(stepSchema).min(1).max(MAX_SCENARIO_STEPS))
97
+ .max(MAX_ALTERNATIVES)
98
+ .optional(),
99
+ })
100
+ .strict(),
101
+ z
102
+ .object({
103
+ scenario: idSchema,
104
+ outcome: z.literal("not_exercised"),
105
+ reason: reasonSchema,
106
+ })
107
+ .strict(),
108
+ ]);
109
+ export type ScenarioObservation = z.infer<typeof scenarioSchema>;
110
+
111
+ /** Statuses that refuse the recording credential a call: the scenario is blocked. */
112
+ const BLOCKING_STATUSES: ReadonlySet<number> = new Set([401, 403]);
113
+
114
+ /** The index of the first step the provider refused this credential, or -1. */
115
+ export const blockedAt = (steps: readonly Step[]): number =>
116
+ steps.findIndex(
117
+ (step) => step.status !== null && BLOCKING_STATUSES.has(step.status),
118
+ );
119
+
120
+ const observedReplySchema = z
121
+ .object({
122
+ status: statusSchema,
123
+ errorCode: z.string().max(120).nullable(),
124
+ errorShape: z.enum(ERROR_SHAPES).nullable(),
125
+ })
126
+ .strict();
127
+ export type ObservedReply = z.infer<typeof observedReplySchema>;
128
+ const notObservedSchema = z
129
+ .object({ observed: z.literal(false), reason: reasonSchema })
130
+ .strict();
131
+
132
+ /** The replica behaviour derived from the observations. */
133
+ export const replicaSchema = z
134
+ .object({
135
+ /** The header a replayed reply carries, when the provider sends one. */
136
+ replayMarker: z
137
+ .object({
138
+ header: z
139
+ .string()
140
+ .regex(/^[a-z0-9-]{1,64}$/)
141
+ .nullable(),
142
+ value: z.string().max(64).nullable(),
143
+ })
144
+ .strict(),
145
+ refusals: z.union([
146
+ z
147
+ .object({
148
+ observed: z.literal(true),
149
+ replay: z.enum(["retryable", "final"]),
150
+ })
151
+ .strict(),
152
+ notObservedSchema,
153
+ ]),
154
+ declined: z.union([
155
+ z
156
+ .object({ observed: z.literal(true), reply: observedReplySchema })
157
+ .strict(),
158
+ notObservedSchema,
159
+ ]),
160
+ /**
161
+ * The same key with changed terms: refused with the observed reply, or
162
+ * answered with the original object as if the terms were the first.
163
+ */
164
+ changedTerms: z.union([
165
+ z
166
+ .object({
167
+ observed: z.literal(true),
168
+ answer: z.literal("refused"),
169
+ reply: observedReplySchema,
170
+ })
171
+ .strict(),
172
+ z
173
+ .object({ observed: z.literal(true), answer: z.literal("original") })
174
+ .strict(),
175
+ notObservedSchema,
176
+ ]),
177
+ /** The state a funded transfer read as, when one could be read. */
178
+ fundedState: z.union([
179
+ z
180
+ .object({ observed: z.literal(true), state: z.string().min(1).max(80) })
181
+ .strict(),
182
+ notObservedSchema,
183
+ ]),
184
+ /** Per route: observed latency, state and the answer to a race on one key. */
185
+ routes: z
186
+ .array(
187
+ z
188
+ .object({
189
+ route: routeSchema,
190
+ call: idSchema,
191
+ delayMs: z.number().int().min(0).max(MAX_REPLY_DELAY_MS),
192
+ /** The state a reply names, when every observation agreed. */
193
+ state: z.string().max(80).nullable(),
194
+ race: z.union([
195
+ z
196
+ .object({
197
+ observed: z.literal(true),
198
+ /**
199
+ * Every outcome a race showed, in recorded order; null is
200
+ * an outcome where both requests were answered alike. The
201
+ * replica picks among them by its seed.
202
+ */
203
+ replies: z
204
+ .array(observedReplySchema.nullable())
205
+ .min(1)
206
+ .max(MAX_ALTERNATIVES + 1),
207
+ })
208
+ .strict(),
209
+ notObservedSchema,
210
+ ]),
211
+ })
212
+ .strict(),
213
+ )
214
+ .max(8),
215
+ notifications: z.union([
216
+ z
217
+ .object({
218
+ observed: z.literal(true),
219
+ copies: z.number().int().min(1).max(MAX_NOTIFY_COPIES),
220
+ delayMs: z.number().int().min(0).max(MAX_REPLY_DELAY_MS),
221
+ })
222
+ .strict(),
223
+ notObservedSchema,
224
+ ]),
225
+ })
226
+ .strict();
227
+ export type ReplicaBehaviour = z.infer<typeof replicaSchema>;
228
+
229
+ export const profileSchema = z
230
+ .object({
231
+ provider: z.enum(CALIBRATED_PROVIDERS),
232
+ /** The SDK format the replica serves. */
233
+ format: idSchema,
234
+ calibratedOn: z.iso.date(),
235
+ /** The recorder's build: the source commit it ran from. */
236
+ build: z.string().regex(/^[0-9a-f]{7,40}$/),
237
+ /** Distinct real calls the calibration spent, and its hard cap. */
238
+ realCalls: z.number().int().min(0),
239
+ realCallCap: z.number().int().min(1),
240
+ scenarios: z.array(scenarioSchema).min(1).max(MAX_PROFILE_SCENARIOS),
241
+ replica: replicaSchema,
242
+ })
243
+ .strict()
244
+ .refine((profile) => profile.realCalls <= profile.realCallCap, {
245
+ message: "a profile cannot record more real calls than its cap",
246
+ })
247
+ .refine(
248
+ (profile) =>
249
+ new Set(profile.scenarios.map((one) => one.scenario)).size ===
250
+ profile.scenarios.length,
251
+ { message: "each scenario appears once" },
252
+ );
253
+ export type CalibratedProfile = z.infer<typeof profileSchema>;
254
+
255
+ /** The key a profile is filed and cited under. */
256
+ export const profileKey = ({
257
+ provider,
258
+ calibratedOn,
259
+ build,
260
+ }: Pick<CalibratedProfile, "provider" | "calibratedOn" | "build">): string =>
261
+ `${provider}-${calibratedOn}-${build}`;
262
+
263
+ /**
264
+ * How a repeated key with other terms is answered by a staged format:
265
+ * refused (the default, recorded under `rejected`), or, as a calibrated
266
+ * profile may have observed, with the original object, its terms unchanged.
267
+ */
268
+ export type ChangedTerms = "refused" | "original";
269
+
270
+ /** How the replica must build a staged format for this profile. */
271
+ export const changedTermsOf = (profile: CalibratedProfile): ChangedTerms =>
272
+ profile.replica.changedTerms.observed &&
273
+ profile.replica.changedTerms.answer === "original"
274
+ ? "original"
275
+ : "refused";
276
+
277
+ /** Parse a profile, refusing anything the schema does not state. */
278
+ export function loadProfile(text: string): CalibratedProfile {
279
+ return profileSchema.parse(JSON.parse(text));
280
+ }
281
+
282
+ const withStatus = (
283
+ reply: WireReply,
284
+ observed: ReplicaBehaviour["declined"],
285
+ ): WireReply =>
286
+ observed.observed ? { ...reply, status: observed.reply.status } : reply;
287
+
288
+ /**
289
+ * The declared wire answering as the profile observed: the replay marker on
290
+ * a repeat, the observed refusal replay, and the observed status of a
291
+ * declined or conflicting request. Bodies stay the declaration's own.
292
+ */
293
+ export function replicaWire(
294
+ wire: PaymentWire,
295
+ { replica }: CalibratedProfile,
296
+ ): PaymentWire {
297
+ const { header, value } = replica.replayMarker;
298
+ if (
299
+ wire.preparatory.length === 0 &&
300
+ replica.changedTerms.observed &&
301
+ replica.changedTerms.answer === "original"
302
+ )
303
+ throw new Error(
304
+ "this replica cannot answer changed terms with the original payment for a single-call format",
305
+ );
306
+ return {
307
+ ...wire,
308
+ refusals: replica.refusals.observed
309
+ ? replica.refusals.replay
310
+ : wire.refusals,
311
+ paid: (effect, created, sentKey) => {
312
+ const reply = wire.paid(effect, created, sentKey);
313
+ return created || header === null || value === null
314
+ ? reply
315
+ : { ...reply, headers: { ...reply.headers, [header]: value } };
316
+ },
317
+ declined: (request) => withStatus(wire.declined(request), replica.declined),
318
+ conflict: (request) => {
319
+ const reply = wire.conflict(request);
320
+ const { changedTerms } = replica;
321
+ return changedTerms.observed && changedTerms.answer === "refused"
322
+ ? observedReply(changedTerms.reply, reply.headers)
323
+ : reply;
324
+ },
325
+ preparatory: wire.preparatory.map((route) => {
326
+ const state =
327
+ replica.routes.find((one) => one.route === route.path)?.state ?? null;
328
+ const { changedTerms } = replica;
329
+ return {
330
+ ...route,
331
+ answer: (body, params, headers) => {
332
+ const answered = route.answer(body, params, headers);
333
+ if (answered.refused)
334
+ return changedTerms.observed && changedTerms.answer === "refused"
335
+ ? { ...answered, reply: observedReply(changedTerms.reply) }
336
+ : answered;
337
+ return state === null
338
+ ? answered
339
+ : { ...answered, reply: withState(answered.reply, state) };
340
+ },
341
+ };
342
+ }),
343
+ };
344
+ }
345
+
346
+ /** A reply body naming `state` where the declaration's names none. */
347
+ function withState(reply: WireReply, state: string): WireReply {
348
+ const { body } = reply;
349
+ if (
350
+ reply.status >= 300 ||
351
+ typeof body !== "object" ||
352
+ body === null ||
353
+ Array.isArray(body) ||
354
+ "status" in body
355
+ )
356
+ return reply;
357
+ return { ...reply, body: { ...body, status: state } };
358
+ }
359
+
360
+ /** The observed status and error code, in the observed body shape. */
361
+ export function observedReply(
362
+ { status, errorCode, errorShape }: ObservedReply,
363
+ headers: Readonly<Record<string, string>> = {},
364
+ ): WireReply {
365
+ const code = errorCode ?? "error";
366
+ const body =
367
+ errorShape === "errors"
368
+ ? { errors: [{ code }] }
369
+ : errorShape === "error"
370
+ ? { error: { code } }
371
+ : { errorCode: code };
372
+ return { status, body, headers };
373
+ }
374
+
375
+ /**
376
+ * Picks race outcomes from a seed, so a run's sequence of race replies can
377
+ * be replayed and every recorded outcome occurs.
378
+ */
379
+ export class RaceChoice {
380
+ private drawn = 0;
381
+
382
+ constructor(private readonly seed: number) {}
383
+
384
+ /** The index of the next outcome among `count`. */
385
+ next(count: number): number {
386
+ this.drawn += 1;
387
+ let state =
388
+ (Math.imul(this.seed ^ 0x9e3779b9, 0x85ebca6b) ^ this.drawn) >>> 0;
389
+ state = Math.imul(state ^ (state >>> 16), 0x7feb352d) >>> 0;
390
+ state = Math.imul(state ^ (state >>> 15), 0x846ca68b) >>> 0;
391
+ return ((state ^ (state >>> 16)) >>> 0) % count;
392
+ }
393
+
394
+ reset(): void {
395
+ this.drawn = 0;
396
+ }
397
+ }
398
+
399
+ /** Answers a request repeated while the first is still being answered. */
400
+ export class InFlight {
401
+ private readonly pending = new Set<string>();
402
+
403
+ /** Runs `answer` unless an identical request is in flight. */
404
+ async run<T>(
405
+ fingerprint: string,
406
+ raced: () => T,
407
+ answer: () => Promise<T>,
408
+ ): Promise<T> {
409
+ if (this.pending.has(fingerprint)) return raced();
410
+ this.pending.add(fingerprint);
411
+ try {
412
+ return await answer();
413
+ } finally {
414
+ this.pending.delete(fingerprint);
415
+ }
416
+ }
417
+ }
@@ -0,0 +1,201 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { KEY_SHAPES, ROUTE_PARAMETER } from "./declaration.js";
3
+ import type { DeclaredWire, Terms } from "./declaration.js";
4
+ import { ProviderError, providerKeySchema } from "./domain.js";
5
+ import type { Instruction } from "./domain.js";
6
+ import type { RequestHeaders } from "./wire.js";
7
+
8
+ /** Joins the parts of a term a format splits, such as bank and account. */
9
+ const JOINED_SEPARATOR = "--";
10
+ /** A currency counted in one asset but funded from another names both. */
11
+ const COUNTED_FROM = "-from-";
12
+
13
+ /** One request as its declaration reads it, with every term read from here. */
14
+ export type RequestReader = Readonly<{
15
+ declared: DeclaredWire;
16
+ body: unknown;
17
+ params: unknown;
18
+ }>;
19
+ /** What a request's amount says: as written, in which terms and at what scale. */
20
+ type StatedAmount = Readonly<{
21
+ written: unknown;
22
+ terms: Terms;
23
+ digits: number;
24
+ }>;
25
+
26
+ /** An own-property walk, so a path can never reach an inherited member. */
27
+ function walk(root: unknown, steps: readonly string[]): unknown {
28
+ let current = root;
29
+ for (const step of steps) {
30
+ if (
31
+ typeof current !== "object" ||
32
+ current === null ||
33
+ !Object.hasOwn(current, step)
34
+ )
35
+ return undefined;
36
+ current = (current as Record<string, unknown>)[step];
37
+ }
38
+ return current;
39
+ }
40
+
41
+ const text = (value: unknown): string | undefined =>
42
+ typeof value === "string" ? value : undefined;
43
+
44
+ /** The identifier of a URL under `resource`; the host is the client's own. */
45
+ function identifierUnder(value: unknown, resource: string): string | undefined {
46
+ const written = text(value);
47
+ if (written === undefined || !URL.canParse(written)) return undefined;
48
+ const { pathname } = new URL(written);
49
+ return pathname.startsWith(resource)
50
+ ? pathname.slice(resource.length)
51
+ : undefined;
52
+ }
53
+
54
+ /** The scale of exactly `asset`. An undeclared asset has none and is refused. */
55
+ function assetDigits(amount: DeclaredWire["amount"], asset: unknown): number {
56
+ if ("minorDigits" in amount) return amount.minorDigits;
57
+ const digits =
58
+ typeof asset === "string" && Object.hasOwn(amount.scales, asset)
59
+ ? amount.scales[asset]
60
+ : undefined;
61
+ if (digits === undefined) throw new ProviderError(400, "unsupported_asset");
62
+ return digits;
63
+ }
64
+
65
+ const scaleTermOf = (amount: DeclaredWire["amount"], terms: Terms): unknown =>
66
+ "minorDigits" in amount ? undefined : terms[amount.scaleTerm];
67
+
68
+ /** The scale of an instruction `read` passed, which may name what funded it. */
69
+ export function recordedDigits(
70
+ declared: DeclaredWire,
71
+ instruction: Instruction,
72
+ ): number {
73
+ const { amount } = declared;
74
+ const named = scaleTermOf(amount, instruction);
75
+ if (typeof named === "string" && named.includes(COUNTED_FROM))
76
+ return assetDigits(amount, named.split(COUNTED_FROM)[0]);
77
+ return assetDigits(
78
+ amount,
79
+ scaleTermOf(amount, countedIn(declared, instruction)),
80
+ );
81
+ }
82
+
83
+ function valueAt(
84
+ { declared, body, params }: RequestReader,
85
+ path: string,
86
+ ): unknown {
87
+ if (path.startsWith(ROUTE_PARAMETER))
88
+ return walk(params, [path.slice(ROUTE_PARAMETER.length)]);
89
+ return walk(body, declared.encoding === "form" ? [path] : path.split("."));
90
+ }
91
+
92
+ /** A default answers only absence: a term written wrongly is refused. */
93
+ function termAt(
94
+ request: RequestReader,
95
+ name: string,
96
+ path: string,
97
+ ): string | undefined {
98
+ const value = valueAt(request, path);
99
+ if (value === undefined) return request.declared.defaults[name];
100
+ const resource = request.declared.urlFields[name];
101
+ const found =
102
+ resource === undefined ? text(value) : identifierUnder(value, resource);
103
+ if (found === undefined) throw new ProviderError(400, "invalid_term");
104
+ return found;
105
+ }
106
+
107
+ export function requireShape(request: RequestReader): void {
108
+ for (const path of request.declared.singleEntry) {
109
+ const entries = valueAt(request, path);
110
+ if (!Array.isArray(entries) || entries.length !== 1)
111
+ throw new ProviderError(400, "single_entry_required");
112
+ }
113
+ }
114
+
115
+ export function keyOf(request: RequestReader, headers: RequestHeaders): string {
116
+ const { key } = request.declared;
117
+ const sent =
118
+ "header" in key ? headers[key.header] : valueAt(request, key.field);
119
+ if (sent === undefined && "optional" in key)
120
+ if (key.optional) return randomUUID();
121
+ if ("shape" in key && key.shape) KEY_SHAPES[key.shape].parse(sent);
122
+ return providerKeySchema.max(key.maxLength).parse(sent);
123
+ }
124
+
125
+ const onePart = (part: string | undefined): boolean =>
126
+ part !== undefined &&
127
+ part !== "" &&
128
+ !part.includes(JOINED_SEPARATOR) &&
129
+ !part.startsWith("-") &&
130
+ !part.endsWith("-");
131
+
132
+ function joinedTerm(request: RequestReader, paths: readonly string[]): string {
133
+ const parts = paths.map((path) => text(valueAt(request, path)));
134
+ if (!parts.every(onePart)) throw new ProviderError(400, "invalid_term");
135
+ return parts.join(JOINED_SEPARATOR);
136
+ }
137
+
138
+ export function statedTerms(request: RequestReader): Terms {
139
+ const { fields, joined } = request.declared;
140
+ const mapped = Object.entries(fields)
141
+ .filter(([name]) => name !== "amount")
142
+ .map(([name, path]) => [name, termAt(request, name, path ?? "")] as const);
143
+ const combined = Object.entries(joined).map(
144
+ ([name, paths]) => [name, joinedTerm(request, paths ?? [])] as const,
145
+ );
146
+ return Object.fromEntries(
147
+ [...mapped, ...combined].filter(([, value]) => value !== undefined),
148
+ );
149
+ }
150
+
151
+ /** What an amount counts in; the terms themselves keep what the request said. */
152
+ function countedIn(declared: DeclaredWire, terms: Terms): Terms {
153
+ return Object.fromEntries(
154
+ Object.entries(terms).map(([name, value]) => {
155
+ const table = declared.pegged[name] ?? {};
156
+ const counted =
157
+ typeof value === "string" && Object.hasOwn(table, value)
158
+ ? table[value]
159
+ : value;
160
+ return [name, counted];
161
+ }),
162
+ );
163
+ }
164
+
165
+ /**
166
+ * The primary amount counts in the stated terms. The alternate counts in its
167
+ * own currency, so the term names that and what funds it, and a changed source
168
+ * still changes the terms. Both sides must be declared assets.
169
+ */
170
+ export function statedAmount(
171
+ request: RequestReader,
172
+ stated: Terms,
173
+ ): StatedAmount {
174
+ const { declared } = request;
175
+ const primary = valueAt(request, declared.fields["amount"] ?? "");
176
+ const alternate = declared.alternateAmount;
177
+ const second = alternate && valueAt(request, alternate.path);
178
+ if (primary !== undefined && second !== undefined)
179
+ throw new ProviderError(400, "invalid_amount");
180
+ if (alternate && second !== undefined) {
181
+ const counted = valueAt(request, alternate.currency);
182
+ const funded = stated["currency"];
183
+ assetDigits(declared.amount, funded);
184
+ return {
185
+ written: second,
186
+ terms: {
187
+ ...stated,
188
+ currency: `${String(counted)}${COUNTED_FROM}${String(funded)}`,
189
+ },
190
+ digits: assetDigits(declared.amount, counted),
191
+ };
192
+ }
193
+ return {
194
+ written: primary === undefined ? declared.amountDefault : primary,
195
+ terms: stated,
196
+ digits: assetDigits(
197
+ declared.amount,
198
+ scaleTermOf(declared.amount, countedIn(declared, stated)),
199
+ ),
200
+ };
201
+ }