@nymbalhq/contract-tests 1.5.0 → 1.6.0

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/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import {
2
2
  CONTRACT_KINDS
3
- } from "./chunk-KK53D2KL.js";
3
+ } from "./chunk-ABEL44IM.js";
4
4
 
5
- // src/analytics.ts
5
+ // src/ai.ts
6
+ import { randomInt } from "crypto";
7
+ import { inspect } from "util";
8
+ import fc from "fast-check";
6
9
  import { describe as describe2, expect as expect2, it as it2 } from "vitest";
7
10
 
8
11
  // src/common.ts
@@ -94,24 +97,838 @@ function healthAndDowntime(build, unreachable, label, operation) {
94
97
  });
95
98
  }
96
99
 
100
+ // src/ai.ts
101
+ var HANG_TIMEOUT_MS = 300;
102
+ var HANG_BOUND_MS = HANG_TIMEOUT_MS + 2e3;
103
+ var STATUS_CODES = [
104
+ ["status:400", "adapter.invalid_request"],
105
+ ["status:401", "adapter.auth_failed"],
106
+ ["status:403", "adapter.auth_failed"],
107
+ ["status:429", "adapter.rate_limited"],
108
+ ["status:500", "adapter.unavailable"],
109
+ ["status:529", "adapter.unavailable"],
110
+ ["html:502", "adapter.unavailable"],
111
+ ["no-text", "adapter.unexpected_response"],
112
+ ["not-json", "adapter.unexpected_response"]
113
+ ];
114
+ var ALL_MODES = [
115
+ ...STATUS_CODES.map(([mode]) => mode),
116
+ "hang",
117
+ "unreachable"
118
+ ];
119
+ function chatOf(adapter) {
120
+ const chat = adapter.chat;
121
+ expect2(typeof chat, "the adapter has no chat()").toBe("function");
122
+ return chat.bind(adapter);
123
+ }
124
+ function chatStreamOf(adapter) {
125
+ const stream = adapter.chatStream;
126
+ expect2(typeof stream, "the adapter lists stream but has no chatStream()").toBe("function");
127
+ return stream.bind(adapter);
128
+ }
129
+ function lists(adapter, capability, requires) {
130
+ const listed = adapter.capabilities().includes(capability);
131
+ if (!listed && requires.includes(capability)) {
132
+ expect2.fail(
133
+ `capabilities() is ${JSON.stringify(adapter.capabilities())}, without ${capability}, which this adapter must list`
134
+ );
135
+ }
136
+ return listed;
137
+ }
138
+ async function drain(stream, ms, onEvent = () => void 0) {
139
+ const events = [];
140
+ const outcome = await settle(async () => {
141
+ for await (const event3 of stream()) {
142
+ events.push(event3);
143
+ onEvent(event3);
144
+ }
145
+ }, ms);
146
+ return { events, outcome };
147
+ }
148
+ var textsOf = (events) => events.flatMap((e) => e.type === "text" ? [e.delta] : []);
149
+ var callsOf = (events) => events.flatMap((e) => e.type === "tool_call" ? [e.call] : []);
150
+ var donesOf = (events) => events.flatMap((e) => e.type === "done" ? [e.result] : []);
151
+ function completeOf(adapter) {
152
+ return (prompt, opts) => adapter.complete(prompt, opts);
153
+ }
154
+ async function rejection(call, ms = BOUND_MS) {
155
+ const outcome = await settle(call, ms);
156
+ expect2(
157
+ outcome.state,
158
+ outcome.state === "hung" ? `still pending after ${ms} ms` : "it resolved"
159
+ ).toBe("rejected");
160
+ const thrown = outcome.state === "rejected" ? outcome.error : void 0;
161
+ const fields = typeof thrown === "object" && thrown !== null ? thrown : {};
162
+ return {
163
+ thrown,
164
+ name: fields["name"],
165
+ code: fields["code"],
166
+ message: fields["message"],
167
+ context: fields["context"],
168
+ hasCause: "cause" in fields,
169
+ ms: outcome.ms
170
+ };
171
+ }
172
+ function recordingLogger(records) {
173
+ const at = (level) => (...args) => {
174
+ records.push([level, ...args]);
175
+ };
176
+ const logger = {
177
+ trace: at("trace"),
178
+ debug: at("debug"),
179
+ info: at("info"),
180
+ warn: at("warn"),
181
+ error: at("error"),
182
+ child: (bindings) => {
183
+ records.push(["child", bindings]);
184
+ return logger;
185
+ }
186
+ };
187
+ return logger;
188
+ }
189
+ var deep = (value) => inspect(value, { depth: Infinity, showHidden: true });
190
+ function formsOf(key) {
191
+ const bytes = Buffer.from(key, "utf8");
192
+ return [key, bytes.toString("base64").replace(/=+$/, ""), bytes.toString("base64url")];
193
+ }
194
+ var keyArb = fc.string({
195
+ unit: fc.constantFrom(
196
+ ..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split("")
197
+ ),
198
+ minLength: 16,
199
+ maxLength: 48
200
+ }).filter((s) => new Set(s).size >= 8);
201
+ var refusedInput = fc.oneof(
202
+ fc.constant({ messages: [], opts: {} }),
203
+ fc.constant({
204
+ messages: [
205
+ { role: "assistant", content: "Hello." },
206
+ { role: "user", content: "Say hello." }
207
+ ],
208
+ opts: {}
209
+ }),
210
+ fc.integer({ min: 0, max: 2 }).map((empty) => ({
211
+ messages: [
212
+ { role: "user", content: "The code word is lantern." },
213
+ { role: "assistant", content: "Noted." },
214
+ { role: "user", content: "Say hello." }
215
+ ].map((turn, i) => i === empty ? { ...turn, content: "" } : turn),
216
+ opts: {}
217
+ })),
218
+ fc.oneof(
219
+ fc.integer({ min: -1e6, max: 0 }),
220
+ fc.double({ min: 1e-3, max: 4096, noNaN: true }).filter((n) => !Number.isInteger(n)),
221
+ fc.constantFrom(Number.NaN, Number.POSITIVE_INFINITY)
222
+ ).map((maxTokens) => ({
223
+ messages: [{ role: "user", content: "Say hello." }],
224
+ opts: { maxTokens }
225
+ }))
226
+ );
227
+ var CODE_WORDS = ["lantern", "juniper", "saffron", "harbour", "quartz", "meadow"];
228
+ var LOOKUP_PRICE = {
229
+ name: "lookup_price",
230
+ description: "The price of one product, by its SKU.",
231
+ inputSchema: {
232
+ type: "object",
233
+ properties: { sku: { type: "string", description: "The product SKU, e.g. B-4." } },
234
+ required: ["sku"],
235
+ additionalProperties: false
236
+ }
237
+ };
238
+ var E5_ASK = "What does SKU A-17 cost? Use the lookup_price tool.";
239
+ var E5_RESULT = "A-17 costs 42.50 EUR.";
240
+ var toolNamed = (name) => ({
241
+ name,
242
+ description: "Reads one thing from the store.",
243
+ inputSchema: { type: "object", properties: {} }
244
+ });
245
+ var TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
246
+ var callIdArb = fc.string({
247
+ unit: fc.constantFrom(..."abcdefghijklmnopqrstuvwxyz0123456789_".split("")),
248
+ minLength: 4,
249
+ maxLength: 24
250
+ });
251
+ var twoIds = fc.tuple(callIdArb, callIdArb).filter(([a, b]) => a !== b);
252
+ var askFor = (id) => ({ id, name: "lookup_price", args: { sku: "A-17" } });
253
+ var user = (content) => ({ role: "user", content });
254
+ var assistant = (content, toolCalls) => toolCalls === void 0 ? { role: "assistant", content } : { role: "assistant", content, toolCalls };
255
+ var toolTurn = (toolCallId, content) => ({
256
+ role: "tool",
257
+ toolCallId,
258
+ content
259
+ });
260
+ var refusedToolInput = fc.oneof(
261
+ twoIds.map(([a, b]) => ({
262
+ why: "a tool turn answers no call of the assistant turn before it",
263
+ messages: [user(E5_ASK), assistant("", [askFor(a)]), toolTurn(b, E5_RESULT)],
264
+ opts: { tools: [LOOKUP_PRICE] }
265
+ })),
266
+ twoIds.map(([a, b]) => ({
267
+ why: "a tool turn answers a call of an earlier assistant turn, not the nearest",
268
+ messages: [
269
+ user(E5_ASK),
270
+ assistant("", [askFor(a)]),
271
+ toolTurn(a, E5_RESULT),
272
+ user("And SKU B-2? Use the lookup_price tool."),
273
+ assistant("", [askFor(b)]),
274
+ toolTurn(a, E5_RESULT)
275
+ ],
276
+ opts: { tools: [LOOKUP_PRICE] }
277
+ })),
278
+ callIdArb.map((a) => ({
279
+ why: "a tool turn follows the user turn, with no assistant turn before it",
280
+ messages: [user(E5_ASK), toolTurn(a, E5_RESULT)],
281
+ opts: { tools: [LOOKUP_PRICE] }
282
+ })),
283
+ twoIds.map(([a, b]) => ({
284
+ why: "a call is left unanswered when the next user turn starts",
285
+ messages: [
286
+ user(E5_ASK),
287
+ assistant("", [askFor(a), askFor(b)]),
288
+ toolTurn(a, E5_RESULT),
289
+ user("Go on.")
290
+ ],
291
+ opts: { tools: [LOOKUP_PRICE] }
292
+ })),
293
+ callIdArb.map((a) => ({
294
+ why: "a call is left unanswered when the next assistant turn starts",
295
+ messages: [user(E5_ASK), assistant("", [askFor(a)]), assistant("It costs 42.50 EUR.")],
296
+ opts: { tools: [LOOKUP_PRICE] }
297
+ })),
298
+ fc.constantFrom(void 0, []).map((toolCalls) => ({
299
+ why: "an assistant turn has empty content and no calls",
300
+ messages: [user(E5_ASK), assistant("", toolCalls), user("Go on.")],
301
+ opts: { tools: [LOOKUP_PRICE] }
302
+ })),
303
+ callIdArb.map((a) => ({
304
+ why: "a tool turn has empty content",
305
+ messages: [user(E5_ASK), assistant("", [askFor(a)]), toolTurn(a, "")],
306
+ opts: { tools: [LOOKUP_PRICE] }
307
+ })),
308
+ fc.stringMatching(TOOL_NAME).map((name) => ({
309
+ why: `two tools are named ${name}`,
310
+ messages: [user("Say hello.")],
311
+ opts: { tools: [toolNamed(name), LOOKUP_PRICE, toolNamed(name)] }
312
+ })),
313
+ fc.oneof(
314
+ fc.constant(""),
315
+ fc.constant("x".repeat(65)),
316
+ fc.stringMatching(/^[A-Za-z0-9_-]{65,90}$/),
317
+ fc.string({ minLength: 1, maxLength: 20 }).filter((name) => !TOOL_NAME.test(name))
318
+ ).map((name) => ({
319
+ why: `the tool name ${JSON.stringify(name)} is outside ^[A-Za-z0-9_-]{1,64}$`,
320
+ messages: [user("Say hello.")],
321
+ opts: { tools: [LOOKUP_PRICE, toolNamed(name)] }
322
+ }))
323
+ );
324
+ var STREAMED = [
325
+ {
326
+ label: "E1",
327
+ tools: false,
328
+ messages: () => [user("Reply with exactly the word PONG.")],
329
+ opts: {}
330
+ },
331
+ {
332
+ label: "E2",
333
+ tools: false,
334
+ messages: () => {
335
+ const word2 = `${CODE_WORDS[randomInt(CODE_WORDS.length)]}${randomInt(100, 1e3)}`;
336
+ return [
337
+ user(`The code word is ${word2}.`),
338
+ assistant("Noted."),
339
+ user("What is the code word? Reply with the word only.")
340
+ ];
341
+ },
342
+ opts: {}
343
+ },
344
+ {
345
+ label: "E3",
346
+ tools: false,
347
+ messages: () => [user("Say hello.")],
348
+ opts: { system: "Answer only in upper case." }
349
+ },
350
+ {
351
+ label: "a count cut at maxTokens 5",
352
+ tools: false,
353
+ messages: () => [user("Count from 1 to 12.")],
354
+ opts: { maxTokens: 5 }
355
+ },
356
+ {
357
+ label: "E5 first turn",
358
+ tools: true,
359
+ messages: () => [user(E5_ASK)],
360
+ opts: { tools: [LOOKUP_PRICE] }
361
+ }
362
+ ];
363
+ var STREAM_STATUS = [
364
+ ["status:401", "adapter.auth_failed"],
365
+ ["status:429", "adapter.rate_limited"],
366
+ ["status:529", "adapter.unavailable"]
367
+ ];
368
+ var STREAM_MODES = ["stream-break", "stream-error"];
369
+ var words = (text) => text.split(/\s+/).filter((w) => w !== "");
370
+ async function underDebug(run) {
371
+ const written = [];
372
+ const out = process.stdout.write;
373
+ const err = process.stderr.write;
374
+ const terminal = console;
375
+ const methods = ["log", "info", "warn", "error", "debug", "trace", "dir"];
376
+ const saved = methods.map((method) => terminal[method]);
377
+ const debug = process.env["DEBUG"];
378
+ const capture = ((chunk2) => {
379
+ written.push(
380
+ typeof chunk2 === "string" ? chunk2 : Buffer.from(chunk2).toString("utf8")
381
+ );
382
+ return true;
383
+ });
384
+ process.stdout.write = capture;
385
+ process.stderr.write = capture;
386
+ for (const method of methods) {
387
+ terminal[method] = (...args) => {
388
+ written.push(args.map((arg) => typeof arg === "string" ? arg : deep(arg)).join(" "));
389
+ };
390
+ }
391
+ process.env["DEBUG"] = "true";
392
+ try {
393
+ return { value: await run(), written };
394
+ } finally {
395
+ process.stdout.write = out;
396
+ process.stderr.write = err;
397
+ methods.forEach((method, i) => {
398
+ terminal[method] = saved[i];
399
+ });
400
+ if (debug === void 0) delete process.env["DEBUG"];
401
+ else process.env["DEBUG"] = debug;
402
+ }
403
+ }
404
+ async function until(ready, ms) {
405
+ const deadline = Date.now() + ms;
406
+ while (!ready() && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
407
+ }
408
+ function runAiContract(name, build, options = {}) {
409
+ describe2(`ai contract: ${name}`, () => {
410
+ it2(
411
+ 'eval E1: "Reply with exactly the word PONG." answers PONG, stopReason end, usage on both sides and a model',
412
+ () => using(build, async (adapter) => {
413
+ const result = await chatOf(adapter)([
414
+ { role: "user", content: "Reply with exactly the word PONG." }
415
+ ]);
416
+ expect2(result.text).toContain("PONG");
417
+ expect2(result.stopReason).toBe("end");
418
+ expect2(result.usage.inputTokens).toBeGreaterThan(0);
419
+ expect2(result.usage.outputTokens).toBeGreaterThan(0);
420
+ expect2(result.model.trim().length, "the model is empty").toBeGreaterThan(0);
421
+ }),
422
+ CASE_MS
423
+ );
424
+ it2(
425
+ "eval E2: a three-turn conversation recalls the code word from the first turn",
426
+ () => using(build, async (adapter) => {
427
+ const word2 = `${CODE_WORDS[randomInt(CODE_WORDS.length)]}${randomInt(100, 1e3)}`;
428
+ const result = await chatOf(adapter)([
429
+ { role: "user", content: `The code word is ${word2}.` },
430
+ { role: "assistant", content: "Noted." },
431
+ { role: "user", content: "What is the code word? Reply with the word only." }
432
+ ]);
433
+ expect2(result.text.toLowerCase()).toContain(word2);
434
+ }),
435
+ CASE_MS
436
+ );
437
+ it2(
438
+ 'eval E3: system "Answer only in upper case." makes the answer its own upper case',
439
+ () => using(build, async (adapter) => {
440
+ const result = await chatOf(adapter)([{ role: "user", content: "Say hello." }], {
441
+ system: "Answer only in upper case."
442
+ });
443
+ expect2(result.text, "the answer has no letter").toMatch(/[A-Z]/);
444
+ expect2(result.text).toBe(result.text.toUpperCase());
445
+ }),
446
+ CASE_MS
447
+ );
448
+ it2(
449
+ 'eval E4: maxTokens 1 on "Count from 1 to 100." stops at max_tokens with at most one output token',
450
+ () => using(build, async (adapter) => {
451
+ const result = await chatOf(adapter)(
452
+ [{ role: "user", content: "Count from 1 to 100." }],
453
+ { maxTokens: 1 }
454
+ );
455
+ expect2(result.stopReason).toBe("max_tokens");
456
+ expect2(result.usage.outputTokens).toBeLessThanOrEqual(1);
457
+ }),
458
+ CASE_MS
459
+ );
460
+ const requires = options.requires ?? [];
461
+ it2(
462
+ `AC-1: eval E5: with the lookup_price tool, "What does SKU A-17 cost?" asks for one call { sku: "A-17" } with an id and stops at tool_use; sending that call and its result back answers with the result's price`,
463
+ (ctx) => using(build, async (adapter) => {
464
+ if (!lists(adapter, "tools", requires)) return ctx.skip();
465
+ const chat = chatOf(adapter);
466
+ const ask = user(E5_ASK);
467
+ const first = await chat([ask], { tools: [LOOKUP_PRICE] });
468
+ expect2(first.stopReason).toBe("tool_use");
469
+ const calls = first.toolCalls ?? [];
470
+ expect2(calls.map((c) => c.name)).toEqual(["lookup_price"]);
471
+ const call = calls[0];
472
+ expect2(call.args).toEqual({ sku: "A-17" });
473
+ expect2(call.id.trim(), "the call has no id").not.toBe("");
474
+ const second = await chat(
475
+ [ask, assistant(first.text, first.toolCalls), toolTurn(call.id, E5_RESULT)],
476
+ { tools: [LOOKUP_PRICE] }
477
+ );
478
+ expect2(second.text).toContain("42.50");
479
+ expect2(second.toolCalls ?? []).toEqual([]);
480
+ }),
481
+ CASE_MS
482
+ );
483
+ const requests = options.requests;
484
+ if (requests !== void 0) {
485
+ it2(
486
+ "AC-3: a tool turn answering no call of the nearest assistant turn, an unanswered call, an empty assistant turn with no calls, an empty tool turn, two tools of one name or a tool name outside ^[A-Za-z0-9_-]{1,64}$ rejects adapter.invalid_request with no request made",
487
+ (ctx) => using(build, async (adapter) => {
488
+ if (!lists(adapter, "tools", requires)) return ctx.skip();
489
+ const chat = chatOf(adapter);
490
+ await fc.assert(
491
+ fc.asyncProperty(refusedToolInput, async ({ why, messages, opts }) => {
492
+ const before = requests();
493
+ const error = await rejection(() => chat(messages, opts));
494
+ expect2(error.code, `${why}: ${String(error.message)}`).toBe(
495
+ "adapter.invalid_request"
496
+ );
497
+ expect2(error.context).toEqual({ provider: adapter.providerName });
498
+ expect2(requests() - before, `${why}: a request was made`).toBe(0);
499
+ }),
500
+ { numRuns: 60 }
501
+ );
502
+ }),
503
+ CASE_MS
504
+ );
505
+ for (const { label, tools, messages, opts } of STREAMED) {
506
+ it2(
507
+ `AC-5: chatStream() on ${label}: one done, last, whose text the text deltas concatenate to (two or more for a multi-word answer) and whose calls the tool_call events are, equal in text, stopReason and calls to chat() on the same conversation, one request each`,
508
+ (ctx) => using(build, async (adapter) => {
509
+ if (!lists(adapter, "stream", requires)) return ctx.skip();
510
+ if (tools && !lists(adapter, "tools", requires)) return ctx.skip();
511
+ const conversation = messages();
512
+ const before = requests();
513
+ const { events, outcome } = await drain(
514
+ () => chatStreamOf(adapter)(conversation, opts),
515
+ BOUND_MS
516
+ );
517
+ expect2(outcome.state, outcome.state === "rejected" ? deep(outcome.error) : "").toBe(
518
+ "resolved"
519
+ );
520
+ const dones = donesOf(events);
521
+ expect2(dones, "not exactly one done event").toHaveLength(1);
522
+ expect2(events.at(-1)?.type).toBe("done");
523
+ const done = dones[0];
524
+ const texts = textsOf(events);
525
+ expect2(texts.join("")).toBe(done.text);
526
+ expect2(texts.length).toBeGreaterThanOrEqual(Math.min(words(done.text).length, 2));
527
+ expect2(callsOf(events)).toEqual(done.toolCalls);
528
+ const viaChat = await chatOf(adapter)(conversation, opts);
529
+ expect2({
530
+ text: done.text,
531
+ stopReason: done.stopReason,
532
+ toolCalls: done.toolCalls
533
+ }).toEqual({
534
+ text: viaChat.text,
535
+ stopReason: viaChat.stopReason,
536
+ toolCalls: viaChat.toolCalls
537
+ });
538
+ expect2(requests() - before).toBe(2);
539
+ }),
540
+ CASE_MS
541
+ );
542
+ }
543
+ it2(
544
+ "input: empty messages, a first turn that is not the user, an empty content or a maxTokens that is not a positive integer rejects adapter.invalid_request with no request made",
545
+ () => using(build, async (adapter) => {
546
+ const chat = chatOf(adapter);
547
+ await fc.assert(
548
+ fc.asyncProperty(refusedInput, async ({ messages, opts }) => {
549
+ const before = requests();
550
+ const error = await rejection(() => chat(messages, opts));
551
+ expect2(error.code, String(error.message)).toBe("adapter.invalid_request");
552
+ expect2(error.context).toEqual({ provider: adapter.providerName });
553
+ expect2(requests()).toBe(before);
554
+ }),
555
+ { numRuns: 30 }
556
+ );
557
+ }),
558
+ CASE_MS
559
+ );
560
+ it2(
561
+ "complete(prompt, { maxTokens }) answers what chat() answers as text for the same single user turn, in one request",
562
+ () => using(build, async (adapter) => {
563
+ const chat = chatOf(adapter);
564
+ const complete = completeOf(adapter);
565
+ for (const [prompt, maxTokens] of [
566
+ ["Reply with exactly the word PONG.", 16],
567
+ ["Count from 1 to 100.", 1]
568
+ ]) {
569
+ const viaChat = await chat([{ role: "user", content: prompt }], { maxTokens });
570
+ const before = requests();
571
+ const viaComplete = await complete(prompt, { maxTokens });
572
+ expect2(requests() - before, "complete() made other than one request").toBe(1);
573
+ expect2(viaComplete, `${prompt} with maxTokens ${maxTokens}`).toBe(viaChat.text);
574
+ }
575
+ }),
576
+ CASE_MS
577
+ );
578
+ }
579
+ const failing = options.failing;
580
+ if (failing !== void 0) {
581
+ describe2("provider failures", () => {
582
+ async function failOnce(mode, key, content, ms) {
583
+ const records = [];
584
+ const built = await failing(mode, key, recordingLogger(records));
585
+ try {
586
+ const chat = chatOf(built.adapter);
587
+ const error = await rejection(() => chat([{ role: "user", content }]), ms);
588
+ return {
589
+ error,
590
+ thrown: error.thrown,
591
+ records,
592
+ requests: built.requests(),
593
+ provider: built.adapter.providerName
594
+ };
595
+ } finally {
596
+ await built.close();
597
+ }
598
+ }
599
+ for (const [mode, code] of STATUS_CODES) {
600
+ it2(
601
+ `${mode} rejects ${code} after exactly one request, its context only provider and status`,
602
+ async () => {
603
+ const key = `sk-contract-${randomInt(1e9, 1e10)}-key`;
604
+ const {
605
+ error,
606
+ requests: made,
607
+ provider
608
+ } = await failOnce(mode, key, "Say hello.", BOUND_MS);
609
+ expect2(error.code, String(error.message)).toBe(code);
610
+ expect2(error.name).toBe("AdapterError");
611
+ expect2(made).toBe(1);
612
+ expect2(error.hasCause, "the error keeps a cause").toBe(false);
613
+ const context = error.context ?? {};
614
+ expect2(
615
+ Object.keys(context).filter((k) => k !== "provider" && k !== "status")
616
+ ).toEqual([]);
617
+ expect2(context["provider"]).toBe(provider);
618
+ const message = String(error.message);
619
+ if (mode.startsWith("status:")) {
620
+ const status = Number(mode.slice("status:".length));
621
+ expect2(context["status"]).toBe(status);
622
+ expect2(message).toBe(`${provider} answered ${status}`);
623
+ } else if (mode === "html:502") {
624
+ expect2(context["status"]).toBe(502);
625
+ expect2(message).toBe(`${provider} answered 502`);
626
+ } else {
627
+ expect2([void 0, 200]).toContain(context["status"]);
628
+ }
629
+ },
630
+ CASE_MS
631
+ );
632
+ }
633
+ it2(
634
+ `a refused connection rejects adapter.unavailable within ${BOUND_MS} ms: "<provider> could not be reached"`,
635
+ async () => {
636
+ const { error, provider } = await failOnce(
637
+ "unreachable",
638
+ "sk-contract-unreachable-key",
639
+ "Say hello.",
640
+ BOUND_MS
641
+ );
642
+ expect2(error.code, String(error.message)).toBe("adapter.unavailable");
643
+ expect2(error.ms).toBeLessThanOrEqual(BOUND_MS);
644
+ expect2(error.hasCause, "the error keeps a cause").toBe(false);
645
+ expect2(error.context).toEqual({ provider });
646
+ expect2(error.message).toBe(`${provider} could not be reached`);
647
+ },
648
+ CASE_MS
649
+ );
650
+ it2(
651
+ `a provider that never answers rejects adapter.timeout after timeoutMs ${HANG_TIMEOUT_MS} and within ${HANG_BOUND_MS} ms, after one request`,
652
+ async () => {
653
+ const {
654
+ error,
655
+ requests: made,
656
+ provider
657
+ } = await failOnce("hang", "sk-contract-hanging-key", "Say hello.", HANG_BOUND_MS);
658
+ expect2(error.code, String(error.message)).toBe("adapter.timeout");
659
+ expect2(error.ms).toBeGreaterThanOrEqual(HANG_TIMEOUT_MS - 10);
660
+ expect2(error.ms).toBeLessThanOrEqual(HANG_BOUND_MS);
661
+ expect2(made).toBe(1);
662
+ expect2(error.hasCause, "the error keeps a cause").toBe(false);
663
+ expect2(error.context).toEqual({ provider });
664
+ expect2(error.message).toBe(`${provider} gave no answer within ${HANG_TIMEOUT_MS} ms`);
665
+ },
666
+ CASE_MS
667
+ );
668
+ async function streamOnce(mode, content, ms, opts = {}, onEvent) {
669
+ const built = await failing(
670
+ mode,
671
+ `sk-contract-${randomInt(1e9, 1e10)}-key`,
672
+ recordingLogger([])
673
+ );
674
+ try {
675
+ if (!lists(built.adapter, "stream", requires)) return void 0;
676
+ const stream = chatStreamOf(built.adapter);
677
+ const started = Date.now();
678
+ const { events, outcome } = await drain(
679
+ () => stream([user(content)], opts),
680
+ ms,
681
+ onEvent
682
+ );
683
+ expect2(
684
+ outcome.state,
685
+ outcome.state === "hung" ? `still pending after ${ms} ms` : "it resolved"
686
+ ).toBe("rejected");
687
+ const thrown = outcome.state === "rejected" ? outcome.error : {};
688
+ return {
689
+ events,
690
+ code: thrown["code"],
691
+ name: thrown["name"],
692
+ context: thrown["context"],
693
+ hasCause: "cause" in thrown,
694
+ settledAt: started + outcome.ms,
695
+ requests: built.requests(),
696
+ sent: built.sent?.() ?? [],
697
+ closed: built.closed,
698
+ provider: built.adapter.providerName
699
+ };
700
+ } finally {
701
+ await built.close();
702
+ }
703
+ }
704
+ for (const [mode, code] of STREAM_STATUS) {
705
+ it2(
706
+ `AC-6: chatStream() on ${mode} rejects ${code} before any event, after one request, its context only provider and status`,
707
+ async (ctx) => {
708
+ const failed = await streamOnce(mode, "Say hello.", BOUND_MS);
709
+ if (failed === void 0) return ctx.skip();
710
+ expect2(failed.code).toBe(code);
711
+ expect2(failed.name).toBe("AdapterError");
712
+ expect2(failed.events).toEqual([]);
713
+ expect2(failed.requests).toBe(1);
714
+ expect2(failed.hasCause, "the error keeps a cause").toBe(false);
715
+ expect2(failed.context).toEqual({
716
+ provider: failed.provider,
717
+ status: Number(mode.slice("status:".length))
718
+ });
719
+ },
720
+ CASE_MS
721
+ );
722
+ }
723
+ it2(
724
+ "AC-6: chatStream() on a connection broken after two deltas yields those two deltas, no done, and rejects adapter.unavailable after one request",
725
+ async (ctx) => {
726
+ const failed = await streamOnce("stream-break", "Count from 1 to 10.", BOUND_MS);
727
+ if (failed === void 0) return ctx.skip();
728
+ expect2(failed.code).toBe("adapter.unavailable");
729
+ expect2(textsOf(failed.events)).toEqual(failed.sent);
730
+ expect2(failed.sent).toHaveLength(2);
731
+ expect2(donesOf(failed.events)).toEqual([]);
732
+ expect2(failed.requests).toBe(1);
733
+ },
734
+ CASE_MS
735
+ );
736
+ it2(
737
+ "AC-6: chatStream() on the provider's mid-stream error event yields no done and rejects adapter.unavailable after one request",
738
+ async (ctx) => {
739
+ const failed = await streamOnce("stream-error", "Count from 1 to 10.", BOUND_MS);
740
+ if (failed === void 0) return ctx.skip();
741
+ expect2(failed.code).toBe("adapter.unavailable");
742
+ expect2(donesOf(failed.events)).toEqual([]);
743
+ expect2(failed.hasCause, "the error keeps a cause").toBe(false);
744
+ expect2(failed.requests).toBe(1);
745
+ },
746
+ CASE_MS
747
+ );
748
+ for (const mode of ["hang", "stream-stall"]) {
749
+ it2(
750
+ `AC-6: chatStream() on a provider that ${mode === "hang" ? "never answers" : "stops after one delta"} rejects adapter.timeout after timeoutMs ${HANG_TIMEOUT_MS} and within ${HANG_BOUND_MS} ms, after one request`,
751
+ async (ctx) => {
752
+ const started = Date.now();
753
+ const failed = await streamOnce(mode, "Count from 1 to 10.", HANG_BOUND_MS);
754
+ if (failed === void 0) return ctx.skip();
755
+ expect2(failed.code).toBe("adapter.timeout");
756
+ expect2(failed.settledAt - started).toBeGreaterThanOrEqual(HANG_TIMEOUT_MS - 10);
757
+ expect2(failed.settledAt - started).toBeLessThanOrEqual(HANG_BOUND_MS);
758
+ expect2(textsOf(failed.events)).toEqual(failed.sent);
759
+ expect2(failed.requests).toBe(1);
760
+ },
761
+ CASE_MS
762
+ );
763
+ }
764
+ it2(
765
+ "AC-6: aborting the signal after the first delta rejects adapter.cancelled within 1000 ms and the provider sees its connection closed",
766
+ async (ctx) => {
767
+ const controller = new AbortController();
768
+ let abortedAt = 0;
769
+ const failed = await streamOnce(
770
+ "stream-stall",
771
+ "Count from 1 to 10.",
772
+ BOUND_MS,
773
+ { signal: controller.signal },
774
+ (event3) => {
775
+ if (event3.type === "text" && abortedAt === 0) {
776
+ abortedAt = Date.now();
777
+ controller.abort();
778
+ }
779
+ }
780
+ );
781
+ if (failed === void 0) return ctx.skip();
782
+ expect2(failed.code).toBe("adapter.cancelled");
783
+ expect2(abortedAt, "no text delta arrived before the stream ended").not.toBe(0);
784
+ expect2(failed.settledAt - abortedAt).toBeLessThanOrEqual(1e3);
785
+ expect2(typeof failed.closed, "the failing build reports no closed connections").toBe(
786
+ "function"
787
+ );
788
+ await until(() => failed.closed() === 1, 1e3);
789
+ expect2(failed.closed()).toBe(1);
790
+ expect2(failed.requests).toBe(1);
791
+ },
792
+ CASE_MS
793
+ );
794
+ it2("AC-7: property: with DEBUG=true, over chat() and chatStream(), every failure (the stream ones included) and a random configured key, neither the key (raw, base64, base64url) nor the user message appears in stdout, stderr or the console, in the error inspected or serialised, or in any log record", async () => {
795
+ const probe = await failing("status:500", "sk-contract-probe-key", recordingLogger([]));
796
+ const streams = probe.adapter.capabilities().includes("stream");
797
+ await probe.close();
798
+ const runs = [
799
+ ...ALL_MODES.map((mode) => ["chat", mode]),
800
+ ...streams ? [...ALL_MODES, ...STREAM_MODES].map((mode) => ["chatStream", mode]) : []
801
+ ];
802
+ await fc.assert(
803
+ fc.asyncProperty(
804
+ fc.constantFrom(...runs),
805
+ keyArb,
806
+ fc.uuid(),
807
+ async ([via, mode], key, marker) => {
808
+ const content = `Count from 1 to 10. Private note ${marker}.`;
809
+ const records = [];
810
+ const built = await failing(mode, key, recordingLogger(records));
811
+ let thrown;
812
+ let written = [];
813
+ try {
814
+ const failure2 = async () => {
815
+ const { outcome } = via === "chat" ? {
816
+ outcome: await settle(
817
+ () => chatOf(built.adapter)([user(content)]),
818
+ HANG_BOUND_MS + BOUND_MS
819
+ )
820
+ } : await drain(
821
+ () => chatStreamOf(built.adapter)([user(content)]),
822
+ HANG_BOUND_MS + BOUND_MS
823
+ );
824
+ return outcome.state === "rejected" ? outcome.error : void 0;
825
+ };
826
+ const ran = await underDebug(failure2);
827
+ thrown = ran.value;
828
+ written = ran.written;
829
+ } finally {
830
+ await built.close();
831
+ }
832
+ expect2(thrown, `${via} on ${mode} did not reject`).toBeInstanceOf(Error);
833
+ const outputs = [
834
+ deep(thrown),
835
+ JSON.stringify(thrown) ?? "",
836
+ ...records.map((record) => record.map(deep).join(" ")),
837
+ ...written
838
+ ];
839
+ const forms = formsOf(key);
840
+ expect2(
841
+ outputs.flatMap(
842
+ (text, at) => forms.filter((form) => text.includes(form)).map((form) => `${at}: ${form}`)
843
+ ),
844
+ `the key leaked from ${via} on ${mode}`
845
+ ).toEqual([]);
846
+ expect2(
847
+ outputs.filter((text) => text.includes(marker)).map((text) => text.slice(0, 200)),
848
+ `the user message leaked from ${via} on ${mode}`
849
+ ).toEqual([]);
850
+ }
851
+ ),
852
+ {
853
+ numRuns: runs.length + 12,
854
+ // Every run kind on every mode once, so a leak in one branch only cannot pass by chance.
855
+ examples: runs.map(
856
+ (run) => [
857
+ run,
858
+ "sk-Ex4mple_Key-012345678",
859
+ "6f1c2a3b-4d5e-4f60-8a71-b2c3d4e5f607"
860
+ ]
861
+ )
862
+ }
863
+ );
864
+ }, 18e4);
865
+ it2("property: over every failure and a random configured key, neither the key nor its base64 or base64url is in the error inspected or serialised, or in any log record, and no log record holds the message text", async () => {
866
+ await fc.assert(
867
+ fc.asyncProperty(
868
+ fc.constantFrom(...ALL_MODES),
869
+ keyArb,
870
+ fc.uuid(),
871
+ async (mode, key, marker) => {
872
+ const content = `Say hello. Private note ${marker}.`;
873
+ const { thrown, records } = await failOnce(
874
+ mode,
875
+ key,
876
+ content,
877
+ HANG_BOUND_MS + BOUND_MS
878
+ );
879
+ const outputs = [
880
+ deep(thrown),
881
+ JSON.stringify(thrown) ?? "",
882
+ ...records.map((record) => record.map(deep).join(" "))
883
+ ];
884
+ const forms = formsOf(key);
885
+ expect2(
886
+ outputs.flatMap(
887
+ (text, at) => forms.filter((form) => text.includes(form)).map((form) => `${at}: ${form}`)
888
+ ),
889
+ `the key leaked under ${mode}`
890
+ ).toEqual([]);
891
+ expect2(
892
+ records.filter((record) => record.map(deep).join(" ").includes(marker)),
893
+ `a log record holds the message text under ${mode}`
894
+ ).toEqual([]);
895
+ }
896
+ ),
897
+ {
898
+ numRuns: 24,
899
+ // Every mode runs on every run, so a leak in one branch only cannot pass by chance.
900
+ examples: ALL_MODES.map((mode) => [
901
+ mode,
902
+ "sk-Ex4mple_Key-012345678",
903
+ "6f1c2a3b-4d5e-4f60-8a71-b2c3d4e5f607"
904
+ ])
905
+ }
906
+ );
907
+ }, 12e4);
908
+ });
909
+ }
910
+ });
911
+ }
912
+
97
913
  // src/analytics.ts
914
+ import { describe as describe3, expect as expect3, it as it3 } from "vitest";
98
915
  function runAnalyticsContract(name, build, options = {}) {
99
- describe2(`AnalyticsAdapter contract: ${name}`, () => {
100
- it2(
916
+ describe3(`AnalyticsAdapter contract: ${name}`, () => {
917
+ it3(
101
918
  "track resolves without throwing",
102
919
  async () => {
103
920
  const adapter = await build();
104
- await expect2(
921
+ await expect3(
105
922
  adapter.track("product_viewed", { productId: "prod-1", source: "test" })
106
923
  ).resolves.not.toThrow();
107
924
  },
108
925
  CASE_MS
109
926
  );
110
- it2(
927
+ it3(
111
928
  "identify resolves without throwing",
112
929
  async () => {
113
930
  const adapter = await build();
114
- await expect2(
931
+ await expect3(
115
932
  adapter.identify("user-1", { email: "test@example.com", plan: "free" })
116
933
  ).resolves.not.toThrow();
117
934
  },
@@ -127,11 +944,11 @@ function runAnalyticsContract(name, build, options = {}) {
127
944
  }
128
945
 
129
946
  // src/document-store.ts
130
- import { describe as describe4, expect as expect5, it as it5 } from "vitest";
947
+ import { describe as describe5, expect as expect6, it as it6 } from "vitest";
131
948
 
132
949
  // src/document-store-model.ts
133
- import fc from "fast-check";
134
- import { describe as describe3, expect as expect3, it as it3 } from "vitest";
950
+ import fc2 from "fast-check";
951
+ import { describe as describe4, expect as expect4, it as it4 } from "vitest";
135
952
  import {
136
953
  compareDocumentValues,
137
954
  matchesSortKey
@@ -139,40 +956,40 @@ import {
139
956
  var COLLECTION = "contract-docs";
140
957
  var DECOY = "contract-decoy";
141
958
  var SLOW = 6e4;
142
- var valueArb = fc.oneof(
143
- fc.constantFrom("a", "A", "\xE1", "b", "B", "\xE9", "e", "ab", "Ab", "1", "10", "2"),
144
- fc.integer({ min: -2, max: 10 }),
145
- fc.constant(null)
959
+ var valueArb = fc2.oneof(
960
+ fc2.constantFrom("a", "A", "\xE1", "b", "B", "\xE9", "e", "ab", "Ab", "1", "10", "2"),
961
+ fc2.integer({ min: -2, max: 10 }),
962
+ fc2.constant(null)
146
963
  );
147
- var fieldArb = fc.option(valueArb, { nil: void 0, freq: 4 });
148
- var docsArb = (minLength) => fc.uniqueArray(
149
- fc.record({
964
+ var fieldArb = fc2.option(valueArb, { nil: void 0, freq: 4 });
965
+ var docsArb = (minLength) => fc2.uniqueArray(
966
+ fc2.record({
150
967
  // Random keys, so key order is unrelated to value order.
151
- key: fc.stringMatching(/^[a-z0-9]{1,6}$/),
152
- part: fc.constantFrom("p", "q"),
968
+ key: fc2.stringMatching(/^[a-z0-9]{1,6}$/),
969
+ part: fc2.constantFrom("p", "q"),
153
970
  v: fieldArb,
154
971
  n: fieldArb
155
972
  }),
156
973
  { minLength, maxLength: 14, selector: (d) => d.key }
157
974
  );
158
- var sortKeyArb = fc.option(
159
- fc.oneof(
160
- fc.record({
161
- field: fc.constant("v"),
162
- operator: fc.constantFrom("eq", "gt", "lt"),
975
+ var sortKeyArb = fc2.option(
976
+ fc2.oneof(
977
+ fc2.record({
978
+ field: fc2.constant("v"),
979
+ operator: fc2.constantFrom("eq", "gt", "lt"),
163
980
  value: valueArb
164
981
  }),
165
- fc.record({
166
- field: fc.constant("v"),
167
- operator: fc.constant("between"),
168
- value: fc.tuple(valueArb, valueArb)
982
+ fc2.record({
983
+ field: fc2.constant("v"),
984
+ operator: fc2.constant("between"),
985
+ value: fc2.tuple(valueArb, valueArb)
169
986
  })
170
987
  ),
171
988
  { nil: void 0 }
172
989
  );
173
- var orderByArb = fc.record({
174
- field: fc.constantFrom("v", "nested.v"),
175
- direction: fc.constantFrom("asc", "desc")
990
+ var orderByArb = fc2.record({
991
+ field: fc2.constantFrom("v", "nested.v"),
992
+ direction: fc2.constantFrom("asc", "desc")
176
993
  });
177
994
  function stored(g) {
178
995
  return {
@@ -253,7 +1070,7 @@ async function closing(store, body) {
253
1070
  await store.close();
254
1071
  }
255
1072
  }
256
- async function rejection(promise) {
1073
+ async function rejection2(promise) {
257
1074
  return promise.then(
258
1075
  () => null,
259
1076
  (error) => error ?? new Error("rejected with nothing")
@@ -261,28 +1078,28 @@ async function rejection(promise) {
261
1078
  }
262
1079
  var TTL_SECONDS = 1;
263
1080
  function documentStoreModelCases(make, opts) {
264
- describe3("agrees with the reference model", () => {
265
- it3(
1081
+ describe4("agrees with the reference model", () => {
1082
+ it4(
266
1083
  "every query\u2019s page sequence equals the reference: filter by partition and sortKey, order with nulls last and ties by key, slice by limit",
267
1084
  async () => {
268
- await fc.assert(
269
- fc.asyncProperty(
1085
+ await fc2.assert(
1086
+ fc2.asyncProperty(
270
1087
  docsArb(0),
271
- fc.constantFrom("p", "*"),
1088
+ fc2.constantFrom("p", "*"),
272
1089
  sortKeyArb,
273
1090
  orderByArb,
274
- fc.integer({ min: 1, max: 5 }),
1091
+ fc2.integer({ min: 1, max: 5 }),
275
1092
  async (generated, partition, sortKey, orderBy, limit) => {
276
1093
  const { store, docs } = await storeWith(make, generated);
277
1094
  await closing(store, async () => {
278
1095
  const q = { partition, sortKey, orderBy };
279
1096
  const expected = reference(docs, q);
280
1097
  const { pages, ended } = await walk(store, q, limit, docs.length + 2);
281
- expect3(ended, "the cursor walk never ended").toBe(true);
282
- for (const page of pages) expect3(page.length).toBeLessThanOrEqual(limit);
283
- expect3(withoutTrailingEmpty(pages.map(idsOf))).toEqual(chunk(expected, limit));
1098
+ expect4(ended, "the cursor walk never ended").toBe(true);
1099
+ for (const page of pages) expect4(page.length).toBeLessThanOrEqual(limit);
1100
+ expect4(withoutTrailingEmpty(pages.map(idsOf))).toEqual(chunk(expected, limit));
284
1101
  const byId = new Map(docs.map((d) => [d.id, d]));
285
- for (const item of pages.flat()) expect3(item).toEqual(byId.get(item.id));
1102
+ for (const item of pages.flat()) expect4(item).toEqual(byId.get(item.id));
286
1103
  });
287
1104
  }
288
1105
  ),
@@ -291,26 +1108,26 @@ function documentStoreModelCases(make, opts) {
291
1108
  },
292
1109
  SLOW
293
1110
  );
294
- it3(
1111
+ it4(
295
1112
  "without orderBy, a cursor walk returns exactly the reference\u2019s matches, each once",
296
1113
  async () => {
297
- await fc.assert(
298
- fc.asyncProperty(
1114
+ await fc2.assert(
1115
+ fc2.asyncProperty(
299
1116
  docsArb(0),
300
- fc.constantFrom("p", "*"),
1117
+ fc2.constantFrom("p", "*"),
301
1118
  sortKeyArb,
302
- fc.integer({ min: 1, max: 5 }),
1119
+ fc2.integer({ min: 1, max: 5 }),
303
1120
  async (generated, partition, sortKey, limit) => {
304
1121
  const { store, docs } = await storeWith(make, generated);
305
1122
  await closing(store, async () => {
306
1123
  const q = { partition, sortKey, orderBy: void 0 };
307
1124
  const { pages, ended } = await walk(store, q, limit, docs.length + 2);
308
1125
  const walked = idsOf(pages.flat());
309
- expect3(ended, "the cursor walk never ended").toBe(true);
310
- expect3(walked.length, `duplicates in ${walked.join(",")}`).toBe(
1126
+ expect4(ended, "the cursor walk never ended").toBe(true);
1127
+ expect4(walked.length, `duplicates in ${walked.join(",")}`).toBe(
311
1128
  new Set(walked).size
312
1129
  );
313
- expect3([...walked].sort()).toEqual(reference(docs, q));
1130
+ expect4([...walked].sort()).toEqual(reference(docs, q));
314
1131
  });
315
1132
  }
316
1133
  ),
@@ -319,34 +1136,34 @@ function documentStoreModelCases(make, opts) {
319
1136
  },
320
1137
  SLOW
321
1138
  );
322
- it3(
1139
+ it4(
323
1140
  "a cursor walk across a mid-walk delete returns every remaining match exactly once, in the reference order",
324
1141
  async () => {
325
- await fc.assert(
326
- fc.asyncProperty(
1142
+ await fc2.assert(
1143
+ fc2.asyncProperty(
327
1144
  docsArb(3),
328
- fc.option(orderByArb, { nil: void 0 }),
329
- fc.integer({ min: 1, max: 3 }),
330
- fc.nat(),
1145
+ fc2.option(orderByArb, { nil: void 0 }),
1146
+ fc2.integer({ min: 1, max: 3 }),
1147
+ fc2.nat(),
331
1148
  async (generated, orderBy, limit, pick) => {
332
1149
  const { store, docs } = await storeWith(make, generated);
333
1150
  await closing(store, async () => {
334
1151
  const q = { partition: "*", sortKey: void 0, orderBy };
335
1152
  const expected = reference(docs, q);
336
- fc.pre(expected.length > limit);
1153
+ fc2.pre(expected.length > limit);
337
1154
  const deleted = expected[pick % expected.length];
338
1155
  const { pages, ended } = await walk(store, q, limit, docs.length + 2, async (n) => {
339
1156
  if (n === 1) await store.delete(COLLECTION, deleted);
340
1157
  });
341
1158
  const walked = idsOf(pages.flat());
342
- expect3(ended, "the cursor walk never ended").toBe(true);
343
- expect3(walked.length, `duplicates in ${walked.join(",")}`).toBe(
1159
+ expect4(ended, "the cursor walk never ended").toBe(true);
1160
+ expect4(walked.length, `duplicates in ${walked.join(",")}`).toBe(
344
1161
  new Set(walked).size
345
1162
  );
346
- expect3(walked.filter((id) => !expected.includes(id))).toEqual([]);
347
- expect3(expected.filter((id) => id !== deleted && !walked.includes(id))).toEqual([]);
1163
+ expect4(walked.filter((id) => !expected.includes(id))).toEqual([]);
1164
+ expect4(expected.filter((id) => id !== deleted && !walked.includes(id))).toEqual([]);
348
1165
  if (orderBy !== void 0) {
349
- expect3(walked).toEqual(expected.filter((id) => walked.includes(id)));
1166
+ expect4(walked).toEqual(expected.filter((id) => walked.includes(id)));
350
1167
  }
351
1168
  });
352
1169
  }
@@ -356,7 +1173,7 @@ function documentStoreModelCases(make, opts) {
356
1173
  },
357
1174
  SLOW
358
1175
  );
359
- it3(
1176
+ it4(
360
1177
  "a cursor issued under one orderBy is refused under another, and continues the walk under its own",
361
1178
  async () => {
362
1179
  const generated = ["k1", "k2", "k3", "k4", "k5"].map((key, i) => ({
@@ -373,23 +1190,23 @@ function documentStoreModelCases(make, opts) {
373
1190
  orderBy: { field: "v", direction: "asc" }
374
1191
  };
375
1192
  const first = await store.query(COLLECTION, params(asc, 2));
376
- expect3(first.nextCursor).not.toBeNull();
1193
+ expect4(first.nextCursor).not.toBeNull();
377
1194
  const cursor = first.nextCursor;
378
1195
  const otherDirection = { ...asc, orderBy: { field: "v", direction: "desc" } };
379
1196
  const otherField = { ...asc, orderBy: { field: "nested.v", direction: "asc" } };
380
- expect3(
381
- await rejection(store.query(COLLECTION, params(otherDirection, 2, cursor)))
1197
+ expect4(
1198
+ await rejection2(store.query(COLLECTION, params(otherDirection, 2, cursor)))
382
1199
  ).toBeInstanceOf(Error);
383
- expect3(
384
- await rejection(store.query(COLLECTION, params(otherField, 2, cursor)))
1200
+ expect4(
1201
+ await rejection2(store.query(COLLECTION, params(otherField, 2, cursor)))
385
1202
  ).toBeInstanceOf(Error);
386
1203
  const next = await store.query(COLLECTION, params(asc, 2, cursor));
387
- expect3(idsOf(next.items)).toEqual(reference(docs, asc).slice(2, 4));
1204
+ expect4(idsOf(next.items)).toEqual(reference(docs, asc).slice(2, 4));
388
1205
  });
389
1206
  },
390
1207
  SLOW
391
1208
  );
392
- it3(
1209
+ it4(
393
1210
  "a document put with a TTL is returned until it expires, then by no get, query or batchGet; one put without stays",
394
1211
  async () => {
395
1212
  const store = await make();
@@ -399,33 +1216,33 @@ function documentStoreModelCases(make, opts) {
399
1216
  const putAt = Date.now();
400
1217
  await store.put(COLLECTION, short.id, short, { ttl: TTL_SECONDS });
401
1218
  await store.put(COLLECTION, long.id, long);
402
- expect3(await store.get(COLLECTION, short.id)).toEqual(short);
1219
+ expect4(await store.get(COLLECTION, short.id)).toEqual(short);
403
1220
  if (opts.clock !== void 0) {
404
1221
  await opts.clock.advance(TTL_SECONDS * 1e3 - 1);
405
- expect3(await store.get(COLLECTION, short.id)).toEqual(short);
1222
+ expect4(await store.get(COLLECTION, short.id)).toEqual(short);
406
1223
  await opts.clock.advance(2);
407
1224
  } else {
408
1225
  const deadline = putAt + TTL_SECONDS * 1e3 + 3e3;
409
1226
  while (await store.get(COLLECTION, short.id) !== null && Date.now() < deadline) {
410
1227
  await new Promise((r) => setTimeout(r, 25));
411
1228
  }
412
- expect3(Date.now() - putAt, "expired before its TTL").toBeGreaterThanOrEqual(
1229
+ expect4(Date.now() - putAt, "expired before its TTL").toBeGreaterThanOrEqual(
413
1230
  TTL_SECONDS * 1e3 - 100
414
1231
  );
415
1232
  }
416
- expect3(await store.get(COLLECTION, short.id)).toBeNull();
1233
+ expect4(await store.get(COLLECTION, short.id)).toBeNull();
417
1234
  const all = await store.query(COLLECTION, {
418
1235
  partitionKey: { field: "part", value: "*" },
419
1236
  limit: 100
420
1237
  });
421
- expect3(idsOf(all.items)).toEqual([long.id]);
1238
+ expect4(idsOf(all.items)).toEqual([long.id]);
422
1239
  const batch = await store.batchGet(COLLECTION, [short.id, long.id]);
423
- expect3([...batch.keys()]).toEqual([long.id]);
1240
+ expect4([...batch.keys()]).toEqual([long.id]);
424
1241
  });
425
1242
  },
426
1243
  SLOW
427
1244
  );
428
- it3("a conditional put applies when the field matches, and otherwise fails condition-failed and changes nothing", async () => {
1245
+ it4("a conditional put applies when the field matches, and otherwise fails condition-failed and changes nothing", async () => {
429
1246
  const store = await make();
430
1247
  await closing(store, async () => {
431
1248
  const v1 = {
@@ -438,8 +1255,8 @@ function documentStoreModelCases(make, opts) {
438
1255
  const v2 = { ...v1, label: "v2", version: 2 };
439
1256
  await store.put(COLLECTION, "c", v1);
440
1257
  await store.put(COLLECTION, "c", v2, { conditionKey: "version", conditionValue: 1 });
441
- expect3(await store.get(COLLECTION, "c")).toEqual(v2);
442
- const stale = await rejection(
1258
+ expect4(await store.get(COLLECTION, "c")).toEqual(v2);
1259
+ const stale = await rejection2(
443
1260
  store.put(
444
1261
  COLLECTION,
445
1262
  "c",
@@ -447,30 +1264,30 @@ function documentStoreModelCases(make, opts) {
447
1264
  { conditionKey: "version", conditionValue: 1 }
448
1265
  )
449
1266
  );
450
- expect3(stale?.code).toBe("adapter.condition-failed");
451
- expect3(await store.get(COLLECTION, "c")).toEqual(v2);
452
- const absent = await rejection(
1267
+ expect4(stale?.code).toBe("adapter.condition-failed");
1268
+ expect4(await store.get(COLLECTION, "c")).toEqual(v2);
1269
+ const absent = await rejection2(
453
1270
  store.put(COLLECTION, "none", v1, { conditionKey: "version", conditionValue: 1 })
454
1271
  );
455
- expect3(absent?.code).toBe("adapter.condition-failed");
456
- expect3(await store.get(COLLECTION, "none")).toBeNull();
1272
+ expect4(absent?.code).toBe("adapter.condition-failed");
1273
+ expect4(await store.get(COLLECTION, "none")).toBeNull();
457
1274
  });
458
1275
  }, CASE_MS);
459
- it3(
1276
+ it4(
460
1277
  "batchPut stores every item and batchGet returns exactly the stored keys, equal to what was put",
461
1278
  async () => {
462
- await fc.assert(
463
- fc.asyncProperty(docsArb(1), async (generated) => {
1279
+ await fc2.assert(
1280
+ fc2.asyncProperty(docsArb(1), async (generated) => {
464
1281
  const store = await make();
465
1282
  await closing(store, async () => {
466
1283
  const docs = generated.map(stored);
467
1284
  await store.batchPut(COLLECTION, new Map(docs.map((d) => [d.id, d])));
468
1285
  const asked = [...docs.map((d) => d.id), "contract-absent"];
469
1286
  const got = await store.batchGet(COLLECTION, asked);
470
- expect3(got.size).toBe(docs.length);
1287
+ expect4(got.size).toBe(docs.length);
471
1288
  for (const doc of docs) {
472
- expect3(got.get(doc.id)).toEqual(doc);
473
- expect3(await store.get(COLLECTION, doc.id)).toEqual(doc);
1289
+ expect4(got.get(doc.id)).toEqual(doc);
1290
+ expect4(await store.get(COLLECTION, doc.id)).toEqual(doc);
474
1291
  }
475
1292
  });
476
1293
  }),
@@ -479,7 +1296,7 @@ function documentStoreModelCases(make, opts) {
479
1296
  },
480
1297
  SLOW
481
1298
  );
482
- it3("collections are isolated for get, query and delete", async () => {
1299
+ it4("collections are isolated for get, query and delete", async () => {
483
1300
  const store = await make();
484
1301
  await closing(store, async () => {
485
1302
  const a = { id: "same", part: "p", nested: {}, label: "A" };
@@ -488,21 +1305,21 @@ function documentStoreModelCases(make, opts) {
488
1305
  await store.put("contract-col-a", a.id, a);
489
1306
  await store.put("contract-col-a", onlyA.id, onlyA);
490
1307
  await store.put("contract-col-b", b.id, b);
491
- expect3(await store.get("contract-col-a", "same")).toEqual(a);
492
- expect3(await store.get("contract-col-b", "same")).toEqual(b);
1308
+ expect4(await store.get("contract-col-a", "same")).toEqual(a);
1309
+ expect4(await store.get("contract-col-b", "same")).toEqual(b);
493
1310
  const inB = await store.query("contract-col-b", {
494
1311
  partitionKey: { field: "part", value: "*" },
495
1312
  limit: 100
496
1313
  });
497
- expect3(idsOf(inB.items)).toEqual([b.id]);
1314
+ expect4(idsOf(inB.items)).toEqual([b.id]);
498
1315
  await store.delete("contract-col-a", "same");
499
- expect3(await store.get("contract-col-b", "same")).toEqual(b);
500
- expect3(await store.get("contract-col-a", "only-a")).toEqual(onlyA);
1316
+ expect4(await store.get("contract-col-b", "same")).toEqual(b);
1317
+ expect4(await store.get("contract-col-a", "only-a")).toEqual(onlyA);
501
1318
  });
502
1319
  }, CASE_MS);
503
1320
  if (opts.isolation !== void 0) {
504
1321
  const isolation = opts.isolation;
505
- it3("two instances with different prefixes never see each other\u2019s documents", async () => {
1322
+ it4("two instances with different prefixes never see each other\u2019s documents", async () => {
506
1323
  const [one, two] = await isolation();
507
1324
  try {
508
1325
  const mine = { id: "shared-key", part: "p", nested: {}, label: "one" };
@@ -510,18 +1327,18 @@ function documentStoreModelCases(make, opts) {
510
1327
  await one.put(COLLECTION, mine.id, mine);
511
1328
  await one.put(COLLECTION, "one-only", { ...mine, id: "one-only" });
512
1329
  await two.put(COLLECTION, theirs.id, theirs);
513
- expect3(await one.get(COLLECTION, mine.id)).toEqual(mine);
514
- expect3(await two.get(COLLECTION, theirs.id)).toEqual(theirs);
515
- expect3(await two.get(COLLECTION, "one-only")).toBeNull();
1330
+ expect4(await one.get(COLLECTION, mine.id)).toEqual(mine);
1331
+ expect4(await two.get(COLLECTION, theirs.id)).toEqual(theirs);
1332
+ expect4(await two.get(COLLECTION, "one-only")).toBeNull();
516
1333
  const inTwo = await two.query(COLLECTION, {
517
1334
  partitionKey: { field: "part", value: "*" },
518
1335
  limit: 100
519
1336
  });
520
- expect3(idsOf(inTwo.items)).toEqual([theirs.id]);
1337
+ expect4(idsOf(inTwo.items)).toEqual([theirs.id]);
521
1338
  const batch = await two.batchGet(COLLECTION, [mine.id, "one-only"]);
522
- expect3([...batch.values()]).toEqual([theirs]);
1339
+ expect4([...batch.values()]).toEqual([theirs]);
523
1340
  await one.delete(COLLECTION, mine.id);
524
- expect3(await two.get(COLLECTION, theirs.id)).toEqual(theirs);
1341
+ expect4(await two.get(COLLECTION, theirs.id)).toEqual(theirs);
525
1342
  } finally {
526
1343
  await one.close();
527
1344
  await two.close();
@@ -532,8 +1349,8 @@ function documentStoreModelCases(make, opts) {
532
1349
  }
533
1350
 
534
1351
  // src/document-store-replace.ts
535
- import fc2 from "fast-check";
536
- import { expect as expect4, it as it4 } from "vitest";
1352
+ import fc3 from "fast-check";
1353
+ import { expect as expect5, it as it5 } from "vitest";
537
1354
  var SLOW2 = 6e4;
538
1355
  var KEYS = ["a", "b", "c", "d", "e", "f", "g", "h"];
539
1356
  var macrotask = () => new Promise((resolve) => setImmediate(resolve));
@@ -553,15 +1370,15 @@ async function putAll(store, collection, docs) {
553
1370
  }
554
1371
  var docsFrom = (keys, v) => keys.map((id) => ({ id, part: "p", v }));
555
1372
  function documentStoreReplaceCases(make, opts) {
556
- it4(
1373
+ it5(
557
1374
  "replaceCollection leaves exactly the new set, whatever the old and new sets: no stale key of the old set survives, and another collection is untouched (property)",
558
1375
  async () => {
559
1376
  await using(make, async (store) => {
560
1377
  let run = 0;
561
- await fc2.assert(
562
- fc2.asyncProperty(
563
- fc2.uniqueArray(fc2.constantFrom(...KEYS)),
564
- fc2.uniqueArray(fc2.constantFrom(...KEYS)),
1378
+ await fc3.assert(
1379
+ fc3.asyncProperty(
1380
+ fc3.uniqueArray(fc3.constantFrom(...KEYS)),
1381
+ fc3.uniqueArray(fc3.constantFrom(...KEYS)),
565
1382
  async (oldKeys, newKeys) => {
566
1383
  run += 1;
567
1384
  const collection = `contract-replace-${run}`;
@@ -570,11 +1387,11 @@ function documentStoreReplaceCases(make, opts) {
570
1387
  await putAll(store, decoy, docsFrom(oldKeys, 3));
571
1388
  const next = docsFrom(newKeys, 2);
572
1389
  await store.replaceCollection(collection, entriesOf(next));
573
- expect4(await snapshot(store, collection)).toEqual(shape(next));
1390
+ expect5(await snapshot(store, collection)).toEqual(shape(next));
574
1391
  for (const key of oldKeys.filter((k) => !newKeys.includes(k))) {
575
- expect4(await store.get(collection, key), `stale key ${key}`).toBeNull();
1392
+ expect5(await store.get(collection, key), `stale key ${key}`).toBeNull();
576
1393
  }
577
- expect4(await snapshot(store, decoy)).toEqual(shape(docsFrom(oldKeys, 3)));
1394
+ expect5(await snapshot(store, decoy)).toEqual(shape(docsFrom(oldKeys, 3)));
578
1395
  }
579
1396
  ),
580
1397
  { numRuns: 25 }
@@ -583,7 +1400,7 @@ function documentStoreReplaceCases(make, opts) {
583
1400
  },
584
1401
  SLOW2
585
1402
  );
586
- it4(
1403
+ it5(
587
1404
  "replaceCollection is atomic to a concurrent reader: polling while the replace runs sees only the full old set or the full new set, never a partial set",
588
1405
  async () => {
589
1406
  await using(make, async (store) => {
@@ -603,19 +1420,19 @@ function documentStoreReplaceCases(make, opts) {
603
1420
  done = true;
604
1421
  });
605
1422
  await reader;
606
- expect4(seen.length, "the reader read while the replace ran").toBeGreaterThan(0);
1423
+ expect5(seen.length, "the reader read while the replace ran").toBeGreaterThan(0);
607
1424
  for (const observed of seen) {
608
- expect4(
1425
+ expect5(
609
1426
  allowed.has(JSON.stringify(observed)),
610
1427
  `a partial set: ${observed.join(" ")}`
611
1428
  ).toBe(true);
612
1429
  }
613
- expect4(await snapshot(store, "contract-replace-reader")).toEqual(shape(next));
1430
+ expect5(await snapshot(store, "contract-replace-reader")).toEqual(shape(next));
614
1431
  });
615
1432
  },
616
1433
  CASE_MS
617
1434
  );
618
- it4(
1435
+ it5(
619
1436
  "replaceCollection whose source throws part-way rejects with the source\u2019s error and leaves the old set intact",
620
1437
  async () => {
621
1438
  await using(make, async (store) => {
@@ -630,34 +1447,34 @@ function documentStoreReplaceCases(make, opts) {
630
1447
  () => null,
631
1448
  (error) => error
632
1449
  );
633
- expect4(String(failed)).toContain("contract: the source failed");
634
- expect4(await snapshot(store, "contract-replace-failing")).toEqual(shape(old));
1450
+ expect5(String(failed)).toContain("contract: the source failed");
1451
+ expect5(await snapshot(store, "contract-replace-failing")).toEqual(shape(old));
635
1452
  });
636
1453
  },
637
1454
  CASE_MS
638
1455
  );
639
- it4(
1456
+ it5(
640
1457
  "replaceCollection with an empty source empties the collection",
641
1458
  async () => {
642
1459
  await using(make, async (store) => {
643
1460
  await putAll(store, "contract-replace-empty", docsFrom(["a", "b"], 1));
644
1461
  await store.replaceCollection("contract-replace-empty", entriesOf([]));
645
- expect4(await snapshot(store, "contract-replace-empty")).toEqual([]);
646
- expect4(await store.get("contract-replace-empty", "a")).toBeNull();
1462
+ expect5(await snapshot(store, "contract-replace-empty")).toEqual([]);
1463
+ expect5(await store.get("contract-replace-empty", "a")).toBeNull();
647
1464
  });
648
1465
  },
649
1466
  CASE_MS
650
1467
  );
651
1468
  const clock = opts.clock;
652
1469
  if (clock !== void 0) {
653
- it4(
1470
+ it5(
654
1471
  "replaceCollection writes documents without a TTL: a key whose old document had one is still there after that TTL passes",
655
1472
  async () => {
656
1473
  await using(make, async (store) => {
657
1474
  await store.put("contract-replace-ttl", "a", { id: "a", part: "p", v: 1 }, { ttl: 60 });
658
1475
  await store.replaceCollection("contract-replace-ttl", entriesOf(docsFrom(["a", "b"], 2)));
659
1476
  await clock.advance(61e3);
660
- expect4(await snapshot(store, "contract-replace-ttl")).toEqual(["a:2", "b:2"]);
1477
+ expect5(await snapshot(store, "contract-replace-ttl")).toEqual(["a:2", "b:2"]);
661
1478
  });
662
1479
  },
663
1480
  CASE_MS
@@ -675,7 +1492,7 @@ async function using2(make, body) {
675
1492
  await store.close();
676
1493
  }
677
1494
  }
678
- async function rejection2(promise) {
1495
+ async function rejection3(promise) {
679
1496
  return promise.then(
680
1497
  () => null,
681
1498
  (error) => error ?? new Error("rejected with nothing")
@@ -700,37 +1517,37 @@ async function walk2(store, collection, params2, between) {
700
1517
  return pages;
701
1518
  }
702
1519
  function runDocumentStoreContract(name, make, opts = {}) {
703
- describe4(`DocumentStoreAdapter contract: ${name}`, () => {
704
- it5(
1520
+ describe5(`DocumentStoreAdapter contract: ${name}`, () => {
1521
+ it6(
705
1522
  "get is null for a missing key; put then get round-trips; a second put overwrites",
706
1523
  async () => {
707
1524
  await using2(make, async (store) => {
708
- expect5(await store.get("col", "missing")).toBeNull();
1525
+ expect6(await store.get("col", "missing")).toBeNull();
709
1526
  await store.put("col", "k1", { name: "test", value: 42, nested: { list: [1, "two"] } });
710
- expect5(await store.get("col", "k1")).toEqual({
1527
+ expect6(await store.get("col", "k1")).toEqual({
711
1528
  name: "test",
712
1529
  value: 42,
713
1530
  nested: { list: [1, "two"] }
714
1531
  });
715
1532
  await store.put("col", "k1", { v: 2 });
716
- expect5(await store.get("col", "k1")).toEqual({ v: 2 });
1533
+ expect6(await store.get("col", "k1")).toEqual({ v: 2 });
717
1534
  });
718
1535
  },
719
1536
  CASE_MS
720
1537
  );
721
- it5(
1538
+ it6(
722
1539
  "delete removes the document, and deleting a missing key does not throw",
723
1540
  async () => {
724
1541
  await using2(make, async (store) => {
725
1542
  await store.put("col", "k1", { v: 1 });
726
1543
  await store.delete("col", "k1");
727
- expect5(await store.get("col", "k1")).toBeNull();
728
- await expect5(store.delete("col", "nope")).resolves.toBeUndefined();
1544
+ expect6(await store.get("col", "k1")).toBeNull();
1545
+ await expect6(store.delete("col", "nope")).resolves.toBeUndefined();
729
1546
  });
730
1547
  },
731
1548
  CASE_MS
732
1549
  );
733
- it5(
1550
+ it6(
734
1551
  "query narrows by partition, and '*' returns the whole collection",
735
1552
  async () => {
736
1553
  await using2(make, async (store) => {
@@ -740,15 +1557,15 @@ function runDocumentStoreContract(name, make, opts = {}) {
740
1557
  { id: "c", part: "p" }
741
1558
  ]);
742
1559
  const p = await store.query("col", { partitionKey: { field: "part", value: "p" } });
743
- expect5(ids(p.items).sort()).toEqual(["a", "c"]);
1560
+ expect6(ids(p.items).sort()).toEqual(["a", "c"]);
744
1561
  const all = await store.query("col", { partitionKey: { field: "part", value: "*" } });
745
- expect5(ids(all.items).sort()).toEqual(["a", "b", "c"]);
746
- expect5(all.nextCursor).toBeNull();
1562
+ expect6(ids(all.items).sort()).toEqual(["a", "b", "c"]);
1563
+ expect6(all.nextCursor).toBeNull();
747
1564
  });
748
1565
  },
749
1566
  CASE_MS
750
1567
  );
751
- it5(
1568
+ it6(
752
1569
  "sortKey eq is strict (1 is not '1', 'a' is not 'A'); gt, lt and between follow compareDocumentValues",
753
1570
  async () => {
754
1571
  await using2(make, async (store) => {
@@ -766,20 +1583,20 @@ function runDocumentStoreContract(name, make, opts = {}) {
766
1583
  sortKey
767
1584
  })).items
768
1585
  ).sort();
769
- expect5(await where({ field: "v", operator: "eq", value: 1 })).toEqual(["n1"]);
770
- expect5(await where({ field: "v", operator: "eq", value: "a" })).toEqual(["sa"]);
771
- expect5(await where({ field: "v", operator: "lt", value: "0" })).toEqual(["n1", "n5"]);
772
- expect5(await where({ field: "v", operator: "gt", value: 5 })).toEqual(
1586
+ expect6(await where({ field: "v", operator: "eq", value: 1 })).toEqual(["n1"]);
1587
+ expect6(await where({ field: "v", operator: "eq", value: "a" })).toEqual(["sa"]);
1588
+ expect6(await where({ field: "v", operator: "lt", value: "0" })).toEqual(["n1", "n5"]);
1589
+ expect6(await where({ field: "v", operator: "gt", value: 5 })).toEqual(
773
1590
  ["nul", "s1", "sA", "sa"].sort()
774
1591
  );
775
- expect5(await where({ field: "v", operator: "between", value: [2, "a"] })).toEqual(
1592
+ expect6(await where({ field: "v", operator: "between", value: [2, "a"] })).toEqual(
776
1593
  ["n5", "s1", "sA", "sa"].sort()
777
1594
  );
778
1595
  });
779
1596
  },
780
1597
  CASE_MS
781
1598
  );
782
- it5(
1599
+ it6(
783
1600
  "orderBy orders by value with the collator, nulls and missing last, ties by key, on a dotted path too",
784
1601
  async () => {
785
1602
  await using2(make, async (store) => {
@@ -796,17 +1613,17 @@ function runDocumentStoreContract(name, make, opts = {}) {
796
1613
  partitionKey: { field: "part", value: "p" },
797
1614
  orderBy: { field: "nested.v", direction: "asc", nulls: "last" }
798
1615
  });
799
- expect5(ids(asc.items)).toEqual(["k6", "k5", "k2", "k1", "k4", "k0", "k3"]);
1616
+ expect6(ids(asc.items)).toEqual(["k6", "k5", "k2", "k1", "k4", "k0", "k3"]);
800
1617
  const desc = await store.query("col", {
801
1618
  partitionKey: { field: "part", value: "p" },
802
1619
  orderBy: { field: "nested.v", direction: "desc", nulls: "last" }
803
1620
  });
804
- expect5(ids(desc.items)).toEqual(["k1", "k4", "k2", "k5", "k6", "k0", "k3"]);
1621
+ expect6(ids(desc.items)).toEqual(["k1", "k4", "k2", "k5", "k6", "k0", "k3"]);
805
1622
  });
806
1623
  },
807
1624
  CASE_MS
808
1625
  );
809
- it5(
1626
+ it6(
810
1627
  "a limit and cursor walk returns every match exactly once, also when a document is deleted mid-walk",
811
1628
  async () => {
812
1629
  await using2(make, async (store) => {
@@ -819,20 +1636,20 @@ function runDocumentStoreContract(name, make, opts = {}) {
819
1636
  ...orderBy !== void 0 && { orderBy }
820
1637
  };
821
1638
  const whole = (await walk2(store, "col", params2)).flat();
822
- expect5(ids(whole).sort()).toEqual(ids(docs).sort());
1639
+ expect6(ids(whole).sort()).toEqual(ids(docs).sort());
823
1640
  const anchor = whole[1];
824
1641
  const walked = (await walk2(store, "col", params2, async (page) => {
825
1642
  if (page === 1) await store.delete("col", anchor.id);
826
1643
  })).flat();
827
- expect5(new Set(ids(walked)).size).toBe(walked.length);
828
- expect5(ids(walked).sort()).toEqual(ids(docs).sort());
1644
+ expect6(new Set(ids(walked)).size).toBe(walked.length);
1645
+ expect6(ids(walked).sort()).toEqual(ids(docs).sort());
829
1646
  await store.put("col", anchor.id, anchor);
830
1647
  }
831
1648
  });
832
1649
  },
833
1650
  SLOW3
834
1651
  );
835
- it5(
1652
+ it6(
836
1653
  "a cursor issued under one orderBy is refused under another, and continues under its own",
837
1654
  async () => {
838
1655
  await using2(make, async (store) => {
@@ -847,25 +1664,25 @@ function runDocumentStoreContract(name, make, opts = {}) {
847
1664
  limit: 2
848
1665
  };
849
1666
  const first = await store.query("col", base);
850
- expect5(first.nextCursor).not.toBeNull();
1667
+ expect6(first.nextCursor).not.toBeNull();
851
1668
  const cursor = first.nextCursor;
852
- const other = await rejection2(
1669
+ const other = await rejection3(
853
1670
  store.query("col", { ...base, orderBy: { field: "v", direction: "desc" }, cursor })
854
1671
  );
855
- expect5(other).toBeInstanceOf(Error);
1672
+ expect6(other).toBeInstanceOf(Error);
856
1673
  const next = await store.query("col", { ...base, cursor });
857
- expect5(ids(next.items)).toEqual(["k2", "k3"]);
1674
+ expect6(ids(next.items)).toEqual(["k2", "k3"]);
858
1675
  });
859
1676
  },
860
1677
  CASE_MS
861
1678
  );
862
- it5(
1679
+ it6(
863
1680
  "a document put with a ttl (seconds) is gone from get, query and batchGet once it expires",
864
1681
  async () => {
865
1682
  await using2(make, async (store) => {
866
1683
  await store.put("col", "short", { id: "short", part: "p" }, { ttl: 1 });
867
1684
  await store.put("col", "kept", { id: "kept", part: "p" });
868
- expect5(await store.get("col", "short")).toEqual({ id: "short", part: "p" });
1685
+ expect6(await store.get("col", "short")).toEqual({ id: "short", part: "p" });
869
1686
  if (opts.clock !== void 0) {
870
1687
  await opts.clock.advance(1001);
871
1688
  } else {
@@ -874,15 +1691,15 @@ function runDocumentStoreContract(name, make, opts = {}) {
874
1691
  await new Promise((r) => setTimeout(r, 50));
875
1692
  }
876
1693
  }
877
- expect5(await store.get("col", "short")).toBeNull();
1694
+ expect6(await store.get("col", "short")).toBeNull();
878
1695
  const all = await store.query("col", { partitionKey: { field: "part", value: "*" } });
879
- expect5(ids(all.items)).toEqual(["kept"]);
880
- expect5([...(await store.batchGet("col", ["short", "kept"])).keys()]).toEqual(["kept"]);
1696
+ expect6(ids(all.items)).toEqual(["kept"]);
1697
+ expect6([...(await store.batchGet("col", ["short", "kept"])).keys()]).toEqual(["kept"]);
881
1698
  });
882
1699
  },
883
1700
  SLOW3
884
1701
  );
885
- it5(
1702
+ it6(
886
1703
  "a conditional put applies when the field is strictly equal, and otherwise fails condition-failed",
887
1704
  async () => {
888
1705
  await using2(make, async (store) => {
@@ -893,14 +1710,14 @@ function runDocumentStoreContract(name, make, opts = {}) {
893
1710
  { version: 2, label: "v2" },
894
1711
  { conditionKey: "version", conditionValue: 1 }
895
1712
  );
896
- expect5(await store.get("col", "c")).toEqual({ version: 2, label: "v2" });
1713
+ expect6(await store.get("col", "c")).toEqual({ version: 2, label: "v2" });
897
1714
  for (const conditionValue of [1, "2"]) {
898
- const failed = await rejection2(
1715
+ const failed = await rejection3(
899
1716
  store.put("col", "c", { version: 3 }, { conditionKey: "version", conditionValue })
900
1717
  );
901
- expect5(failed?.code).toBe("adapter.condition-failed");
1718
+ expect6(failed?.code).toBe("adapter.condition-failed");
902
1719
  }
903
- const absent = await rejection2(
1720
+ const absent = await rejection3(
904
1721
  store.put(
905
1722
  "col",
906
1723
  "none",
@@ -908,14 +1725,14 @@ function runDocumentStoreContract(name, make, opts = {}) {
908
1725
  { conditionKey: "version", conditionValue: 1 }
909
1726
  )
910
1727
  );
911
- expect5(absent?.code).toBe("adapter.condition-failed");
912
- expect5(await store.get("col", "c")).toEqual({ version: 2, label: "v2" });
913
- expect5(await store.get("col", "none")).toBeNull();
1728
+ expect6(absent?.code).toBe("adapter.condition-failed");
1729
+ expect6(await store.get("col", "c")).toEqual({ version: 2, label: "v2" });
1730
+ expect6(await store.get("col", "none")).toBeNull();
914
1731
  });
915
1732
  },
916
1733
  CASE_MS
917
1734
  );
918
- it5(
1735
+ it6(
919
1736
  "batchPut stores every item; batchGet returns exactly the stored keys",
920
1737
  async () => {
921
1738
  await using2(make, async (store) => {
@@ -927,32 +1744,32 @@ function runDocumentStoreContract(name, make, opts = {}) {
927
1744
  ])
928
1745
  );
929
1746
  const got = await store.batchGet("col", ["x", "y", "missing"]);
930
- expect5([...got.keys()].sort()).toEqual(["x", "y"]);
931
- expect5(got.get("x")).toEqual({ n: 10 });
932
- expect5(await store.get("col", "y")).toEqual({ n: 20 });
933
- expect5((await store.batchGet("col", [])).size).toBe(0);
1747
+ expect6([...got.keys()].sort()).toEqual(["x", "y"]);
1748
+ expect6(got.get("x")).toEqual({ n: 10 });
1749
+ expect6(await store.get("col", "y")).toEqual({ n: 20 });
1750
+ expect6((await store.batchGet("col", [])).size).toBe(0);
934
1751
  });
935
1752
  },
936
1753
  CASE_MS
937
1754
  );
938
- it5(
1755
+ it6(
939
1756
  "collections are isolated for get, query and delete",
940
1757
  async () => {
941
1758
  await using2(make, async (store) => {
942
1759
  await store.put("colA", "key", { id: "key", part: "p", from: "A" });
943
1760
  await store.put("colB", "key", { id: "key", part: "p", from: "B" });
944
- expect5(await store.get("colA", "key")).toEqual({ id: "key", part: "p", from: "A" });
1761
+ expect6(await store.get("colA", "key")).toEqual({ id: "key", part: "p", from: "A" });
945
1762
  const inB = await store.query("colB", { partitionKey: { field: "part", value: "*" } });
946
- expect5(inB.items).toEqual([{ id: "key", part: "p", from: "B" }]);
1763
+ expect6(inB.items).toEqual([{ id: "key", part: "p", from: "B" }]);
947
1764
  await store.delete("colA", "key");
948
- expect5(await store.get("colB", "key")).toEqual({ id: "key", part: "p", from: "B" });
1765
+ expect6(await store.get("colB", "key")).toEqual({ id: "key", part: "p", from: "B" });
949
1766
  });
950
1767
  },
951
1768
  CASE_MS
952
1769
  );
953
1770
  const isolation = opts.isolation;
954
1771
  if (isolation !== void 0) {
955
- it5(
1772
+ it6(
956
1773
  "two stores under different prefixes never see each other\u2019s documents",
957
1774
  async () => {
958
1775
  const [one, two] = await isolation();
@@ -960,16 +1777,16 @@ function runDocumentStoreContract(name, make, opts = {}) {
960
1777
  await one.put("col", "shared", { id: "shared", part: "p", owner: "one" });
961
1778
  await one.put("col", "one-only", { id: "one-only", part: "p", owner: "one" });
962
1779
  await two.put("col", "shared", { id: "shared", part: "p", owner: "two" });
963
- expect5(await one.get("col", "shared")).toEqual({
1780
+ expect6(await one.get("col", "shared")).toEqual({
964
1781
  id: "shared",
965
1782
  part: "p",
966
1783
  owner: "one"
967
1784
  });
968
- expect5(await two.get("col", "one-only")).toBeNull();
1785
+ expect6(await two.get("col", "one-only")).toBeNull();
969
1786
  const inTwo = await two.query("col", { partitionKey: { field: "part", value: "*" } });
970
- expect5(inTwo.items).toEqual([{ id: "shared", part: "p", owner: "two" }]);
1787
+ expect6(inTwo.items).toEqual([{ id: "shared", part: "p", owner: "two" }]);
971
1788
  await one.delete("col", "shared");
972
- expect5(await two.get("col", "shared")).toEqual({
1789
+ expect6(await two.get("col", "shared")).toEqual({
973
1790
  id: "shared",
974
1791
  part: "p",
975
1792
  owner: "two"
@@ -989,28 +1806,28 @@ function runDocumentStoreContract(name, make, opts = {}) {
989
1806
  }
990
1807
 
991
1808
  // src/email.ts
992
- import { describe as describe5, expect as expect6, it as it6 } from "vitest";
1809
+ import { describe as describe6, expect as expect7, it as it7 } from "vitest";
993
1810
  var MAIL = {
994
1811
  template: "order-confirmation",
995
1812
  to: "test@example.com",
996
1813
  vars: { orderNumber: "ORD-001" }
997
1814
  };
998
1815
  function runEmailContract(name, build, options = {}) {
999
- describe5(`EmailAdapter contract: ${name}`, () => {
1000
- it6(
1816
+ describe6(`EmailAdapter contract: ${name}`, () => {
1817
+ it7(
1001
1818
  "sendTransactional resolves with accepted or messageId",
1002
1819
  async () => {
1003
1820
  const adapter = await build();
1004
1821
  const result = await adapter.sendTransactional(MAIL);
1005
- expect6(typeof result.accepted).toBe("boolean");
1822
+ expect7(typeof result.accepted).toBe("boolean");
1006
1823
  },
1007
1824
  CASE_MS
1008
1825
  );
1009
- it6(
1826
+ it7(
1010
1827
  "syncCustomerToList resolves without throwing",
1011
1828
  async () => {
1012
1829
  const adapter = await build();
1013
- await expect6(
1830
+ await expect7(
1014
1831
  adapter.syncCustomerToList({
1015
1832
  customerId: "cust-1",
1016
1833
  orderCount: 0,
@@ -1022,11 +1839,11 @@ function runEmailContract(name, build, options = {}) {
1022
1839
  },
1023
1840
  CASE_MS
1024
1841
  );
1025
- it6(
1842
+ it7(
1026
1843
  "removeCustomerFromList resolves without throwing",
1027
1844
  async () => {
1028
1845
  const adapter = await build();
1029
- await expect6(adapter.removeCustomerFromList("cust-1")).resolves.not.toThrow();
1846
+ await expect7(adapter.removeCustomerFromList("cust-1")).resolves.not.toThrow();
1030
1847
  },
1031
1848
  CASE_MS
1032
1849
  );
@@ -1041,12 +1858,12 @@ function runEmailContract(name, build, options = {}) {
1041
1858
 
1042
1859
  // src/event-bus.ts
1043
1860
  import { randomUUID as randomUUID3 } from "crypto";
1044
- import { describe as describe8, expect as expect9, it as it9 } from "vitest";
1861
+ import { describe as describe9, expect as expect10, it as it10 } from "vitest";
1045
1862
 
1046
1863
  // src/event-bus-delivery.ts
1047
1864
  import { randomUUID } from "crypto";
1048
- import fc3 from "fast-check";
1049
- import { describe as describe6, expect as expect7, it as it7 } from "vitest";
1865
+ import fc4 from "fast-check";
1866
+ import { describe as describe7, expect as expect8, it as it8 } from "vitest";
1050
1867
  var SLOW4 = 6e4;
1051
1868
  function event(type, payload = {}) {
1052
1869
  return {
@@ -1060,7 +1877,7 @@ function event(type, payload = {}) {
1060
1877
  };
1061
1878
  }
1062
1879
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
1063
- async function until(check, label, ms) {
1880
+ async function until2(check, label, ms) {
1064
1881
  const deadline = Date.now() + ms;
1065
1882
  while (!check()) {
1066
1883
  if (Date.now() > deadline) throw new Error(`timed out after ${ms} ms waiting for ${label}`);
@@ -1083,8 +1900,8 @@ async function closingAll(buses, body) {
1083
1900
  }
1084
1901
  var TYPES = ["order.created.v1", "order.paid.v1", "cart.updated.v1"];
1085
1902
  function eventBusDeliveryCases(make, opts) {
1086
- describe6("keeps the delivery contract", () => {
1087
- it7(
1903
+ describe7("keeps the delivery contract", () => {
1904
+ it8(
1088
1905
  "publish resolves only after every matching handler has finished: a 200 ms handler, named and unnamed, is done first",
1089
1906
  async () => {
1090
1907
  const bus = await make();
@@ -1105,13 +1922,13 @@ function eventBusDeliveryCases(make, opts) {
1105
1922
  const startedAt = Date.now();
1106
1923
  await bus.publish(event("contract.slow.v1"));
1107
1924
  const elapsed = Date.now() - startedAt;
1108
- expect7([...finished].sort()).toEqual(["named", "unnamed"]);
1109
- expect7(elapsed).toBeGreaterThanOrEqual(190);
1925
+ expect8([...finished].sort()).toEqual(["named", "unnamed"]);
1926
+ expect8(elapsed).toBeGreaterThanOrEqual(190);
1110
1927
  });
1111
1928
  },
1112
1929
  SLOW4
1113
1930
  );
1114
- it7(
1931
+ it8(
1115
1932
  "a throwing named handler rejects publish with handler_failed naming it, and every other matching handler is called, event after event",
1116
1933
  async () => {
1117
1934
  const bus = await make();
@@ -1133,17 +1950,17 @@ function eventBusDeliveryCases(make, opts) {
1133
1950
  event("contract.boom.v1")
1134
1951
  ];
1135
1952
  for (const e of events) {
1136
- await expect7(bus.publish(e)).rejects.toMatchObject({
1953
+ await expect8(bus.publish(e)).rejects.toMatchObject({
1137
1954
  code: "adapter.handler_failed",
1138
1955
  context: { eventId: e.id, failed: [{ subscription: "contract-throws" }] }
1139
1956
  });
1140
1957
  }
1141
- expect7(received).toEqual(events.map((e) => e.id));
1958
+ expect8(received).toEqual(events.map((e) => e.id));
1142
1959
  });
1143
1960
  },
1144
1961
  SLOW4
1145
1962
  );
1146
- it7(
1963
+ it8(
1147
1964
  "replay reaches derived subscriptions only, in order; a later publish still reaches every subscription",
1148
1965
  async () => {
1149
1966
  const bus = await make();
@@ -1161,24 +1978,24 @@ function eventBusDeliveryCases(make, opts) {
1161
1978
  await bus.subscribe("contract.replay.v1", async (e) => void sideUnnamed.push(e.id));
1162
1979
  const replayed = [event("contract.replay.v1"), event("contract.replay.v1")];
1163
1980
  await bus.replay(replayed);
1164
- expect7(derived).toEqual(replayed.map((e) => e.id));
1165
- expect7(sideNamed).toEqual([]);
1166
- expect7(sideUnnamed).toEqual([]);
1981
+ expect8(derived).toEqual(replayed.map((e) => e.id));
1982
+ expect8(sideNamed).toEqual([]);
1983
+ expect8(sideUnnamed).toEqual([]);
1167
1984
  const live = event("contract.replay.v1");
1168
1985
  await bus.publish(live);
1169
- expect7(derived).toEqual([...replayed, live].map((e) => e.id));
1170
- expect7(sideNamed).toEqual([live.id]);
1171
- expect7(sideUnnamed).toEqual([live.id]);
1986
+ expect8(derived).toEqual([...replayed, live].map((e) => e.id));
1987
+ expect8(sideNamed).toEqual([live.id]);
1988
+ expect8(sideUnnamed).toEqual([live.id]);
1172
1989
  });
1173
1990
  },
1174
1991
  SLOW4
1175
1992
  );
1176
- it7(
1993
+ it8(
1177
1994
  "publishBatch reaches each subscription with exactly its matching events, in batch order (wildcards and pattern arrays)",
1178
1995
  async () => {
1179
- await fc3.assert(
1180
- fc3.asyncProperty(
1181
- fc3.array(fc3.constantFrom(...TYPES), { minLength: 1, maxLength: 12 }),
1996
+ await fc4.assert(
1997
+ fc4.asyncProperty(
1998
+ fc4.array(fc4.constantFrom(...TYPES), { minLength: 1, maxLength: 12 }),
1182
1999
  async (types) => {
1183
2000
  const bus = await make();
1184
2001
  await closingAll([bus], async () => {
@@ -1207,7 +2024,7 @@ function eventBusDeliveryCases(make, opts) {
1207
2024
  );
1208
2025
  for (const [i, sub] of subs.entries()) {
1209
2026
  const expected = events.filter((e) => matches(sub.patterns, e.type));
1210
- expect7(seen[i], sub.patterns.join("|")).toEqual([
2027
+ expect8(seen[i], sub.patterns.join("|")).toEqual([
1211
2028
  ...expected.map((e) => e.id),
1212
2029
  fence.id
1213
2030
  ]);
@@ -1220,7 +2037,7 @@ function eventBusDeliveryCases(make, opts) {
1220
2037
  },
1221
2038
  SLOW4
1222
2039
  );
1223
- it7(
2040
+ it8(
1224
2041
  "an unsubscribed handler, by bus.unsubscribe or by its own unsubscribe(), receives nothing more",
1225
2042
  async () => {
1226
2043
  const bus = await make();
@@ -1239,14 +2056,14 @@ function eventBusDeliveryCases(make, opts) {
1239
2056
  await b.unsubscribe();
1240
2057
  const after = [event("contract.unsub.v1"), event("contract.unsub.v1")];
1241
2058
  for (const e of after) await bus.publish(e);
1242
- expect7(kept).toEqual([before, ...after].map((e) => e.id));
1243
- expect7(gone).toEqual([before.id]);
1244
- expect7(goneToo).toEqual([before.id]);
2059
+ expect8(kept).toEqual([before, ...after].map((e) => e.id));
2060
+ expect8(gone).toEqual([before.id]);
2061
+ expect8(goneToo).toEqual([before.id]);
1245
2062
  });
1246
2063
  },
1247
2064
  SLOW4
1248
2065
  );
1249
- it7(
2066
+ it8(
1250
2067
  "on one instance, a named and an unnamed subscription each handle every event once",
1251
2068
  async () => {
1252
2069
  const bus = await make();
@@ -1259,17 +2076,17 @@ function eventBusDeliveryCases(make, opts) {
1259
2076
  await bus.subscribe("contract.both.v1", async (e) => void unnamed.push(e.id));
1260
2077
  const events = Array.from({ length: 6 }, () => event("contract.both.v1"));
1261
2078
  for (const e of events) await bus.publish(e);
1262
- expect7(named).toEqual(events.map((e) => e.id));
1263
- expect7(unnamed).toEqual(named);
2079
+ expect8(named).toEqual(events.map((e) => e.id));
2080
+ expect8(unnamed).toEqual(named);
1264
2081
  });
1265
2082
  },
1266
2083
  SLOW4
1267
2084
  );
1268
2085
  const second = opts.second;
1269
2086
  if (second === void 0) return;
1270
- describe6("two instances on the same streams", () => {
2087
+ describe7("two instances on the same streams", () => {
1271
2088
  const N = 12;
1272
- it7(
2089
+ it8(
1273
2090
  "one named subscription on both instances handles each of N events exactly once in total",
1274
2091
  async () => {
1275
2092
  const a = await make();
@@ -1289,13 +2106,13 @@ function eventBusDeliveryCases(make, opts) {
1289
2106
  await a.publish(event("contract.named.fence"));
1290
2107
  const ids2 = new Set(events.map((e) => e.id));
1291
2108
  const handled = [...byA, ...byB].filter((id) => ids2.has(id));
1292
- expect7(handled.length).toBe(events.length);
1293
- expect7([...handled].sort()).toEqual(events.map((e) => e.id).sort());
2109
+ expect8(handled.length).toBe(events.length);
2110
+ expect8([...handled].sort()).toEqual(events.map((e) => e.id).sort());
1294
2111
  });
1295
2112
  },
1296
2113
  SLOW4
1297
2114
  );
1298
- it7(
2115
+ it8(
1299
2116
  "an unnamed subscription on each instance receives all N events, in order, on both",
1300
2117
  async () => {
1301
2118
  const a = await make();
@@ -1313,14 +2130,14 @@ function eventBusDeliveryCases(make, opts) {
1313
2130
  const fenceB = event("contract.fanout.fence");
1314
2131
  await b.publish(fenceB);
1315
2132
  const ids2 = events.map((e) => e.id);
1316
- expect7(onA.slice(0, N)).toEqual(ids2);
1317
- expect7(onB.slice(0, N)).toEqual(ids2);
1318
- expect7(onB[N]).toBe(fenceB.id);
2133
+ expect8(onA.slice(0, N)).toEqual(ids2);
2134
+ expect8(onB.slice(0, N)).toEqual(ids2);
2135
+ expect8(onB[N]).toBe(fenceB.id);
1319
2136
  });
1320
2137
  },
1321
2138
  SLOW4
1322
2139
  );
1323
- it7(
2140
+ it8(
1324
2141
  "replay on one instance reaches its own derived handlers and nothing on the other instance",
1325
2142
  async () => {
1326
2143
  const a = await make();
@@ -1344,10 +2161,10 @@ function eventBusDeliveryCases(make, opts) {
1344
2161
  await a.replay(replayed);
1345
2162
  const fence = event("contract.rebuild.fence");
1346
2163
  await b.publish(fence);
1347
- expect7(derivedA.slice(0, replayed.length)).toEqual(replayed.map((e) => e.id));
2164
+ expect8(derivedA.slice(0, replayed.length)).toEqual(replayed.map((e) => e.id));
1348
2165
  const ids2 = new Set(replayed.map((e) => e.id));
1349
- expect7(derivedB.filter((id) => ids2.has(id))).toEqual([]);
1350
- expect7(sideB).toEqual([fence.id]);
2166
+ expect8(derivedB.filter((id) => ids2.has(id))).toEqual([]);
2167
+ expect8(sideB).toEqual([fence.id]);
1351
2168
  });
1352
2169
  },
1353
2170
  SLOW4
@@ -1355,7 +2172,7 @@ function eventBusDeliveryCases(make, opts) {
1355
2172
  const timing = opts.timing;
1356
2173
  if (timing === void 0) return;
1357
2174
  const { claimIdleMs, ackTimeoutMs } = timing;
1358
- it7(
2175
+ it8(
1359
2176
  "groups left by a stopped instance (never unsubscribed) do not delay publish on the other instance",
1360
2177
  async () => {
1361
2178
  const a = await make();
@@ -1374,13 +2191,13 @@ function eventBusDeliveryCases(make, opts) {
1374
2191
  const startedAt = Date.now();
1375
2192
  await a.publish(e);
1376
2193
  const elapsed = Date.now() - startedAt;
1377
- expect7(handled).toEqual([e.id]);
1378
- expect7(elapsed).toBeLessThan(ackTimeoutMs / 2);
2194
+ expect8(handled).toEqual([e.id]);
2195
+ expect8(elapsed).toBeLessThan(ackTimeoutMs / 2);
1379
2196
  });
1380
2197
  },
1381
2198
  SLOW4
1382
2199
  );
1383
- it7(
2200
+ it8(
1384
2201
  "an entry pending on a stopped consumer of a named group is handled by the live one after claimIdleMs and before ackTimeoutMs",
1385
2202
  async () => {
1386
2203
  const a = await make();
@@ -1399,7 +2216,7 @@ function eventBusDeliveryCases(make, opts) {
1399
2216
  );
1400
2217
  const stranded = event("contract.claim.x");
1401
2218
  await a.publish(stranded);
1402
- await until(() => receivedByB !== void 0, "b to receive the entry", ackTimeoutMs);
2219
+ await until2(() => receivedByB !== void 0, "b to receive the entry", ackTimeoutMs);
1403
2220
  closingB = b.close();
1404
2221
  const byA = [];
1405
2222
  await a.subscribe(
@@ -1413,17 +2230,17 @@ function eventBusDeliveryCases(make, opts) {
1413
2230
  const startedAt = Date.now();
1414
2231
  await a.publish(next);
1415
2232
  const publishMs = Date.now() - startedAt;
1416
- await until(
2233
+ await until2(
1417
2234
  () => byA.some((h) => h.id === stranded.id),
1418
2235
  "a to take over the stranded entry",
1419
2236
  ackTimeoutMs * 2
1420
2237
  );
1421
2238
  const claimed = byA.find((h) => h.id === stranded.id);
1422
2239
  const idle = claimed.at - receivedByB;
1423
- expect7(idle, "taken over before claimIdleMs").toBeGreaterThanOrEqual(claimIdleMs - 50);
1424
- expect7(idle, "taken over only after ackTimeoutMs").toBeLessThan(ackTimeoutMs);
1425
- expect7(byA.filter((h) => h.id === stranded.id).length).toBe(1);
1426
- expect7(publishMs, "a publish on the group waited out the timeout").toBeLessThan(
2240
+ expect8(idle, "taken over before claimIdleMs").toBeGreaterThanOrEqual(claimIdleMs - 50);
2241
+ expect8(idle, "taken over only after ackTimeoutMs").toBeLessThan(ackTimeoutMs);
2242
+ expect8(byA.filter((h) => h.id === stranded.id).length).toBe(1);
2243
+ expect8(publishMs, "a publish on the group waited out the timeout").toBeLessThan(
1427
2244
  ackTimeoutMs
1428
2245
  );
1429
2246
  } finally {
@@ -1434,7 +2251,7 @@ function eventBusDeliveryCases(make, opts) {
1434
2251
  },
1435
2252
  SLOW4
1436
2253
  );
1437
- it7(
2254
+ it8(
1438
2255
  "an unnamed subscription unsubscribed while publish waits on it lets publish resolve well before ackTimeoutMs",
1439
2256
  async () => {
1440
2257
  const a = await make();
@@ -1449,12 +2266,12 @@ function eventBusDeliveryCases(make, opts) {
1449
2266
  () => Date.now(),
1450
2267
  (error) => error
1451
2268
  );
1452
- await until(() => entered, "the handler to start", ackTimeoutMs);
2269
+ await until2(() => entered, "the handler to start", ackTimeoutMs);
1453
2270
  const unsubscribedAt = Date.now();
1454
2271
  const unsubscribing = a.unsubscribe(sub);
1455
2272
  const outcome = await publishing;
1456
- expect7(typeof outcome, `publish rejected: ${String(outcome)}`).toBe("number");
1457
- expect7(outcome - unsubscribedAt).toBeLessThan(ackTimeoutMs / 2);
2273
+ expect8(typeof outcome, `publish rejected: ${String(outcome)}`).toBe("number");
2274
+ expect8(outcome - unsubscribedAt).toBeLessThan(ackTimeoutMs / 2);
1458
2275
  held.open();
1459
2276
  await unsubscribing;
1460
2277
  } finally {
@@ -1470,7 +2287,7 @@ function eventBusDeliveryCases(make, opts) {
1470
2287
 
1471
2288
  // src/event-bus-failure.ts
1472
2289
  import { randomUUID as randomUUID2 } from "crypto";
1473
- import { describe as describe7, expect as expect8, it as it8 } from "vitest";
2290
+ import { describe as describe8, expect as expect9, it as it9 } from "vitest";
1474
2291
  var SLOW5 = 6e4;
1475
2292
  var SLOW_HANDLER_MS = 200;
1476
2293
  var IN_PROCESS_WINDOW_MS = 200;
@@ -1486,7 +2303,7 @@ function event2(type, payload = {}) {
1486
2303
  };
1487
2304
  }
1488
2305
  var delay2 = (ms) => new Promise((r) => setTimeout(r, ms));
1489
- async function until2(check, label, ms) {
2306
+ async function until3(check, label, ms) {
1490
2307
  const deadline = Date.now() + ms;
1491
2308
  while (!check()) {
1492
2309
  if (Date.now() > deadline) throw new Error(`timed out after ${ms} ms waiting for ${label}`);
@@ -1517,7 +2334,7 @@ async function settled(promise) {
1517
2334
  }
1518
2335
  }
1519
2336
  function failure(outcome) {
1520
- expect8(outcome.state, "publish resolved, so the failure was swallowed").toBe("rejected");
2337
+ expect9(outcome.state, "publish resolved, so the failure was swallowed").toBe("rejected");
1521
2338
  const e = outcome.error;
1522
2339
  return {
1523
2340
  name: String(e.name),
@@ -1529,15 +2346,15 @@ function failure(outcome) {
1529
2346
  var failedNames = (f) => (f.context.failed ?? []).map((x) => x.subscription);
1530
2347
  function eventBusFailureCases(make, opts) {
1531
2348
  const window = opts.timing === void 0 ? IN_PROCESS_WINDOW_MS : 3 * opts.timing.claimIdleMs;
1532
- describe7("reports handler failures", () => {
1533
- it8(
2349
+ describe8("reports handler failures", () => {
2350
+ it9(
1534
2351
  "a named handler that throws rejects publish with handler_failed naming it alone, only after the other named handlers (one of them slow) have each run once and finished; a throwing unnamed handler is named nowhere; replay past a throwing derived handler resolves",
1535
2352
  async () => {
1536
2353
  const bus = await make();
1537
2354
  await closing2([bus], async () => {
1538
2355
  const type = "contract.failure.v1";
1539
2356
  const ran = { a: 0, b: 0, c: 0 };
1540
- const finished = { b: void 0, c: void 0 };
2357
+ const marks = [];
1541
2358
  await bus.subscribe(
1542
2359
  type,
1543
2360
  async () => {
@@ -1551,7 +2368,7 @@ function eventBusFailureCases(make, opts) {
1551
2368
  async () => {
1552
2369
  ran.b += 1;
1553
2370
  await delay2(SLOW_HANDLER_MS);
1554
- finished.b = Date.now();
2371
+ marks.push("b finished");
1555
2372
  },
1556
2373
  { name: "contract-failure-b" }
1557
2374
  );
@@ -1559,7 +2376,7 @@ function eventBusFailureCases(make, opts) {
1559
2376
  type,
1560
2377
  async () => {
1561
2378
  ran.c += 1;
1562
- finished.c = Date.now();
2379
+ marks.push("c finished");
1563
2380
  },
1564
2381
  { name: "contract-failure-c" }
1565
2382
  );
@@ -1567,13 +2384,13 @@ function eventBusFailureCases(make, opts) {
1567
2384
  throw new Error("contract admin tab refused");
1568
2385
  });
1569
2386
  const e = event2(type);
1570
- const outcome = await settled(bus.publish(e));
1571
- expect8(ran).toEqual({ a: 1, b: 1, c: 1 });
1572
- expect8(finished.b, "the slow handler finished before the rejection").toBeLessThanOrEqual(
1573
- outcome.at
1574
- );
1575
- expect8(finished.c).toBeLessThanOrEqual(outcome.at);
1576
- expect8(outcome.ms).toBeGreaterThanOrEqual(SLOW_HANDLER_MS - 10);
2387
+ const outcome = await settled(bus.publish(e).finally(() => marks.push("publish settled")));
2388
+ expect9(ran).toEqual({ a: 1, b: 1, c: 1 });
2389
+ expect9(
2390
+ [...marks.slice(0, 2)].sort(),
2391
+ "the other named handlers finished before the publish settled"
2392
+ ).toEqual(["b finished", "c finished"]);
2393
+ expect9(marks.slice(2)).toEqual(["publish settled"]);
1577
2394
  const rebuilt = [];
1578
2395
  await bus.subscribe(
1579
2396
  "contract.failure-replay.v1",
@@ -1591,18 +2408,18 @@ function eventBusFailureCases(make, opts) {
1591
2408
  event2("contract.failure-replay.v1")
1592
2409
  ];
1593
2410
  const replay = await settled(bus.replay(replayed));
1594
- expect8(replay.state).toBe("resolved");
1595
- expect8(rebuilt).toEqual(replayed.map((r) => r.id));
2411
+ expect9(replay.state).toBe("resolved");
2412
+ expect9(rebuilt).toEqual(replayed.map((r) => r.id));
1596
2413
  const f = failure(outcome);
1597
- expect8([f.name, f.code]).toEqual(["AdapterError", "adapter.handler_failed"]);
1598
- expect8([f.context.eventId, f.context.eventType]).toEqual([e.id, e.type]);
1599
- expect8(failedNames(f)).toEqual(["contract-failure-a"]);
1600
- expect8(f.context.failed?.[0]?.message).toContain("contract handler A refused");
2414
+ expect9([f.name, f.code]).toEqual(["AdapterError", "adapter.handler_failed"]);
2415
+ expect9([f.context.eventId, f.context.eventType]).toEqual([e.id, e.type]);
2416
+ expect9(failedNames(f)).toEqual(["contract-failure-a"]);
2417
+ expect9(f.context.failed?.[0]?.message).toContain("contract handler A refused");
1601
2418
  });
1602
2419
  },
1603
2420
  SLOW5
1604
2421
  );
1605
- it8(
2422
+ it9(
1606
2423
  "publishBatch of three events whose second fails a named handler hands all three, in order, to every subscription and only then rejects with handler_failed naming that event and subscription",
1607
2424
  async () => {
1608
2425
  const bus = await make();
@@ -1641,11 +2458,11 @@ function eventBusFailureCases(make, opts) {
1641
2458
  })
1642
2459
  );
1643
2460
  const f = failure(outcome);
1644
- expect8(f.code).toBe("adapter.handler_failed");
1645
- expect8(f.context.eventId).toBe(events[1].id);
1646
- expect8(failedNames(f)).toEqual(["contract-failure-picky"]);
2461
+ expect9(f.code).toBe("adapter.handler_failed");
2462
+ expect9(f.context.eventId).toBe(events[1].id);
2463
+ expect9(failedNames(f)).toEqual(["contract-failure-picky"]);
1647
2464
  const ids2 = events.map((e) => e.id);
1648
- expect8(
2465
+ expect9(
1649
2466
  seenAtRejection,
1650
2467
  "what each subscription had been handed when the batch rejected"
1651
2468
  ).toEqual([ids2, ids2, ids2]);
@@ -1653,7 +2470,7 @@ function eventBusFailureCases(make, opts) {
1653
2470
  },
1654
2471
  SLOW5
1655
2472
  );
1656
- it8(
2473
+ it9(
1657
2474
  "publishing a rejected event again reaches every subscription again and resolves once the failed handler passes; in the window after the rejection the bus ran the failed handler only once per publish",
1658
2475
  async () => {
1659
2476
  const bus = await make();
@@ -1673,17 +2490,17 @@ function eventBusFailureCases(make, opts) {
1673
2490
  await bus.subscribe(type, async () => void (ran.unnamed += 1));
1674
2491
  const e = event2(type);
1675
2492
  const first = await settled(bus.publish(e));
1676
- expect8(failure(first).code).toBe("adapter.handler_failed");
2493
+ expect9(failure(first).code).toBe("adapter.handler_failed");
1677
2494
  await delay2(window);
1678
2495
  const afterWindow = { ...ran };
1679
- expect8(afterWindow.a, "the failed handler ran again without a publish").toBe(1);
2496
+ expect9(afterWindow.a, "the failed handler ran again without a publish").toBe(1);
1680
2497
  const second2 = await settled(bus.publish(e));
1681
- expect8(second2.state, String(second2.error)).toBe("resolved");
1682
- expect8(ran.a).toBe(2);
1683
- expect8(ran.b).toBe(2);
1684
- expect8(ran.c).toBe(ran.b);
1685
- expect8(ran.unnamed).toBe(ran.b);
1686
- expect8(ran.b - afterWindow.b, "the second publish reached B again").toBe(1);
2498
+ expect9(second2.state, String(second2.error)).toBe("resolved");
2499
+ expect9(ran.a).toBe(2);
2500
+ expect9(ran.b).toBe(2);
2501
+ expect9(ran.c).toBe(ran.b);
2502
+ expect9(ran.unnamed).toBe(ran.b);
2503
+ expect9(ran.b - afterWindow.b, "the second publish reached B again").toBe(1);
1687
2504
  });
1688
2505
  },
1689
2506
  SLOW5
@@ -1691,7 +2508,7 @@ function eventBusFailureCases(make, opts) {
1691
2508
  const second = opts.second;
1692
2509
  const timing = opts.timing;
1693
2510
  if (second === void 0 || timing === void 0) return;
1694
- it8(
2511
+ it9(
1695
2512
  "a named handler that throws on another instance fails the publish on this one with handler_failed, not publish_timeout, well within ackTimeoutMs",
1696
2513
  async () => {
1697
2514
  const a = await make();
@@ -1717,7 +2534,7 @@ function eventBusFailureCases(make, opts) {
1717
2534
  { name: group }
1718
2535
  );
1719
2536
  holding = settled(a.publish(event2(hold)));
1720
- await until2(() => aHolding, "a to take the holding entry", timing.ackTimeoutMs);
2537
+ await until3(() => aHolding, "a to take the holding entry", timing.ackTimeoutMs);
1721
2538
  await b.subscribe(
1722
2539
  "contract.remote.*",
1723
2540
  async (e2) => {
@@ -1729,11 +2546,11 @@ function eventBusFailureCases(make, opts) {
1729
2546
  );
1730
2547
  const e = event2(target);
1731
2548
  const outcome = await settled(a.publish(e));
1732
- expect8(ranOn[e.id], "the failing handler ran on the second instance only").toEqual(["b"]);
2549
+ expect9(ranOn[e.id], "the failing handler ran on the second instance only").toEqual(["b"]);
1733
2550
  const f = failure(outcome);
1734
- expect8(f.code, f.message).toBe("adapter.handler_failed");
1735
- expect8(failedNames(f)).toEqual([group]);
1736
- expect8(outcome.ms).toBeLessThan(timing.ackTimeoutMs / 2);
2551
+ expect9(f.code, f.message).toBe("adapter.handler_failed");
2552
+ expect9(failedNames(f)).toEqual([group]);
2553
+ expect9(outcome.ms).toBeLessThan(timing.ackTimeoutMs / 2);
1737
2554
  } finally {
1738
2555
  held.open();
1739
2556
  await holding;
@@ -1743,7 +2560,7 @@ function eventBusFailureCases(make, opts) {
1743
2560
  },
1744
2561
  SLOW5
1745
2562
  );
1746
- it8(
2563
+ it9(
1747
2564
  "a named handler that fails once on another instance, then passes on the second publish within ackTimeoutMs: the first publish rejects and the second resolves, and the handler ran twice",
1748
2565
  async () => {
1749
2566
  const a = await make();
@@ -1769,7 +2586,7 @@ function eventBusFailureCases(make, opts) {
1769
2586
  { name: group }
1770
2587
  );
1771
2588
  holding = settled(a.publish(event2(hold)));
1772
- await until2(() => aHolding, "a to take the holding entry", timing.ackTimeoutMs);
2589
+ await until3(() => aHolding, "a to take the holding entry", timing.ackTimeoutMs);
1773
2590
  let runs = 0;
1774
2591
  await b.subscribe(
1775
2592
  "contract.remote-once.*",
@@ -1784,13 +2601,13 @@ function eventBusFailureCases(make, opts) {
1784
2601
  const e = event2(target);
1785
2602
  const first = await settled(a.publish(e));
1786
2603
  const again = await settled(a.publish(e));
1787
- expect8(ranOn[e.id], "the handler ran on the second instance, once per publish").toEqual([
2604
+ expect9(ranOn[e.id], "the handler ran on the second instance, once per publish").toEqual([
1788
2605
  "b",
1789
2606
  "b"
1790
2607
  ]);
1791
- expect8(failure(first).code).toBe("adapter.handler_failed");
1792
- expect8(again.at - first.at).toBeLessThan(timing.ackTimeoutMs);
1793
- expect8(again.state, String(again.error)).toBe("resolved");
2608
+ expect9(failure(first).code).toBe("adapter.handler_failed");
2609
+ expect9(again.at - first.at).toBeLessThan(timing.ackTimeoutMs);
2610
+ expect9(again.state, String(again.error)).toBe("resolved");
1794
2611
  } finally {
1795
2612
  held.open();
1796
2613
  await holding;
@@ -1825,8 +2642,8 @@ async function using3(buses, body) {
1825
2642
  }
1826
2643
  }
1827
2644
  function runEventBusContract(name, make, opts = {}) {
1828
- describe8(`EventBusAdapter contract: ${name}`, () => {
1829
- it9(
2645
+ describe9(`EventBusAdapter contract: ${name}`, () => {
2646
+ it10(
1830
2647
  "publish resolves after the matching handler has finished, and never calls a non-matching one",
1831
2648
  async () => {
1832
2649
  const bus = await make();
@@ -1839,13 +2656,13 @@ function runEventBusContract(name, make, opts = {}) {
1839
2656
  });
1840
2657
  await bus.subscribe("test.other.v1", async (e) => void other.push(e));
1841
2658
  await bus.publish(makeEvent("test.event.v1", { x: 1 }));
1842
- expect9(received).toEqual([{ x: 1 }]);
1843
- expect9(other).toEqual([]);
2659
+ expect10(received).toEqual([{ x: 1 }]);
2660
+ expect10(other).toEqual([]);
1844
2661
  });
1845
2662
  },
1846
2663
  CASE_MS
1847
2664
  );
1848
- it9(
2665
+ it10(
1849
2666
  "a handler that throws leaves publish resolved and every other handler called",
1850
2667
  async () => {
1851
2668
  const bus = await make();
@@ -1855,13 +2672,13 @@ function runEventBusContract(name, make, opts = {}) {
1855
2672
  throw new Error("boom");
1856
2673
  });
1857
2674
  await bus.subscribe("error.test.v1", async () => void results.push("ok"));
1858
- await expect9(bus.publish(makeEvent("error.test.v1"))).resolves.toBeUndefined();
1859
- expect9(results).toEqual(["ok"]);
2675
+ await expect10(bus.publish(makeEvent("error.test.v1"))).resolves.toBeUndefined();
2676
+ expect10(results).toEqual(["ok"]);
1860
2677
  });
1861
2678
  },
1862
2679
  CASE_MS
1863
2680
  );
1864
- it9(
2681
+ it10(
1865
2682
  "replay reaches derived subscriptions only",
1866
2683
  async () => {
1867
2684
  const bus = await make();
@@ -1877,13 +2694,13 @@ function runEventBusContract(name, make, opts = {}) {
1877
2694
  });
1878
2695
  const events = [makeEvent("replay.test.v1"), makeEvent("replay.test.v1")];
1879
2696
  await bus.replay(events);
1880
- expect9(derived).toEqual(events.map((e) => e.id));
1881
- expect9(sideEffect).toEqual([]);
2697
+ expect10(derived).toEqual(events.map((e) => e.id));
2698
+ expect10(sideEffect).toEqual([]);
1882
2699
  });
1883
2700
  },
1884
2701
  CASE_MS
1885
2702
  );
1886
- it9(
2703
+ it10(
1887
2704
  "publishBatch reaches each subscription in batch order, through wildcards and pattern arrays",
1888
2705
  async () => {
1889
2706
  const bus = await make();
@@ -1898,13 +2715,13 @@ function runEventBusContract(name, make, opts = {}) {
1898
2715
  (t, seq) => makeEvent(t, { seq })
1899
2716
  );
1900
2717
  await bus.publishBatch(events);
1901
- expect9(wildcard).toEqual(events.map((e) => e.id));
1902
- expect9(listed).toEqual(events.filter((e) => e.type !== "batch.b.v1").map((e) => e.id));
2718
+ expect10(wildcard).toEqual(events.map((e) => e.id));
2719
+ expect10(listed).toEqual(events.filter((e) => e.type !== "batch.b.v1").map((e) => e.id));
1903
2720
  });
1904
2721
  },
1905
2722
  CASE_MS
1906
2723
  );
1907
- it9(
2724
+ it10(
1908
2725
  "an unsubscribed handler receives nothing more",
1909
2726
  async () => {
1910
2727
  const bus = await make();
@@ -1915,12 +2732,12 @@ function runEventBusContract(name, make, opts = {}) {
1915
2732
  await bus.publish(before);
1916
2733
  await bus.unsubscribe(sub);
1917
2734
  await bus.publish(makeEvent("unsub.event.v1"));
1918
- expect9(received).toEqual([before.id]);
2735
+ expect10(received).toEqual([before.id]);
1919
2736
  });
1920
2737
  },
1921
2738
  CASE_MS
1922
2739
  );
1923
- it9(
2740
+ it10(
1924
2741
  "on one instance, a named and an unnamed subscription each handle every event once",
1925
2742
  async () => {
1926
2743
  const bus = await make();
@@ -1933,8 +2750,8 @@ function runEventBusContract(name, make, opts = {}) {
1933
2750
  await bus.subscribe("both.event.v1", async (e) => void unnamed.push(e.id));
1934
2751
  const events = [makeEvent("both.event.v1"), makeEvent("both.event.v1")];
1935
2752
  for (const e of events) await bus.publish(e);
1936
- expect9(named).toEqual(events.map((e) => e.id));
1937
- expect9(unnamed).toEqual(named);
2753
+ expect10(named).toEqual(events.map((e) => e.id));
2754
+ expect10(unnamed).toEqual(named);
1938
2755
  });
1939
2756
  },
1940
2757
  CASE_MS
@@ -1949,7 +2766,7 @@ function runEventBusContract(name, make, opts = {}) {
1949
2766
  );
1950
2767
  const second = opts.second;
1951
2768
  if (second === void 0) return;
1952
- it9(
2769
+ it10(
1953
2770
  "across two instances, a named subscription handles each event once in total, and an unnamed one on each",
1954
2771
  async () => {
1955
2772
  const a = await make();
@@ -1973,9 +2790,9 @@ function runEventBusContract(name, make, opts = {}) {
1973
2790
  await a.publish(fenceA);
1974
2791
  await b.publish(fenceB);
1975
2792
  const ids2 = events.map((e) => e.id);
1976
- expect9(named.filter((id) => ids2.includes(id)).sort()).toEqual([...ids2].sort());
1977
- expect9(onA.filter((id) => ids2.includes(id))).toEqual(ids2);
1978
- expect9(onB.filter((id) => ids2.includes(id))).toEqual(ids2);
2793
+ expect10(named.filter((id) => ids2.includes(id)).sort()).toEqual([...ids2].sort());
2794
+ expect10(onA.filter((id) => ids2.includes(id))).toEqual(ids2);
2795
+ expect10(onB.filter((id) => ids2.includes(id))).toEqual(ids2);
1979
2796
  });
1980
2797
  },
1981
2798
  SLOW6
@@ -1984,15 +2801,15 @@ function runEventBusContract(name, make, opts = {}) {
1984
2801
  }
1985
2802
 
1986
2803
  // src/media-storage.ts
1987
- import { describe as describe9, expect as expect10, it as it10 } from "vitest";
2804
+ import { describe as describe10, expect as expect11, it as it11 } from "vitest";
1988
2805
  function runMediaStorageContract(name, make, options) {
1989
2806
  const { fetchUrl } = options;
1990
- describe9(`MediaStorage contract: ${name}`, () => {
1991
- it10("reports put among its capabilities", async () => {
2807
+ describe10(`MediaStorage contract: ${name}`, () => {
2808
+ it11("reports put among its capabilities", async () => {
1992
2809
  const storage = await make();
1993
- expect10(storage.capabilities()).toContain("put");
2810
+ expect11(storage.capabilities()).toContain("put");
1994
2811
  }, CASE_MS);
1995
- it10("put then a read of the returned url gives back the same bytes, for nested keys too", async () => {
2812
+ it11("put then a read of the returned url gives back the same bytes, for nested keys too", async () => {
1996
2813
  const storage = await make();
1997
2814
  const bodies = /* @__PURE__ */ new Map([
1998
2815
  ["image.png", Uint8Array.from([137, 80, 78, 71, 0, 255, 1])],
@@ -2003,11 +2820,11 @@ function runMediaStorageContract(name, make, options) {
2003
2820
  for (const [key, body] of bodies) {
2004
2821
  const { url } = await storage.put(key, body, "application/octet-stream");
2005
2822
  urls.add(url);
2006
- expect10([...await fetchUrl(url)]).toEqual([...body]);
2823
+ expect11([...await fetchUrl(url)]).toEqual([...body]);
2007
2824
  }
2008
- expect10(urls.size).toBe(bodies.size);
2825
+ expect11(urls.size).toBe(bodies.size);
2009
2826
  }, CASE_MS);
2010
- it10("a second put under a key replaces what the url serves", async () => {
2827
+ it11("a second put under a key replaces what the url serves", async () => {
2011
2828
  const storage = await make();
2012
2829
  await storage.put("replaced.bin", Uint8Array.from([1, 2, 3]), "application/octet-stream");
2013
2830
  const { url } = await storage.put(
@@ -2015,7 +2832,7 @@ function runMediaStorageContract(name, make, options) {
2015
2832
  Uint8Array.from([9]),
2016
2833
  "application/octet-stream"
2017
2834
  );
2018
- expect10([...await fetchUrl(url)]).toEqual([9]);
2835
+ expect11([...await fetchUrl(url)]).toEqual([9]);
2019
2836
  }, CASE_MS);
2020
2837
  healthAndDowntime(
2021
2838
  make,
@@ -2028,7 +2845,7 @@ function runMediaStorageContract(name, make, options) {
2028
2845
 
2029
2846
  // src/payments.ts
2030
2847
  import { randomUUID as randomUUID4 } from "crypto";
2031
- import { describe as describe10, expect as expect11, it as it11 } from "vitest";
2848
+ import { describe as describe11, expect as expect12, it as it12 } from "vitest";
2032
2849
  var TOTAL = 1999;
2033
2850
  async function rejectionCode(call) {
2034
2851
  return call.then(
@@ -2037,8 +2854,8 @@ async function rejectionCode(call) {
2037
2854
  );
2038
2855
  }
2039
2856
  function runPaymentsContract(name, build, options = {}) {
2040
- describe10(`PaymentsAdapter contract: ${name}`, () => {
2041
- it11(
2857
+ describe11(`PaymentsAdapter contract: ${name}`, () => {
2858
+ it12(
2042
2859
  "createPaymentIntent returns a clientSecret and id",
2043
2860
  async () => {
2044
2861
  const adapter = await build();
@@ -2047,20 +2864,20 @@ function runPaymentsContract(name, build, options = {}) {
2047
2864
  currency: "GBP",
2048
2865
  orderRef: `contract-${randomUUID4()}`
2049
2866
  });
2050
- expect11(intent.id).toBeTruthy();
2051
- expect11(intent.clientSecret).toBeTruthy();
2052
- expect11(intent.amountMinor).toBe(1e3);
2053
- expect11(intent.currency).toBe("GBP");
2867
+ expect12(intent.id).toBeTruthy();
2868
+ expect12(intent.clientSecret).toBeTruthy();
2869
+ expect12(intent.amountMinor).toBe(1e3);
2870
+ expect12(intent.currency).toBe("GBP");
2054
2871
  },
2055
2872
  CASE_MS
2056
2873
  );
2057
- it11(
2874
+ it12(
2058
2875
  "getPaymentStatus returns a valid status",
2059
2876
  async () => {
2060
2877
  const adapter = await build();
2061
2878
  const intent = await adapter.createPaymentIntent({ amountMinor: 500, currency: "GBP" });
2062
2879
  const status = await adapter.getPaymentStatus(intent.id);
2063
- expect11([
2880
+ expect12([
2064
2881
  "requires_payment_method",
2065
2882
  "requires_confirmation",
2066
2883
  "requires_action",
@@ -2073,7 +2890,7 @@ function runPaymentsContract(name, build, options = {}) {
2073
2890
  },
2074
2891
  CASE_MS
2075
2892
  );
2076
- it11(
2893
+ it12(
2077
2894
  "idempotency: a refund repeated with the same idempotencyKey returns the same refund and refunds once",
2078
2895
  async () => {
2079
2896
  const adapter = await build();
@@ -2091,31 +2908,31 @@ function runPaymentsContract(name, build, options = {}) {
2091
2908
  const again = await adapter.refund(intent.id, half, "requested_by_customer", {
2092
2909
  idempotencyKey: key
2093
2910
  });
2094
- expect11(again.refundId, "the retry under the same key made another refund").toBe(
2911
+ expect12(again.refundId, "the retry under the same key made another refund").toBe(
2095
2912
  first.refundId
2096
2913
  );
2097
- expect11(again.amountMinor).toBe(first.amountMinor);
2914
+ expect12(again.amountMinor).toBe(first.amountMinor);
2098
2915
  const rest = await adapter.refund(intent.id, TOTAL - half, "requested_by_customer", {
2099
2916
  idempotencyKey: `${key}-rest`
2100
2917
  });
2101
- expect11(rest.amountMinor + first.amountMinor).toBe(TOTAL);
2918
+ expect12(rest.amountMinor + first.amountMinor).toBe(TOTAL);
2102
2919
  const over = await rejectionCode(
2103
2920
  adapter.refund(intent.id, 1, "requested_by_customer", { idempotencyKey: `${key}-over` })
2104
2921
  );
2105
- expect11(over, "a minor unit past the amount was refunded").toBe("payment.refund_rejected");
2922
+ expect12(over, "a minor unit past the amount was refunded").toBe("payment.refund_rejected");
2106
2923
  },
2107
2924
  CASE_MS
2108
2925
  );
2109
2926
  const signedWebhook = options.signedWebhook;
2110
2927
  if (signedWebhook !== void 0) {
2111
- it11(
2928
+ it12(
2112
2929
  "idempotency: parsing one signed webhook event twice gives equal results",
2113
2930
  async () => {
2114
2931
  const adapter = await build();
2115
2932
  const { rawBody, signature } = signedWebhook();
2116
2933
  const first = await adapter.parseWebhook(rawBody, signature);
2117
2934
  const second = await adapter.parseWebhook(rawBody, signature);
2118
- expect11(second).toEqual(first);
2935
+ expect12(second).toEqual(first);
2119
2936
  },
2120
2937
  CASE_MS
2121
2938
  );
@@ -2131,16 +2948,24 @@ function runPaymentsContract(name, build, options = {}) {
2131
2948
 
2132
2949
  // src/reviews.ts
2133
2950
  import { randomUUID as randomUUID5 } from "crypto";
2134
- import fc4 from "fast-check";
2135
- import { describe as describe11, expect as expect12, it as it12 } from "vitest";
2136
- async function seed(adapter, count) {
2951
+ import fc5 from "fast-check";
2952
+ import { describe as describe12, expect as expect13, it as it13 } from "vitest";
2953
+ var takesSubmissions = (adapter) => adapter.capabilities().includes("submit");
2954
+ async function seedWith(adapter, count, options) {
2137
2955
  const productId = `contract-reviews-${randomUUID5()}`;
2956
+ if (options.seed !== void 0) return options.seed(adapter, productId, count);
2957
+ if (!takesSubmissions(adapter)) {
2958
+ throw new Error(
2959
+ "runReviewsContract: an adapter without the submit capability needs the seed option to put reviews in its store"
2960
+ );
2961
+ }
2138
2962
  const seeded = [];
2139
2963
  for (let i = 0; i < count; i++) {
2140
2964
  const { review } = await adapter.submitReview({
2141
2965
  productId,
2142
2966
  customerId: null,
2143
2967
  orderId: null,
2968
+ author: null,
2144
2969
  rating: i % 5 + 1,
2145
2970
  title: `review ${i}`,
2146
2971
  body: `body ${i}`
@@ -2163,65 +2988,108 @@ async function walk3(adapter, first, limit, maxPages) {
2163
2988
  } while (cursor !== void 0 && pages.length < maxPages);
2164
2989
  return pages;
2165
2990
  }
2991
+ var arbSubmission = fc5.record({
2992
+ productId: fc5.uuid().map((id) => `contract-reviews-${id}`),
2993
+ customerId: fc5.option(
2994
+ fc5.uuid().map((id) => `contract-customer-${id}`),
2995
+ { nil: null }
2996
+ ),
2997
+ orderId: fc5.option(
2998
+ fc5.uuid().map((id) => `contract-order-${id}`),
2999
+ { nil: null }
3000
+ ),
3001
+ author: fc5.option(
3002
+ fc5.record({
3003
+ name: fc5.stringMatching(/^[A-Z][a-z]{1,10} [A-Z][a-z]{1,12}$/),
3004
+ email: fc5.stringMatching(/^[a-z]{3,10}@contract\.test$/)
3005
+ }),
3006
+ { nil: null }
3007
+ ),
3008
+ rating: fc5.integer({ min: 1, max: 5 }),
3009
+ title: fc5.stringMatching(/^[A-Z][a-z]{2,10}( [a-z]{2,8}){0,3}$/),
3010
+ body: fc5.stringMatching(/^[A-Z][a-z]{2,10}( [a-z]{2,8}){0,8}\.$/)
3011
+ });
2166
3012
  function runReviewsContract(name, build, options = {}) {
2167
- describe11(`ReviewsAdapter contract: ${name}`, () => {
2168
- it12(
2169
- "submitReview returns the created review",
3013
+ const seed = (adapter, count) => seedWith(adapter, count, options);
3014
+ describe12(`ReviewsAdapter contract: ${name}`, () => {
3015
+ it13(
3016
+ "submit: with submit among its capabilities, submitReview returns the review carrying the submission\u2019s productId, customerId, orderId, rating, title and body; without it, submitReview rejects with ReviewRefusedError reviews.submit_unsupported",
2170
3017
  async () => {
2171
3018
  const adapter = await build();
2172
- const productId = `contract-reviews-${randomUUID5()}`;
2173
- const { review } = await adapter.submitReview({
2174
- productId,
2175
- customerId: null,
2176
- orderId: null,
2177
- rating: 5,
2178
- title: "Great!",
2179
- body: "Really liked it."
2180
- });
2181
- expect12(review.productId).toBe(productId);
2182
- expect12(review.rating).toBe(5);
2183
- expect12(review.id).toBeTruthy();
3019
+ const takes = takesSubmissions(adapter);
3020
+ await fc5.assert(
3021
+ fc5.asyncProperty(arbSubmission, async (submission) => {
3022
+ const answer = await settle(() => adapter.submitReview(submission));
3023
+ if (takes) {
3024
+ expect13(answer.state, JSON.stringify(answer)).toBe("resolved");
3025
+ const { review } = answer.value;
3026
+ expect13([
3027
+ review.productId,
3028
+ review.customerId,
3029
+ review.orderId,
3030
+ review.rating,
3031
+ review.title,
3032
+ review.body
3033
+ ]).toEqual([
3034
+ submission.productId,
3035
+ submission.customerId,
3036
+ submission.orderId,
3037
+ submission.rating,
3038
+ submission.title,
3039
+ submission.body
3040
+ ]);
3041
+ } else {
3042
+ expect13(answer.state, "submitReview of an adapter without submit").toBe("rejected");
3043
+ const error = answer.error;
3044
+ expect13({ name: error?.name, code: error?.code }).toEqual({
3045
+ name: "ReviewRefusedError",
3046
+ code: "reviews.submit_unsupported"
3047
+ });
3048
+ }
3049
+ }),
3050
+ { numRuns: 10 }
3051
+ );
2184
3052
  },
2185
3053
  CASE_MS
2186
3054
  );
2187
- it12(
2188
- "getProductReviews returns the submitted review, read under the status submitReview reported",
3055
+ it13(
3056
+ "getProductReviews returns the seeded review, read under the status it was seeded with",
2189
3057
  async () => {
2190
3058
  const adapter = await build();
2191
3059
  const [review] = await seed(adapter, 1);
2192
3060
  const { items } = await adapter.getProductReviews(review.productId, {
2193
3061
  status: review.moderationStatus
2194
3062
  });
2195
- expect12(items.map((r) => r.id)).toEqual([review.id]);
2196
- expect12(items[0].productId).toBe(review.productId);
3063
+ expect13(items.map((r) => r.id)).toEqual([review.id]);
3064
+ expect13(items[0].productId).toBe(review.productId);
2197
3065
  },
2198
3066
  CASE_MS
2199
3067
  );
2200
- it12(
3068
+ it13(
2201
3069
  "getAggregateRating is consistent: its histogram sums to its count, and an approved review is counted",
2202
3070
  async () => {
2203
3071
  const adapter = await build();
2204
3072
  const [review] = await seed(adapter, 1);
2205
3073
  const agg = await adapter.getAggregateRating(review.productId);
2206
- expect12(agg.productId).toBe(review.productId);
2207
- expect12(Object.values(agg.histogram).reduce((a, b) => a + b, 0)).toBe(agg.count);
2208
- if (agg.count === 0) expect12(agg.average).toBe(0);
3074
+ expect13(agg.productId).toBe(review.productId);
3075
+ expect13(Object.values(agg.histogram).reduce((a, b) => a + b, 0)).toBe(agg.count);
3076
+ if (agg.count === 0) expect13(agg.average).toBe(0);
2209
3077
  else {
2210
- expect12(agg.average).toBeGreaterThanOrEqual(1);
2211
- expect12(agg.average).toBeLessThanOrEqual(5);
3078
+ expect13(agg.average).toBeGreaterThanOrEqual(1);
3079
+ expect13(agg.average).toBeLessThanOrEqual(5);
2212
3080
  }
2213
- if (review.moderationStatus === "approved") expect12(agg.count).toBeGreaterThanOrEqual(1);
3081
+ if (review.moderationStatus === "approved") expect13(agg.count).toBeGreaterThanOrEqual(1);
2214
3082
  },
2215
3083
  CASE_MS
2216
3084
  );
2217
- it12(
3085
+ it13(
2218
3086
  "pagination: over seeds larger than a page, the cursor walk from page 1 yields each review once, the walk is the seed, no page exceeds limit and nextCursor is null exactly on the last page",
2219
3087
  async () => {
2220
3088
  const adapter = await build();
2221
- await fc4.assert(
2222
- fc4.asyncProperty(
2223
- fc4.integer({ min: 1, max: 5 }),
2224
- fc4.integer({ min: 1, max: 8 }),
3089
+ await fc5.assert(
3090
+ fc5.asyncProperty(
3091
+ fc5.integer({ min: 1, max: 5 }),
3092
+ fc5.integer({ min: 1, max: 8 }),
2225
3093
  async (limit, extra) => {
2226
3094
  const seeded = await seed(adapter, limit + extra);
2227
3095
  const status = seeded[0].moderationStatus;
@@ -2233,10 +3101,10 @@ function runReviewsContract(name, build, options = {}) {
2233
3101
  Math.ceil(expected.length / limit) + 2
2234
3102
  );
2235
3103
  const walked = pages.flatMap((p) => p.items.map((r) => r.id));
2236
- expect12(new Set(walked).size, "a review came back on two pages").toBe(walked.length);
2237
- expect12([...walked].sort()).toEqual([...expected].sort());
2238
- for (const page of pages) expect12(page.items.length).toBeLessThanOrEqual(limit);
2239
- expect12(pages.map((p) => p.nextCursor === null)).toEqual(
3104
+ expect13(new Set(walked).size, "a review came back on two pages").toBe(walked.length);
3105
+ expect13([...walked].sort()).toEqual([...expected].sort());
3106
+ for (const page of pages) expect13(page.items.length).toBeLessThanOrEqual(limit);
3107
+ expect13(pages.map((p) => p.nextCursor === null)).toEqual(
2240
3108
  pages.map((_, i) => i === pages.length - 1)
2241
3109
  );
2242
3110
  }
@@ -2257,8 +3125,8 @@ function runReviewsContract(name, build, options = {}) {
2257
3125
 
2258
3126
  // src/search.ts
2259
3127
  import { randomUUID as randomUUID6 } from "crypto";
2260
- import fc5 from "fast-check";
2261
- import { describe as describe12, expect as expect13, it as it13 } from "vitest";
3128
+ import fc6 from "fast-check";
3129
+ import { describe as describe13, expect as expect14, it as it14 } from "vitest";
2262
3130
 
2263
3131
  // src/search-oracle.ts
2264
3132
  function searchTerms(text) {
@@ -2302,21 +3170,21 @@ function tierOf(p, query) {
2302
3170
  function runToken() {
2303
3171
  return `t${randomUUID6().replace(/-/g, "").slice(0, 15)}`;
2304
3172
  }
2305
- var word = fc5.string({
2306
- unit: fc5.constantFrom("a", "b", "c", "d", "1", "2"),
3173
+ var word = fc6.string({
3174
+ unit: fc6.constantFrom("a", "b", "c", "d", "1", "2"),
2307
3175
  minLength: 1,
2308
3176
  maxLength: 3
2309
3177
  });
2310
- var words = (max) => fc5.array(word, { maxLength: max }).map((ws) => ws.join(" "));
3178
+ var words2 = (max) => fc6.array(word, { maxLength: max }).map((ws) => ws.join(" "));
2311
3179
  var CATEGORIES = 3;
2312
- var genProduct = fc5.record({
2313
- name: words(3),
2314
- description: words(6),
2315
- variants: fc5.array(
2316
- fc5.record({ sku: word, name: words(2), priceMinor: fc5.integer({ min: 1, max: 2222 }) }),
3180
+ var genProduct = fc6.record({
3181
+ name: words2(3),
3182
+ description: words2(6),
3183
+ variants: fc6.array(
3184
+ fc6.record({ sku: word, name: words2(2), priceMinor: fc6.integer({ min: 1, max: 2222 }) }),
2317
3185
  { maxLength: 3 }
2318
3186
  ),
2319
- categories: fc5.subarray([0, 1, 2])
3187
+ categories: fc6.subarray([0, 1, 2])
2320
3188
  });
2321
3189
  function runCategories(token) {
2322
3190
  return Array.from({ length: CATEGORIES }, (_, k) => `c${k}${token.slice(1)}`);
@@ -2343,10 +3211,10 @@ async function walk4(adapter, query, limit, expectedMatches, filters) {
2343
3211
  });
2344
3212
  pages.push(page);
2345
3213
  const again = page.items.map((item) => item.id).filter((id) => seen.has(id));
2346
- expect13(again, `the walk for "${query}": an id came back on page ${pages.length}`).toEqual([]);
3214
+ expect14(again, `the walk for "${query}": an id came back on page ${pages.length}`).toEqual([]);
2347
3215
  for (const item of page.items) seen.add(item.id);
2348
3216
  if (page.nextCursor === null) return pages;
2349
- expect13(
3217
+ expect14(
2350
3218
  pages.length,
2351
3219
  `the walk for "${query}" did not end within ${maxPages} pages`
2352
3220
  ).toBeLessThan(maxPages);
@@ -2356,26 +3224,26 @@ async function walk4(adapter, query, limit, expectedMatches, filters) {
2356
3224
  var idsOf2 = (pages) => pages.flatMap((p) => p.items.map((item) => item.id));
2357
3225
  function expectExactWalk(pages, expected, limit, label) {
2358
3226
  const ids2 = idsOf2(pages);
2359
- expect13(new Set(ids2).size, `${label}: an id came back on two pages`).toBe(ids2.length);
2360
- expect13([...ids2].sort(), `${label}: the walk's union is not the oracle's match set`).toEqual(
3227
+ expect14(new Set(ids2).size, `${label}: an id came back on two pages`).toBe(ids2.length);
3228
+ expect14([...ids2].sort(), `${label}: the walk's union is not the oracle's match set`).toEqual(
2361
3229
  [...expected].sort()
2362
3230
  );
2363
3231
  for (const [i, page] of pages.entries()) {
2364
- expect13(page.total, `${label}: total on page ${i + 1}`).toBe(expected.length);
2365
- expect13(page.items.length, `${label}: page ${i + 1} exceeds limit`).toBeLessThanOrEqual(limit);
2366
- expect13(
3232
+ expect14(page.total, `${label}: total on page ${i + 1}`).toBe(expected.length);
3233
+ expect14(page.items.length, `${label}: page ${i + 1} exceeds limit`).toBeLessThanOrEqual(limit);
3234
+ expect14(
2367
3235
  page.nextCursor === null,
2368
3236
  `${label}: nextCursor is null on page ${i + 1} of ${pages.length}`
2369
3237
  ).toBe(i === pages.length - 1);
2370
3238
  if (expected.length > 0)
2371
- expect13(page.items.length, `${label}: page ${i + 1} is empty`).toBeGreaterThan(0);
3239
+ expect14(page.items.length, `${label}: page ${i + 1} is empty`).toBeGreaterThan(0);
2372
3240
  }
2373
3241
  }
2374
3242
  var SLOW7 = 18e4;
2375
3243
  function runSearchContract(name, build, options = {}) {
2376
3244
  const numRuns = options.numRuns ?? 25;
2377
- describe12(`SearchAdapter contract: ${name}`, () => {
2378
- it13(
3245
+ describe13(`SearchAdapter contract: ${name}`, () => {
3246
+ it14(
2379
3247
  "index returns count of indexed documents",
2380
3248
  async () => {
2381
3249
  const adapter = await build();
@@ -2383,11 +3251,11 @@ function runSearchContract(name, build, options = {}) {
2383
3251
  { id: "doc-1", type: "product", fields: { name: "Widget" } },
2384
3252
  { id: "doc-2", type: "product", fields: { name: "Gadget" } }
2385
3253
  ]);
2386
- expect13(result.indexed).toBe(2);
3254
+ expect14(result.indexed).toBe(2);
2387
3255
  },
2388
3256
  CASE_MS
2389
3257
  );
2390
- it13(
3258
+ it14(
2391
3259
  "search returns indexed documents",
2392
3260
  async () => {
2393
3261
  const adapter = await build();
@@ -2395,12 +3263,12 @@ function runSearchContract(name, build, options = {}) {
2395
3263
  { id: "search-doc-1", type: "product", fields: { name: "Searchable Item" } }
2396
3264
  ]);
2397
3265
  const result = await adapter.search("Searchable");
2398
- expect13(result.items.length).toBeGreaterThanOrEqual(1);
2399
- expect13(result.total).toBeGreaterThanOrEqual(1);
3266
+ expect14(result.items.length).toBeGreaterThanOrEqual(1);
3267
+ expect14(result.total).toBeGreaterThanOrEqual(1);
2400
3268
  },
2401
3269
  CASE_MS
2402
3270
  );
2403
- it13(
3271
+ it14(
2404
3272
  "remove deletes documents from index",
2405
3273
  async () => {
2406
3274
  const adapter = await build();
@@ -2408,11 +3276,11 @@ function runSearchContract(name, build, options = {}) {
2408
3276
  await adapter.index([{ id: tag, type: "product", fields: { name: "To Remove" } }]);
2409
3277
  await adapter.remove([tag]);
2410
3278
  const result = await adapter.search("To Remove");
2411
- expect13(result.items.find((i) => i.id === tag)).toBeUndefined();
3279
+ expect14(result.items.find((i) => i.id === tag)).toBeUndefined();
2412
3280
  },
2413
3281
  CASE_MS
2414
3282
  );
2415
- it13(
3283
+ it14(
2416
3284
  "facet returns values for a field",
2417
3285
  async () => {
2418
3286
  const adapter = await build();
@@ -2422,11 +3290,11 @@ function runSearchContract(name, build, options = {}) {
2422
3290
  { id: "facet-doc-3", type: "product", fields: { category: "shirts" } }
2423
3291
  ]);
2424
3292
  const facet = await adapter.facet("category");
2425
- expect13(typeof facet.field).toBe("string");
2426
- expect13(typeof facet.label).toBe("string");
2427
- expect13(Array.isArray(facet.values)).toBe(true);
3293
+ expect14(typeof facet.field).toBe("string");
3294
+ expect14(typeof facet.label).toBe("string");
3295
+ expect14(Array.isArray(facet.values)).toBe(true);
2428
3296
  if (facet.values.length > 0) {
2429
- expect13(typeof facet.values[0].value).toBe("string");
3297
+ expect14(typeof facet.values[0].value).toBe("string");
2430
3298
  }
2431
3299
  },
2432
3300
  CASE_MS
@@ -2437,30 +3305,30 @@ function runSearchContract(name, build, options = {}) {
2437
3305
  "search()",
2438
3306
  (adapter) => adapter.search("contract", { limit: 1 })
2439
3307
  );
2440
- describe12("pages, ranking, facets and hostile input", () => {
2441
- it13(
3308
+ describe13("pages, ranking, facets and hostile input", () => {
3309
+ it14(
2442
3310
  "over generated catalogues and page sizes, the cursor walk yields each oracle match exactly once, total is exact on every page, nextCursor is null exactly on the last page and no page exceeds limit, with and without a category filter, after removals and re-indexes",
2443
3311
  async () => {
2444
3312
  const adapter = await build();
2445
- await fc5.assert(
2446
- fc5.asyncProperty(
3313
+ await fc6.assert(
3314
+ fc6.asyncProperty(
2447
3315
  // The page size first: fast-check shrinks the arguments in order, so a failing walk shrinks its limit
2448
3316
  // before its catalogue, and the catalogue's products are shrunk once there are few of them.
2449
- fc5.integer({ min: 1, max: 40 }),
2450
- fc5.array(fc5.record({ first: genProduct, second: fc5.option(genProduct) }), {
3317
+ fc6.integer({ min: 1, max: 40 }),
3318
+ fc6.array(fc6.record({ first: genProduct, second: fc6.option(genProduct) }), {
2451
3319
  maxLength: 300,
2452
3320
  size: "large"
2453
3321
  }),
2454
- fc5.array(word, { maxLength: 2 }),
2455
- fc5.integer({ min: 0, max: CATEGORIES - 1 }),
2456
- fc5.func(fc5.boolean()),
3322
+ fc6.array(word, { maxLength: 2 }),
3323
+ fc6.integer({ min: 0, max: CATEGORIES - 1 }),
3324
+ fc6.func(fc6.boolean()),
2457
3325
  async (limit, catalogue, queryWords, filterCategory, removeIt) => {
2458
3326
  const token = runToken();
2459
3327
  const cats = runCategories(token);
2460
3328
  const first = catalogue.map((c, i) => materialise(token, c.first, i, cats));
2461
3329
  try {
2462
3330
  const indexed = await adapter.index(first.map(toSearchDocument));
2463
- expect13(indexed.indexed).toBe(first.length);
3331
+ expect14(indexed.indexed).toBe(first.length);
2464
3332
  const current = catalogue.map(
2465
3333
  (c, i) => c.second === null ? first[i] : materialise(token, c.second, i, cats)
2466
3334
  );
@@ -2491,7 +3359,7 @@ function runSearchContract(name, build, options = {}) {
2491
3359
  `"${query}" in ${category} limit ${limit}`
2492
3360
  );
2493
3361
  const shown = [...idsOf2(all), ...idsOf2(filtered)];
2494
- expect13(
3362
+ expect14(
2495
3363
  shown.filter((id) => gone.has(id)),
2496
3364
  "a removed id came back"
2497
3365
  ).toEqual([]);
@@ -2506,24 +3374,24 @@ function runSearchContract(name, build, options = {}) {
2506
3374
  SLOW7
2507
3375
  );
2508
3376
  if (options.ranking) {
2509
- it13(
3377
+ it14(
2510
3378
  "for any query, every all-terms-in-name match ranks above every other match and every name/SKU/variant-name match above every description-only match, however often the description repeats the term, and the same query walks in the same order twice",
2511
3379
  async () => {
2512
3380
  const adapter = await build();
2513
- const placed = fc5.record({
3381
+ const placed = fc6.record({
2514
3382
  base: genProduct,
2515
- inName: fc5.boolean(),
2516
- inSku: fc5.boolean(),
2517
- inVariant: fc5.boolean(),
2518
- descriptionRepeats: fc5.integer({ min: 0, max: 10 })
3383
+ inName: fc6.boolean(),
3384
+ inSku: fc6.boolean(),
3385
+ inVariant: fc6.boolean(),
3386
+ descriptionRepeats: fc6.integer({ min: 0, max: 10 })
2519
3387
  });
2520
- await fc5.assert(
2521
- fc5.asyncProperty(
2522
- fc5.array(placed, { minLength: 1, maxLength: 60 }),
3388
+ await fc6.assert(
3389
+ fc6.asyncProperty(
3390
+ fc6.array(placed, { minLength: 1, maxLength: 60 }),
2523
3391
  word,
2524
- fc5.option(word),
2525
- fc5.integer({ min: 1, max: 30 }),
2526
- fc5.integer({ min: 1, max: 30 }),
3392
+ fc6.option(word),
3393
+ fc6.integer({ min: 1, max: 30 }),
3394
+ fc6.integer({ min: 1, max: 30 }),
2527
3395
  async (catalogue, term, second, limitA, limitB) => {
2528
3396
  const token = runToken();
2529
3397
  const cats = runCategories(token);
@@ -2546,18 +3414,18 @@ function runSearchContract(name, build, options = {}) {
2546
3414
  const byId = new Map(products.map((p) => [p.id, p]));
2547
3415
  const matches = products.filter((p) => matchesQuery(p, query));
2548
3416
  const order = idsOf2(await walk4(adapter, query, limitA, matches.length));
2549
- expect13([...order].sort(), "the walk is not the match set").toEqual(
3417
+ expect14([...order].sort(), "the walk is not the match set").toEqual(
2550
3418
  matches.map((p) => p.id).sort()
2551
3419
  );
2552
3420
  const tiers = order.map((id) => tierOf(byId.get(id), query));
2553
3421
  for (let i = 1; i < tiers.length; i++) {
2554
- expect13(
3422
+ expect14(
2555
3423
  tiers[i - 1],
2556
3424
  `"${query}": ${order[i - 1]} (tier ${tiers[i - 1]}) ranked above ${order[i]} (tier ${tiers[i]})`
2557
3425
  ).toBeGreaterThanOrEqual(tiers[i]);
2558
3426
  }
2559
3427
  const again = idsOf2(await walk4(adapter, query, limitB, matches.length));
2560
- expect13(again, `"${query}" walked at limit ${limitA}, then ${limitB}`).toEqual(
3428
+ expect14(again, `"${query}" walked at limit ${limitA}, then ${limitB}`).toEqual(
2561
3429
  order
2562
3430
  );
2563
3431
  } finally {
@@ -2572,16 +3440,16 @@ function runSearchContract(name, build, options = {}) {
2572
3440
  );
2573
3441
  }
2574
3442
  if (options.facets) {
2575
- it13(
3443
+ it14(
2576
3444
  "facet('categoryIds', {query, filters}) counts, per category id, exactly the oracle's matches in that category under the filters, lists no category without one, and orders by count descending, then value",
2577
3445
  async () => {
2578
3446
  const adapter = await build();
2579
- expect13(adapter.capabilities()).toContain("facet");
2580
- await fc5.assert(
2581
- fc5.asyncProperty(
2582
- fc5.array(genProduct, { maxLength: 150, size: "medium" }),
2583
- fc5.array(word, { maxLength: 2 }),
2584
- fc5.option(fc5.integer({ min: 0, max: CATEGORIES - 1 })),
3447
+ expect14(adapter.capabilities()).toContain("facet");
3448
+ await fc6.assert(
3449
+ fc6.asyncProperty(
3450
+ fc6.array(genProduct, { maxLength: 150, size: "medium" }),
3451
+ fc6.array(word, { maxLength: 2 }),
3452
+ fc6.option(fc6.integer({ min: 0, max: CATEGORIES - 1 })),
2585
3453
  async (catalogue, queryWords, filterCategory) => {
2586
3454
  const token = runToken();
2587
3455
  const cats = runCategories(token);
@@ -2601,12 +3469,12 @@ function runSearchContract(name, build, options = {}) {
2601
3469
  ...filter !== void 0 && { filters: { categoryIds: filter } }
2602
3470
  });
2603
3471
  const label = `facet for "${query}"${filter === void 0 ? "" : ` in ${filter}`}`;
2604
- expect13(
3472
+ expect14(
2605
3473
  Object.fromEntries(facet.values.map((v) => [v.value, v.count])),
2606
3474
  label
2607
3475
  ).toEqual(Object.fromEntries(expected));
2608
3476
  const ordered = [...expected.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([value]) => value);
2609
- expect13(
3477
+ expect14(
2610
3478
  facet.values.map((v) => v.value),
2611
3479
  `${label}: order`
2612
3480
  ).toEqual(ordered);
@@ -2621,8 +3489,8 @@ function runSearchContract(name, build, options = {}) {
2621
3489
  SLOW7
2622
3490
  );
2623
3491
  }
2624
- describe12("hostile input", () => {
2625
- const operator = fc5.constantFrom(
3492
+ describe13("hostile input", () => {
3493
+ const operator = fc6.constantFrom(
2626
3494
  '"',
2627
3495
  "*",
2628
3496
  "NEAR",
@@ -2650,22 +3518,22 @@ function runSearchContract(name, build, options = {}) {
2650
3518
  ";",
2651
3519
  "\0"
2652
3520
  );
2653
- const fragment = fc5.oneof(
2654
- fc5.string({ unit: "binary", maxLength: 6 }),
3521
+ const fragment = fc6.oneof(
3522
+ fc6.string({ unit: "binary", maxLength: 6 }),
2655
3523
  operator,
2656
3524
  word,
2657
3525
  word.map((w) => w.toUpperCase())
2658
3526
  );
2659
- const hostile = fc5.array(fragment, { maxLength: 6 }).map((fs) => fs.join(""));
3527
+ const hostile = fc6.array(fragment, { maxLength: 6 }).map((fs) => fs.join(""));
2660
3528
  const longTerm = "a".repeat(2047);
2661
3529
  const plain = { name: "a b", description: "c", variants: [], categories: [0] };
2662
- it13(
3530
+ it14(
2663
3531
  "any string after the run token, full unicode and FTS operators included, never throws and returns exactly the oracle's matches for the query's normalised terms",
2664
3532
  async () => {
2665
3533
  const adapter = await build();
2666
- await fc5.assert(
2667
- fc5.asyncProperty(
2668
- fc5.array(genProduct, { maxLength: 40 }),
3534
+ await fc6.assert(
3535
+ fc6.asyncProperty(
3536
+ fc6.array(genProduct, { maxLength: 40 }),
2669
3537
  hostile,
2670
3538
  async (catalogue, raw) => {
2671
3539
  const token = runToken();
@@ -2676,10 +3544,10 @@ function runSearchContract(name, build, options = {}) {
2676
3544
  const query = `${token} ${raw}`;
2677
3545
  const expected = products.filter((p) => matchesQuery(p, query)).map((p) => p.id);
2678
3546
  const result = await adapter.search(query, { limit: 100 });
2679
- expect13(result.items.map((d) => d.id).sort(), JSON.stringify(query)).toEqual(
3547
+ expect14(result.items.map((d) => d.id).sort(), JSON.stringify(query)).toEqual(
2680
3548
  expected.sort()
2681
3549
  );
2682
- expect13(result.total, JSON.stringify(query)).toBe(expected.length);
3550
+ expect14(result.total, JSON.stringify(query)).toBe(expected.length);
2683
3551
  } finally {
2684
3552
  await adapter.remove(products.map((p) => p.id));
2685
3553
  }
@@ -2699,7 +3567,7 @@ function runSearchContract(name, build, options = {}) {
2699
3567
  },
2700
3568
  SLOW7
2701
3569
  );
2702
- it13(
3570
+ it14(
2703
3571
  "input with no terms returns no items, total 0 and no next page, over an index that holds products",
2704
3572
  async () => {
2705
3573
  const adapter = await build();
@@ -2713,20 +3581,20 @@ function runSearchContract(name, build, options = {}) {
2713
3581
  }));
2714
3582
  await adapter.index(products.map(toSearchDocument));
2715
3583
  try {
2716
- const termless = fc5.array(
2717
- fc5.oneof(
3584
+ const termless = fc6.array(
3585
+ fc6.oneof(
2718
3586
  operator,
2719
- fc5.string({ unit: "binary", maxLength: 4 }),
2720
- fc5.constantFrom(" ", " ", "\n")
3587
+ fc6.string({ unit: "binary", maxLength: 4 }),
3588
+ fc6.constantFrom(" ", " ", "\n")
2721
3589
  ),
2722
3590
  { maxLength: 6 }
2723
3591
  ).map((fs) => fs.join("")).filter((s) => searchTerms(s).length === 0);
2724
- await fc5.assert(
2725
- fc5.asyncProperty(termless, async (raw) => {
3592
+ await fc6.assert(
3593
+ fc6.asyncProperty(termless, async (raw) => {
2726
3594
  const result = await adapter.search(raw, { limit: 20 });
2727
- expect13(result.items.length, JSON.stringify(raw)).toBe(0);
2728
- expect13(result.total, JSON.stringify(raw)).toBe(0);
2729
- expect13(result.nextCursor, JSON.stringify(raw)).toBeNull();
3595
+ expect14(result.items.length, JSON.stringify(raw)).toBe(0);
3596
+ expect14(result.total, JSON.stringify(raw)).toBe(0);
3597
+ expect14(result.nextCursor, JSON.stringify(raw)).toBeNull();
2730
3598
  }),
2731
3599
  {
2732
3600
  numRuns: numRuns * 2,
@@ -2739,7 +3607,7 @@ function runSearchContract(name, build, options = {}) {
2739
3607
  },
2740
3608
  SLOW7
2741
3609
  );
2742
- it13(
3610
+ it14(
2743
3611
  "a malformed cursor (undecodable, negative, non-integer) rejects, and a cursor at or past total, as after a removal between two pages, is an empty page with nextCursor null",
2744
3612
  async () => {
2745
3613
  const adapter = await build();
@@ -2754,17 +3622,17 @@ function runSearchContract(name, build, options = {}) {
2754
3622
  await adapter.index(products.map(toSearchDocument));
2755
3623
  try {
2756
3624
  const first = await adapter.search(token, { limit: 4 });
2757
- expect13(first.total).toBe(products.length);
2758
- expect13(first.nextCursor, "six matches at limit 4 have a second page").not.toBeNull();
3625
+ expect14(first.total).toBe(products.length);
3626
+ expect14(first.nextCursor, "six matches at limit 4 have a second page").not.toBeNull();
2759
3627
  for (const cursor of ["not a cursor", "%%%", "!!"]) {
2760
- await expect13(
3628
+ await expect14(
2761
3629
  adapter.search(token, { limit: 2, cursor }),
2762
3630
  `cursor ${cursor}`
2763
3631
  ).rejects.toThrow();
2764
3632
  }
2765
3633
  if (options.cursorAt !== void 0) {
2766
3634
  for (const offset of [-1, -20, 1.5, 0.25]) {
2767
- await expect13(
3635
+ await expect14(
2768
3636
  adapter.search(token, { limit: 2, cursor: options.cursorAt(offset) }),
2769
3637
  `cursor at offset ${offset}`
2770
3638
  ).rejects.toThrow();
@@ -2773,18 +3641,18 @@ function runSearchContract(name, build, options = {}) {
2773
3641
  const kept = products.slice(0, 2);
2774
3642
  await adapter.remove(products.slice(2).map((p) => p.id));
2775
3643
  const stale = await adapter.search(token, { limit: 4, cursor: first.nextCursor });
2776
- expect13(stale.items.length).toBe(0);
2777
- expect13(stale.nextCursor).toBeNull();
2778
- expect13(stale.total).toBe(kept.length);
3644
+ expect14(stale.items.length).toBe(0);
3645
+ expect14(stale.nextCursor).toBeNull();
3646
+ expect14(stale.total).toBe(kept.length);
2779
3647
  if (options.cursorAt !== void 0) {
2780
3648
  for (const offset of [kept.length, kept.length + 7]) {
2781
3649
  const past = await adapter.search(token, {
2782
3650
  limit: 4,
2783
3651
  cursor: options.cursorAt(offset)
2784
3652
  });
2785
- expect13(past.items.length, `offset ${offset}`).toBe(0);
2786
- expect13(past.nextCursor, `offset ${offset}`).toBeNull();
2787
- expect13(past.total, `offset ${offset}`).toBe(kept.length);
3653
+ expect14(past.items.length, `offset ${offset}`).toBe(0);
3654
+ expect14(past.nextCursor, `offset ${offset}`).toBeNull();
3655
+ expect14(past.total, `offset ${offset}`).toBe(kept.length);
2788
3656
  }
2789
3657
  }
2790
3658
  } finally {
@@ -2799,66 +3667,232 @@ function runSearchContract(name, build, options = {}) {
2799
3667
  }
2800
3668
 
2801
3669
  // src/shipping.ts
2802
- import { describe as describe13, expect as expect14, it as it14 } from "vitest";
2803
- var REQUEST = {
2804
- fromPostalCode: "SW1A 1AA",
2805
- toPostalCode: "EC1A 1BB",
2806
- toCountry: "GB",
2807
- weightGrams: 500,
2808
- currency: "GBP"
3670
+ import { randomUUID as randomUUID7 } from "crypto";
3671
+ import fc7 from "fast-check";
3672
+ import { describe as describe14, expect as expect15, it as it15 } from "vitest";
3673
+ var WORDS = ["rates", "labels", "tracking"];
3674
+ var METHOD = {
3675
+ rates: "rate",
3676
+ labels: "createLabel",
3677
+ tracking: "startTracking"
2809
3678
  };
3679
+ var FROM = {
3680
+ firstName: "Nymbal",
3681
+ lastName: "Warehouse",
3682
+ company: "Nymbal Contract",
3683
+ addressLine1: "417 Montgomery Street",
3684
+ addressLine2: "Floor 5",
3685
+ city: "San Francisco",
3686
+ region: "CA",
3687
+ postalCode: "94104",
3688
+ country: "US",
3689
+ phone: "4155559999"
3690
+ };
3691
+ var TO = {
3692
+ firstName: "Dr Steve",
3693
+ lastName: "Brule",
3694
+ addressLine1: "179 N Harbor Dr",
3695
+ city: "Redondo Beach",
3696
+ region: "CA",
3697
+ postalCode: "90277",
3698
+ country: "US",
3699
+ phone: "3105551234"
3700
+ };
3701
+ var PARCEL = { weightGrams: 500 };
3702
+ var declares = (adapter, word2) => adapter.capabilities().includes(word2);
3703
+ var serves = (adapter, word2) => declares(adapter, word2) && typeof adapter[METHOD[word2]] === "function";
3704
+ var freshNumber = () => `NYM${randomUUID7().replace(/\D/g, "").padEnd(18, "7").slice(0, 18)}`;
3705
+ var arbParcel = fc7.oneof(
3706
+ fc7.record({ weightGrams: fc7.integer({ min: 1, max: 3e4 }) }),
3707
+ fc7.record({
3708
+ weightGrams: fc7.integer({ min: 1, max: 3e4 }),
3709
+ lengthMm: fc7.integer({ min: 10, max: 1e3 }),
3710
+ widthMm: fc7.integer({ min: 10, max: 1e3 }),
3711
+ heightMm: fc7.integer({ min: 10, max: 1e3 })
3712
+ })
3713
+ );
3714
+ function expectRate(rate) {
3715
+ const what = JSON.stringify(rate);
3716
+ expect15(typeof rate.id === "string" && rate.id.length > 0, `a rate without an id: ${what}`).toBe(
3717
+ true
3718
+ );
3719
+ expect15(Number.isInteger(rate.amountMinor), `amountMinor not an integer: ${what}`).toBe(true);
3720
+ expect15(rate.amountMinor, what).toBeGreaterThanOrEqual(0);
3721
+ expect15(rate.currency, what).toMatch(/^[A-Z]{3}$/);
3722
+ const days = rate.estimatedDays;
3723
+ expect15(
3724
+ days === null || Number.isInteger(days) && days >= 0,
3725
+ `estimatedDays neither null nor an integer \u2265 0: ${what}`
3726
+ ).toBe(true);
3727
+ }
2810
3728
  function runShippingContract(name, build, options = {}) {
2811
- describe13(`ShippingAdapter contract: ${name}`, () => {
2812
- it14(
2813
- "rate returns an array of shipping options",
2814
- async () => {
2815
- const adapter = await build();
2816
- const rates = await adapter.rate(REQUEST);
2817
- expect14(Array.isArray(rates)).toBe(true);
2818
- if (rates.length > 0) {
2819
- const rate = rates[0];
2820
- expect14(typeof rate.amountMinor).toBe("number");
2821
- expect14(typeof rate.carrier).toBe("string");
2822
- expect14(typeof rate.estimatedDays).toBe("number");
3729
+ const from = options.from ?? FROM;
3730
+ const to = options.to ?? TO;
3731
+ const trackingNumber = options.trackingNumber ?? freshNumber;
3732
+ const carrier = options.carrier ?? null;
3733
+ async function ratesOf(adapter, parcel) {
3734
+ const rates = await adapter.rate({ from, to, parcel });
3735
+ expect15(Array.isArray(rates), "rate() did not answer an array").toBe(true);
3736
+ return rates;
3737
+ }
3738
+ function firstOperation(adapter) {
3739
+ const word2 = WORDS.find((w) => serves(adapter, w));
3740
+ if (word2 === "rates") return () => adapter.rate({ from, to, parcel: options.parcel ?? PARCEL });
3741
+ if (word2 === "labels") return () => adapter.createLabel({ rateId: "contract-unbought-rate" });
3742
+ if (word2 === "tracking") {
3743
+ return () => adapter.startTracking({ trackingNumber: trackingNumber(), carrier });
3744
+ }
3745
+ return void 0;
3746
+ }
3747
+ describe14(`ShippingAdapter contract: ${name}`, () => {
3748
+ it15(
3749
+ "words: each of rates, labels and tracking is declared exactly when its method (rate, createLabel, startTracking) is a function; tracking needs receiveWebhook, labels needs rates, and no other word is declared or any twice",
3750
+ () => using(build, async (adapter) => {
3751
+ const words3 = [...adapter.capabilities()];
3752
+ const methods = adapter;
3753
+ expect15(
3754
+ words3.filter((w) => !WORDS.includes(w)),
3755
+ "words the shipping slot does not have"
3756
+ ).toEqual([]);
3757
+ expect15(words3.length, `a word declared twice: ${JSON.stringify(words3)}`).toBe(
3758
+ new Set(words3).size
3759
+ );
3760
+ expect15(
3761
+ Object.fromEntries(WORDS.map((w) => [w, words3.includes(w)])),
3762
+ "declared words against the methods present"
3763
+ ).toEqual(
3764
+ Object.fromEntries(WORDS.map((w) => [w, typeof methods[METHOD[w]] === "function"]))
3765
+ );
3766
+ if (words3.includes("tracking")) {
3767
+ expect15(typeof adapter.receiveWebhook, "tracking without receiveWebhook").toBe(
3768
+ "function"
3769
+ );
2823
3770
  }
2824
- },
3771
+ if (words3.includes("labels")) {
3772
+ expect15(words3, "labels without rates: a label is bought from a rate").toContain("rates");
3773
+ }
3774
+ }),
3775
+ CASE_MS
3776
+ );
3777
+ it15(
3778
+ "rates: property: over generated parcels, every rate has a non-empty id, an integer amountMinor \u2265 0, a three-letter currency and estimatedDays null or an integer \u2265 0",
3779
+ (ctx) => using(build, async (adapter) => {
3780
+ if (!serves(adapter, "rates")) return ctx.skip();
3781
+ const parcels = options.parcel === void 0 ? arbParcel : fc7.constant(options.parcel);
3782
+ await fc7.assert(
3783
+ fc7.asyncProperty(parcels, async (parcel) => {
3784
+ for (const rate of await ratesOf(adapter, parcel)) expectRate(rate);
3785
+ }),
3786
+ { numRuns: 3 }
3787
+ );
3788
+ }),
3789
+ CASE_MS
3790
+ );
3791
+ it15(
3792
+ "labels: createLabel({ rateId }) of a returned rate answers a labelUrl that parses as a URL and a non-empty trackingNumber",
3793
+ (ctx) => using(build, async (adapter) => {
3794
+ if (!serves(adapter, "labels") || !serves(adapter, "rates")) return ctx.skip();
3795
+ const rates = await ratesOf(adapter, options.parcel ?? PARCEL);
3796
+ expect15(rates.length, "no rate to buy a label from").toBeGreaterThan(0);
3797
+ const label = await adapter.createLabel({ rateId: rates[0].id });
3798
+ expect15(URL.canParse(label.labelUrl), `labelUrl ${label.labelUrl}`).toBe(true);
3799
+ expect15(label.trackingNumber.trim().length, JSON.stringify(label)).toBeGreaterThan(0);
3800
+ }),
3801
+ CASE_MS
3802
+ );
3803
+ it15(
3804
+ "labels: property: one rateId bought 2 to 3 times answers the first label\u2019s trackingNumber or rejects, never a second, different label",
3805
+ (ctx) => using(build, async (adapter) => {
3806
+ if (!serves(adapter, "labels") || !serves(adapter, "rates")) return ctx.skip();
3807
+ await fc7.assert(
3808
+ fc7.asyncProperty(fc7.integer({ min: 2, max: 3 }), fc7.nat(), async (buys, pick) => {
3809
+ const rates = await ratesOf(adapter, options.parcel ?? PARCEL);
3810
+ expect15(rates.length, "no rate to buy a label from").toBeGreaterThan(0);
3811
+ const rateId = rates[pick % rates.length].id;
3812
+ const first = await adapter.createLabel({ rateId });
3813
+ const again = [];
3814
+ for (let i = 1; i < buys; i += 1) {
3815
+ const answer = await settle(() => adapter.createLabel({ rateId }));
3816
+ if (answer.state === "resolved") again.push(answer.value.trackingNumber);
3817
+ else expect15(answer.state, "a repeated buy hung").toBe("rejected");
3818
+ }
3819
+ expect15(again, `rate ${rateId} bought ${buys} times`).toEqual(
3820
+ again.map(() => first.trackingNumber)
3821
+ );
3822
+ }),
3823
+ { numRuns: 3 }
3824
+ );
3825
+ }),
3826
+ CASE_MS
3827
+ );
3828
+ it15(
3829
+ "tracking: startTracking of one number twice answers tracking both times",
3830
+ (ctx) => using(build, async (adapter) => {
3831
+ if (!serves(adapter, "tracking")) return ctx.skip();
3832
+ const number = trackingNumber();
3833
+ const first = await adapter.startTracking({ trackingNumber: number, carrier });
3834
+ const second = await adapter.startTracking({ trackingNumber: number, carrier });
3835
+ expect15([first, second]).toEqual([{ status: "tracking" }, { status: "tracking" }]);
3836
+ }),
2825
3837
  CASE_MS
2826
3838
  );
2827
- healthAndDowntime(build, options.unreachable, "rate()", (adapter) => adapter.rate(REQUEST));
3839
+ it15(
3840
+ "health: healthCheck() resolves healthy or degraded within 6 s",
3841
+ () => using(build, (adapter) => expectHealthy(adapter)),
3842
+ CASE_MS
3843
+ );
3844
+ const unreachable = options.unreachable;
3845
+ if (unreachable === void 0) return;
3846
+ describe14("unreachable dependency", () => {
3847
+ it15(
3848
+ "down: healthCheck() reports down within 6 s",
3849
+ () => using(unreachable, (adapter) => expectDown(adapter)),
3850
+ CASE_MS
3851
+ );
3852
+ it15(
3853
+ "down: the first declared word\u2019s method rejects within 6 s instead of hanging",
3854
+ (ctx) => using(unreachable, async (adapter) => {
3855
+ const operation = firstOperation(adapter);
3856
+ if (operation === void 0) return ctx.skip();
3857
+ await expectRejects(operation);
3858
+ }),
3859
+ CASE_MS
3860
+ );
3861
+ });
2828
3862
  });
2829
3863
  }
2830
3864
 
2831
3865
  // src/tax.ts
2832
- import { describe as describe14, expect as expect15, it as it15 } from "vitest";
2833
- var REQUEST2 = {
3866
+ import { describe as describe15, expect as expect16, it as it16 } from "vitest";
3867
+ var REQUEST = {
2834
3868
  currency: "GBP",
2835
3869
  shippingCountry: "GB",
2836
3870
  shippingRegion: "England",
2837
3871
  lines: [{ amountMinor: 1e3, qty: 2 }]
2838
3872
  };
2839
3873
  function runTaxContract(name, build, options = {}) {
2840
- describe14(`TaxAdapter contract: ${name}`, () => {
2841
- it15(
3874
+ describe15(`TaxAdapter contract: ${name}`, () => {
3875
+ it16(
2842
3876
  "calculate returns totalTaxMinor >= 0",
2843
3877
  async () => {
2844
3878
  const adapter = await build();
2845
- const result = await adapter.calculate(REQUEST2);
2846
- expect15(typeof result.totalTaxMinor).toBe("number");
2847
- expect15(result.totalTaxMinor).toBeGreaterThanOrEqual(0);
2848
- expect15(result.ratePerLine).toHaveLength(1);
2849
- expect15(typeof result.ratePerLine[0].taxMinor).toBe("number");
3879
+ const result = await adapter.calculate(REQUEST);
3880
+ expect16(typeof result.totalTaxMinor).toBe("number");
3881
+ expect16(result.totalTaxMinor).toBeGreaterThanOrEqual(0);
3882
+ expect16(result.ratePerLine).toHaveLength(1);
3883
+ expect16(typeof result.ratePerLine[0].taxMinor).toBe("number");
2850
3884
  },
2851
3885
  CASE_MS
2852
3886
  );
2853
- it15(
3887
+ it16(
2854
3888
  "calculate with zero amount returns zero tax",
2855
3889
  async () => {
2856
3890
  const adapter = await build();
2857
3891
  const result = await adapter.calculate({
2858
- ...REQUEST2,
3892
+ ...REQUEST,
2859
3893
  lines: [{ amountMinor: 0, qty: 1 }]
2860
3894
  });
2861
- expect15(result.totalTaxMinor).toBe(0);
3895
+ expect16(result.totalTaxMinor).toBe(0);
2862
3896
  },
2863
3897
  CASE_MS
2864
3898
  );
@@ -2866,7 +3900,7 @@ function runTaxContract(name, build, options = {}) {
2866
3900
  build,
2867
3901
  options.unreachable,
2868
3902
  "calculate()",
2869
- (adapter) => adapter.calculate(REQUEST2)
3903
+ (adapter) => adapter.calculate(REQUEST)
2870
3904
  );
2871
3905
  });
2872
3906
  }
@@ -2885,36 +3919,36 @@ function adapterContext(slot, config, env = {}) {
2885
3919
  }
2886
3920
 
2887
3921
  // src/webhook.ts
2888
- import { describe as describe15, expect as expect16, it as it16 } from "vitest";
3922
+ import { describe as describe16, expect as expect17, it as it17 } from "vitest";
2889
3923
  import {
2890
3924
  webhookDeliveryProblem
2891
3925
  } from "@nymbalhq/types";
2892
3926
  function receiving(adapter) {
2893
- expect16(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
3927
+ expect17(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
2894
3928
  return adapter;
2895
3929
  }
2896
3930
  async function receive(adapter, request) {
2897
3931
  return receiving(adapter).receiveWebhook(request.rawBody, request.headers);
2898
3932
  }
2899
3933
  function runWebhookContract(name, build, options) {
2900
- describe15(`webhook contract: ${name}`, () => {
2901
- it16(
3934
+ describe16(`webhook contract: ${name}`, () => {
3935
+ it17(
2902
3936
  "idempotency: one delivery received twice gives one deliveryId and equal events",
2903
3937
  () => using(build, async (adapter) => {
2904
3938
  const first = await receive(adapter, options.delivery());
2905
3939
  const second = await receive(adapter, options.delivery());
2906
- expect16(first.verified, "the signed delivery was not verified").toBe(true);
2907
- expect16(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
2908
- expect16(second.deliveryId, "the same delivery got another deliveryId").toBe(
3940
+ expect17(first.verified, "the signed delivery was not verified").toBe(true);
3941
+ expect17(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
3942
+ expect17(second.deliveryId, "the same delivery got another deliveryId").toBe(
2909
3943
  first.deliveryId
2910
3944
  );
2911
- expect16(second.events).toEqual(first.events);
3945
+ expect17(second.events).toEqual(first.events);
2912
3946
  }),
2913
3947
  CASE_MS
2914
3948
  );
2915
3949
  const tampered = options.tampered;
2916
3950
  if (tampered !== void 0) {
2917
- it16(
3951
+ it17(
2918
3952
  "verification: a tampered delivery is not verified",
2919
3953
  () => using(build, async (adapter) => {
2920
3954
  const outcome = await receive(adapter, tampered()).then(
@@ -2924,21 +3958,21 @@ function runWebhookContract(name, build, options) {
2924
3958
  code: err?.code
2925
3959
  })
2926
3960
  );
2927
- expect16(outcome.verified, "a tampered delivery was verified").toBe(false);
2928
- if (outcome.code !== null) expect16(String(outcome.code)).toMatch(/webhook_invalid$/);
3961
+ expect17(outcome.verified, "a tampered delivery was verified").toBe(false);
3962
+ if (outcome.code !== null) expect17(String(outcome.code)).toMatch(/webhook_invalid$/);
2929
3963
  }),
2930
3964
  CASE_MS
2931
3965
  );
2932
3966
  }
2933
- it16(
3967
+ it17(
2934
3968
  "namespace: every event is the adapter's own, declared and versioned",
2935
3969
  () => using(build, async (adapter) => {
2936
3970
  const delivery = await receive(adapter, options.delivery());
2937
- expect16(delivery.verified, "the signed delivery was not verified").toBe(true);
2938
- expect16(delivery.events.length, "the delivery carried no event to check").toBeGreaterThan(
3971
+ expect17(delivery.verified, "the signed delivery was not verified").toBe(true);
3972
+ expect17(delivery.events.length, "the delivery carried no event to check").toBeGreaterThan(
2939
3973
  0
2940
3974
  );
2941
- expect16(
3975
+ expect17(
2942
3976
  webhookDeliveryProblem(adapter.providerName, adapter.producesEvents, delivery),
2943
3977
  "the kernel would refuse this delivery"
2944
3978
  ).toBeNull();
@@ -2949,14 +3983,14 @@ function runWebhookContract(name, build, options) {
2949
3983
  }
2950
3984
 
2951
3985
  // src/email-feedback.ts
2952
- import { describe as describe16, expect as expect17, it as it17 } from "vitest";
3986
+ import { describe as describe17, expect as expect18, it as it18 } from "vitest";
2953
3987
  import {
2954
3988
  emailFeedbackProblem,
2955
3989
  emailFeedbackType,
2956
3990
  webhookDeliveryProblem as webhookDeliveryProblem2
2957
3991
  } from "@nymbalhq/types";
2958
3992
  async function receive2(adapter, request) {
2959
- expect17(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
3993
+ expect18(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
2960
3994
  return adapter.receiveWebhook(request.rawBody, request.headers);
2961
3995
  }
2962
3996
  function eventsFor(delivery, type, recipient) {
@@ -2966,20 +4000,20 @@ function runEmailFeedbackContract(name, build, options) {
2966
4000
  const samples = [options.bounce, options.softBounce, options.complaint].filter(
2967
4001
  (sample) => sample !== void 0
2968
4002
  );
2969
- describe16(`email feedback contract: ${name}`, () => {
2970
- it17(
4003
+ describe17(`email feedback contract: ${name}`, () => {
4004
+ it18(
2971
4005
  "replay: one bounce received twice gives one deliveryId and equal events",
2972
4006
  () => using(build, async (adapter) => {
2973
4007
  const first = await receive2(adapter, options.bounce().request);
2974
4008
  const second = await receive2(adapter, options.bounce().request);
2975
- expect17(first.verified, "the signed bounce was not verified").toBe(true);
2976
- expect17(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
2977
- expect17(second.deliveryId, "the same bounce got another deliveryId").toBe(first.deliveryId);
2978
- expect17(second.events).toEqual(first.events);
4009
+ expect18(first.verified, "the signed bounce was not verified").toBe(true);
4010
+ expect18(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
4011
+ expect18(second.deliveryId, "the same bounce got another deliveryId").toBe(first.deliveryId);
4012
+ expect18(second.events).toEqual(first.events);
2979
4013
  }),
2980
4014
  CASE_MS
2981
4015
  );
2982
- it17(
4016
+ it18(
2983
4017
  "shape: every event passes the kernel's rules for this slot",
2984
4018
  () => using(build, async (adapter) => {
2985
4019
  const feedback = [
@@ -2988,16 +4022,16 @@ function runEmailFeedbackContract(name, build, options) {
2988
4022
  ];
2989
4023
  for (const sample of samples) {
2990
4024
  const delivery = await receive2(adapter, sample().request);
2991
- expect17(delivery.verified, "a signed delivery was not verified").toBe(true);
2992
- expect17(
4025
+ expect18(delivery.verified, "a signed delivery was not verified").toBe(true);
4026
+ expect18(
2993
4027
  delivery.events.filter((e) => feedback.includes(e.type)).length,
2994
4028
  "the delivery carried no bounce or complaint to check"
2995
4029
  ).toBeGreaterThan(0);
2996
- expect17(
4030
+ expect18(
2997
4031
  webhookDeliveryProblem2(adapter.providerName, adapter.producesEvents, delivery),
2998
4032
  "the kernel would refuse this delivery"
2999
4033
  ).toBeNull();
3000
- expect17(
4034
+ expect18(
3001
4035
  emailFeedbackProblem(adapter.providerName, delivery),
3002
4036
  "the kernel would refuse this delivery for the email slot"
3003
4037
  ).toBeNull();
@@ -3005,7 +4039,7 @@ function runEmailFeedbackContract(name, build, options) {
3005
4039
  }),
3006
4040
  CASE_MS
3007
4041
  );
3008
- it17(
4042
+ it18(
3009
4043
  "classification: the hard bounce is hard for its recipient",
3010
4044
  () => using(build, async (adapter) => {
3011
4045
  const { request, recipient } = options.bounce();
@@ -3015,14 +4049,14 @@ function runEmailFeedbackContract(name, build, options) {
3015
4049
  emailFeedbackType(adapter.providerName, "bounced"),
3016
4050
  recipient
3017
4051
  );
3018
- expect17(bounces.length, `no bounce for ${recipient}`).toBeGreaterThan(0);
3019
- expect17(bounces.map((e) => e.payload["bounce"])).toEqual(bounces.map(() => "hard"));
4052
+ expect18(bounces.length, `no bounce for ${recipient}`).toBeGreaterThan(0);
4053
+ expect18(bounces.map((e) => e.payload["bounce"])).toEqual(bounces.map(() => "hard"));
3020
4054
  }),
3021
4055
  CASE_MS
3022
4056
  );
3023
4057
  const { softBounce, complaint } = options;
3024
4058
  if (softBounce !== void 0) {
3025
- it17(
4059
+ it18(
3026
4060
  "classification: the soft bounce is soft for its recipient",
3027
4061
  () => using(build, async (adapter) => {
3028
4062
  const { request, recipient } = softBounce();
@@ -3032,14 +4066,14 @@ function runEmailFeedbackContract(name, build, options) {
3032
4066
  emailFeedbackType(adapter.providerName, "bounced"),
3033
4067
  recipient
3034
4068
  );
3035
- expect17(bounces.length, `no bounce for ${recipient}`).toBeGreaterThan(0);
3036
- expect17(bounces.map((e) => e.payload["bounce"])).toEqual(bounces.map(() => "soft"));
4069
+ expect18(bounces.length, `no bounce for ${recipient}`).toBeGreaterThan(0);
4070
+ expect18(bounces.map((e) => e.payload["bounce"])).toEqual(bounces.map(() => "soft"));
3037
4071
  }),
3038
4072
  CASE_MS
3039
4073
  );
3040
4074
  }
3041
4075
  if (complaint !== void 0) {
3042
- it17(
4076
+ it18(
3043
4077
  "classification: the complaint is a complaint for its recipient",
3044
4078
  () => using(build, async (adapter) => {
3045
4079
  const { request, recipient } = complaint();
@@ -3049,7 +4083,7 @@ function runEmailFeedbackContract(name, build, options) {
3049
4083
  emailFeedbackType(adapter.providerName, "complained"),
3050
4084
  recipient
3051
4085
  );
3052
- expect17(complaints.length, `no complaint for ${recipient}`).toBeGreaterThan(0);
4086
+ expect18(complaints.length, `no complaint for ${recipient}`).toBeGreaterThan(0);
3053
4087
  }),
3054
4088
  CASE_MS
3055
4089
  );
@@ -3058,7 +4092,7 @@ function runEmailFeedbackContract(name, build, options) {
3058
4092
  }
3059
4093
 
3060
4094
  // src/shipping-tracking.ts
3061
- import { describe as describe17, expect as expect18, it as it18 } from "vitest";
4095
+ import { describe as describe18, expect as expect19, it as it19 } from "vitest";
3062
4096
  import {
3063
4097
  normaliseTrackingNumber,
3064
4098
  shippingTrackingProblem,
@@ -3066,7 +4100,7 @@ import {
3066
4100
  webhookDeliveryProblem as webhookDeliveryProblem3
3067
4101
  } from "@nymbalhq/types";
3068
4102
  async function receive3(adapter, request) {
3069
- expect18(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
4103
+ expect19(typeof adapter.receiveWebhook, "the adapter has no receiveWebhook").toBe("function");
3070
4104
  return adapter.receiveWebhook(request.rawBody, request.headers);
3071
4105
  }
3072
4106
  function eventsFor2(delivery, type, trackingNumber) {
@@ -3089,39 +4123,39 @@ function runShippingTrackingContract(name, build, options) {
3089
4123
  shippingTrackingType(adapter.providerName),
3090
4124
  trackingNumber
3091
4125
  );
3092
- expect18(updates.length, `no tracking update for ${trackingNumber}`).toBeGreaterThan(0);
3093
- expect18(updates.map((e) => e.payload["status"])).toEqual(updates.map(() => status));
4126
+ expect19(updates.length, `no tracking update for ${trackingNumber}`).toBeGreaterThan(0);
4127
+ expect19(updates.map((e) => e.payload["status"])).toEqual(updates.map(() => status));
3094
4128
  });
3095
4129
  }
3096
- describe17(`shipping tracking contract: ${name}`, () => {
3097
- it18(
4130
+ describe18(`shipping tracking contract: ${name}`, () => {
4131
+ it19(
3098
4132
  "replay: one tracking update received twice gives one deliveryId and equal events",
3099
4133
  () => using(build, async (adapter) => {
3100
4134
  const first = await receive3(adapter, options.delivered().request);
3101
4135
  const second = await receive3(adapter, options.delivered().request);
3102
- expect18(first.verified, "the signed update was not verified").toBe(true);
3103
- expect18(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
3104
- expect18(second.deliveryId, "the same update got another deliveryId").toBe(first.deliveryId);
3105
- expect18(second.events).toEqual(first.events);
4136
+ expect19(first.verified, "the signed update was not verified").toBe(true);
4137
+ expect19(typeof first.deliveryId === "string" && first.deliveryId !== "").toBe(true);
4138
+ expect19(second.deliveryId, "the same update got another deliveryId").toBe(first.deliveryId);
4139
+ expect19(second.events).toEqual(first.events);
3106
4140
  }),
3107
4141
  CASE_MS
3108
4142
  );
3109
- it18(
4143
+ it19(
3110
4144
  "shape: every event passes the kernel's rules for this slot",
3111
4145
  () => using(build, async (adapter) => {
3112
4146
  const tracking = shippingTrackingType(adapter.providerName);
3113
4147
  for (const sample of samples) {
3114
4148
  const delivery = await receive3(adapter, sample().request);
3115
- expect18(delivery.verified, "a signed delivery was not verified").toBe(true);
3116
- expect18(
4149
+ expect19(delivery.verified, "a signed delivery was not verified").toBe(true);
4150
+ expect19(
3117
4151
  delivery.events.filter((e) => e.type === tracking).length,
3118
4152
  "the delivery carried no tracking update to check"
3119
4153
  ).toBeGreaterThan(0);
3120
- expect18(
4154
+ expect19(
3121
4155
  webhookDeliveryProblem3(adapter.providerName, adapter.producesEvents, delivery),
3122
4156
  "the kernel would refuse this delivery"
3123
4157
  ).toBeNull();
3124
- expect18(
4158
+ expect19(
3125
4159
  shippingTrackingProblem(adapter.providerName, delivery),
3126
4160
  "the kernel would refuse this delivery for the shipping slot"
3127
4161
  ).toBeNull();
@@ -3129,13 +4163,13 @@ function runShippingTrackingContract(name, build, options) {
3129
4163
  }),
3130
4164
  CASE_MS
3131
4165
  );
3132
- it18(
4166
+ it19(
3133
4167
  "classification: the delivered update is delivered for its tracking number",
3134
4168
  classifies(options.delivered, "delivered"),
3135
4169
  CASE_MS
3136
4170
  );
3137
4171
  if (options.inTransit !== void 0) {
3138
- it18(
4172
+ it19(
3139
4173
  "classification: the in-transit update is in transit for its tracking number",
3140
4174
  classifies(options.inTransit, "in_transit"),
3141
4175
  CASE_MS
@@ -3145,7 +4179,7 @@ function runShippingTrackingContract(name, build, options) {
3145
4179
  }
3146
4180
 
3147
4181
  // src/security.ts
3148
- import { describe as describe18, expect as expect19, it as it19 } from "vitest";
4182
+ import { describe as describe19, expect as expect20, it as it20 } from "vitest";
3149
4183
  var testConfig = {
3150
4184
  rateLimit: {
3151
4185
  api: { requests: 100, window: "1m", action: "block" }
@@ -3159,24 +4193,24 @@ var testConfig = {
3159
4193
  }
3160
4194
  };
3161
4195
  function runSecurityContract(name, build, options = {}) {
3162
- describe18(`SecurityAdapter contract: ${name}`, () => {
3163
- it19(
4196
+ describe19(`SecurityAdapter contract: ${name}`, () => {
4197
+ it20(
3164
4198
  "validate accepts a valid config",
3165
4199
  async () => {
3166
4200
  const adapter = await build();
3167
4201
  const result = await adapter.validate(testConfig);
3168
- expect19(typeof result.valid).toBe("boolean");
3169
- expect19(Array.isArray(result.errors)).toBe(true);
4202
+ expect20(typeof result.valid).toBe("boolean");
4203
+ expect20(Array.isArray(result.errors)).toBe(true);
3170
4204
  },
3171
4205
  CASE_MS
3172
4206
  );
3173
- it19(
4207
+ it20(
3174
4208
  "validate of empty config reports errors",
3175
4209
  async () => {
3176
4210
  const adapter = await build();
3177
4211
  const result = await adapter.validate({});
3178
4212
  if (!result.valid) {
3179
- expect19(result.errors.length).toBeGreaterThan(0);
4213
+ expect20(result.errors.length).toBeGreaterThan(0);
3180
4214
  }
3181
4215
  },
3182
4216
  CASE_MS
@@ -3191,7 +4225,7 @@ function runSecurityContract(name, build, options = {}) {
3191
4225
  }
3192
4226
 
3193
4227
  // src/projection.ts
3194
- import { describe as describe19, it as it20, expect as expect20 } from "vitest";
4228
+ import { describe as describe20, it as it21, expect as expect21 } from "vitest";
3195
4229
  function makeEvent2(id) {
3196
4230
  return {
3197
4231
  id,
@@ -3204,26 +4238,26 @@ function makeEvent2(id) {
3204
4238
  };
3205
4239
  }
3206
4240
  function runProjectionContract(opts) {
3207
- describe19("Projection idempotency contract", () => {
3208
- it20("processing the same event twice applies the mutation only once", async () => {
4241
+ describe20("Projection idempotency contract", () => {
4242
+ it21("processing the same event twice applies the mutation only once", async () => {
3209
4243
  const ctx = await opts.build();
3210
4244
  const event3 = makeEvent2("dedup-evt-001");
3211
4245
  await ctx.handle(event3);
3212
4246
  await ctx.handle(event3);
3213
- expect20(await ctx.applicationCount()).toBe(1);
4247
+ expect21(await ctx.applicationCount()).toBe(1);
3214
4248
  });
3215
- it20("distinct events each apply their mutation", async () => {
4249
+ it21("distinct events each apply their mutation", async () => {
3216
4250
  const ctx = await opts.build();
3217
4251
  await ctx.handle(makeEvent2("distinct-evt-001"));
3218
4252
  await ctx.handle(makeEvent2("distinct-evt-002"));
3219
- expect20(await ctx.applicationCount()).toBe(2);
4253
+ expect21(await ctx.applicationCount()).toBe(2);
3220
4254
  });
3221
- it20("after reprocessing a batch the count equals unique event count", async () => {
4255
+ it21("after reprocessing a batch the count equals unique event count", async () => {
3222
4256
  const ctx = await opts.build();
3223
4257
  const events = [makeEvent2("batch-001"), makeEvent2("batch-002"), makeEvent2("batch-003")];
3224
4258
  for (const e of events) await ctx.handle(e);
3225
4259
  for (const e of events) await ctx.handle(e);
3226
- expect20(await ctx.applicationCount()).toBe(3);
4260
+ expect21(await ctx.applicationCount()).toBe(3);
3227
4261
  });
3228
4262
  });
3229
4263
  }
@@ -3242,6 +4276,7 @@ var suites = {
3242
4276
  analytics: runAnalyticsContract,
3243
4277
  shipping: runShippingContract,
3244
4278
  tax: runTaxContract,
4279
+ ai: runAiContract,
3245
4280
  documentStore: runDocumentStoreContract,
3246
4281
  eventBus: runEventBusContract,
3247
4282
  media: (name, build, options = {}) => runMediaStorageContract(
@@ -3260,6 +4295,7 @@ export {
3260
4295
  adapterContext,
3261
4296
  contractSuites,
3262
4297
  matchesQuery,
4298
+ runAiContract,
3263
4299
  runAnalyticsContract,
3264
4300
  runDocumentStoreContract,
3265
4301
  runEmailContract,