@fantastic.dev/better-stripe 0.92.0 → 0.93.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +30 -0
  4. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +113 -0
  6. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +594 -32
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +281 -0
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +594 -32
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +281 -0
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/index.d.ts +3 -2
  16. package/dist/client/index.d.ts.map +1 -1
  17. package/dist/client/index.js +16 -3
  18. package/dist/client/index.js.map +1 -1
  19. package/dist/component/_generated/api.d.ts +6 -0
  20. package/dist/component/_generated/api.d.ts.map +1 -1
  21. package/dist/component/_generated/api.js.map +1 -1
  22. package/dist/component/_generated/component.d.ts +406 -0
  23. package/dist/component/_generated/component.d.ts.map +1 -1
  24. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  25. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  26. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  27. package/dist/component/earnings/triggers.d.ts +294 -0
  28. package/dist/component/earnings/triggers.d.ts.map +1 -1
  29. package/dist/component/financialObservations/settlementHelpers.d.ts +3 -3
  30. package/dist/component/renewalOperations/helpers.d.ts +236 -0
  31. package/dist/component/renewalOperations/helpers.d.ts.map +1 -0
  32. package/dist/component/renewalOperations/helpers.js +457 -0
  33. package/dist/component/renewalOperations/helpers.js.map +1 -0
  34. package/dist/component/renewalOperations/mutations.d.ts +252 -0
  35. package/dist/component/renewalOperations/mutations.d.ts.map +1 -0
  36. package/dist/component/renewalOperations/mutations.js +340 -0
  37. package/dist/component/renewalOperations/mutations.js.map +1 -0
  38. package/dist/component/renewalOperations/queries.d.ts +163 -0
  39. package/dist/component/renewalOperations/queries.d.ts.map +1 -0
  40. package/dist/component/renewalOperations/queries.js +167 -0
  41. package/dist/component/renewalOperations/queries.js.map +1 -0
  42. package/dist/component/renewalOperations/schema.d.ts +1988 -0
  43. package/dist/component/renewalOperations/schema.d.ts.map +1 -0
  44. package/dist/component/renewalOperations/schema.js +227 -0
  45. package/dist/component/renewalOperations/schema.js.map +1 -0
  46. package/dist/component/schema.d.ts +281 -0
  47. package/dist/component/schema.js +5 -0
  48. package/dist/component/schema.js.map +1 -1
  49. package/dist/component/usage/allowance.fixtures.d.ts +281 -0
  50. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  51. package/dist/component/usageCredits/accounting.fixtures.d.ts +297 -16
  52. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  53. package/dist/shared/renewalOperationJournal.d.ts +43 -0
  54. package/dist/shared/renewalOperationJournal.d.ts.map +1 -0
  55. package/dist/shared/renewalOperationJournal.js +294 -0
  56. package/dist/shared/renewalOperationJournal.js.map +1 -0
  57. package/docs/renewal-context-reads.md +152 -0
  58. package/package.json +1 -1
  59. package/src/client/billing/renewalAttach/internal/operationJournal.integration.test.ts +380 -0
  60. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +155 -0
  61. package/src/client/index.ts +24 -3
  62. package/src/component/_generated/api.ts +6 -0
  63. package/src/component/_generated/component.ts +450 -0
  64. package/src/component/renewalOperations/acknowledgement.fixtures.ts +552 -0
  65. package/src/component/renewalOperations/acknowledgement.test.ts +573 -0
  66. package/src/component/renewalOperations/acknowledgementReads.test.ts +442 -0
  67. package/src/component/renewalOperations/acknowledgementV2.test.ts +493 -0
  68. package/src/component/renewalOperations/acknowledgementV2Publication.test.ts +373 -0
  69. package/src/component/renewalOperations/basisBinding.test.ts +567 -0
  70. package/src/component/renewalOperations/basisLifecycle.test.ts +569 -0
  71. package/src/component/renewalOperations/boundHistory.test.ts +474 -0
  72. package/src/component/renewalOperations/helpers.ts +592 -0
  73. package/src/component/renewalOperations/historyReads.test.ts +595 -0
  74. package/src/component/renewalOperations/initialBasis.test.ts +578 -0
  75. package/src/component/renewalOperations/journal.test.ts +567 -0
  76. package/src/component/renewalOperations/mutations.ts +456 -0
  77. package/src/component/renewalOperations/payload.test.ts +589 -0
  78. package/src/component/renewalOperations/payloadEncoding.test.ts +592 -0
  79. package/src/component/renewalOperations/queries.ts +204 -0
  80. package/src/component/renewalOperations/schema.ts +268 -0
  81. package/src/component/renewalOperations/timingPolicy.fixtures.ts +193 -0
  82. package/src/component/renewalOperations/timingPolicy.test.ts +523 -0
  83. package/src/component/schema.ts +11 -0
  84. package/src/shared/renewalOperationJournal.ts +333 -0
@@ -0,0 +1,567 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { getConvexSize, getDocumentSize } from "convex/values";
4
+ import { afterEach, expect, it, vi } from "vitest";
5
+ import { modules, schema } from "../../test.js";
6
+ import { renewalSnapshot } from "../../client/billing/renewalReplacementSnapshot.js";
7
+ import {
8
+ eventDigest,
9
+ materialize,
10
+ objectNode,
11
+ scalarNode,
12
+ } from "../../client/billing/renewalAttach/internal/c10/eventCodec.js";
13
+
14
+ const create = makeFunctionReference<"mutation">(
15
+ "renewalOperations/mutations:createAuthorizedOperation",
16
+ );
17
+ const reserve = makeFunctionReference<"mutation">(
18
+ "renewalOperations/mutations:reserveAttempt",
19
+ );
20
+ const load = makeFunctionReference<"query">(
21
+ "renewalOperations/queries:loadAuthorizedOperation",
22
+ );
23
+ const append = makeFunctionReference<"mutation">(
24
+ "renewalOperations/mutations:appendStageEvent",
25
+ );
26
+ const read = makeFunctionReference<"query">(
27
+ "renewalOperations/queries:readAttempt",
28
+ );
29
+
30
+ // Storage DATA only. This declaration is not a qualified C1/C2/Owner/ACK fixture.
31
+ export const originalRecord = Object.freeze({
32
+ schemaVersion: 1,
33
+ requestBinding: "journal-consistency-fixture-A",
34
+ authorization: Object.freeze({
35
+ scope: "merchant-A",
36
+ id: "consent-A",
37
+ revision: 1,
38
+ }),
39
+ logicalOperationId: "replacement-A",
40
+ stage: "attach",
41
+ account: Object.freeze({
42
+ mode: "platform",
43
+ stripeAccount: null,
44
+ livemode: false,
45
+ }),
46
+ apiVersion: "2026-09-30.endive",
47
+ profile: "renewal-fixture-no-operational-authority",
48
+ subscriptionId: "sub_A",
49
+ customerId: "cus_A",
50
+ itemId: "si_A",
51
+ currentPriceId: "price_old",
52
+ targetPriceId: "price_new",
53
+ targetProductId: "prod_new",
54
+ period: Object.freeze({ start: 2000000000, end: 2000003600 }),
55
+ dispatch: Object.freeze({
56
+ scope: "platform",
57
+ apiVersion: "2026-09-30.endive",
58
+ method: "POST",
59
+ path: "/v1/subscription_schedules",
60
+ payload: Object.freeze({ from_subscription: "sub_A" }),
61
+ key: "retained-attach-A",
62
+ firstDispatchedAt: 2000000000,
63
+ }),
64
+ options: Object.freeze({ maxNetworkRetries: 0, redirect: "error" }),
65
+ originalBundle: Object.freeze({
66
+ subscription: Object.freeze({
67
+ id: "sub_A",
68
+ schedule: null,
69
+ metadata: Object.freeze({ original: "retained" }),
70
+ }),
71
+ targetPrice: Object.freeze({ id: "price_new", product: "prod_new" }),
72
+ }),
73
+ basis: Object.freeze({
74
+ startWallMs: 2000000000000,
75
+ startNs: "1000000000",
76
+ workEndWallMs: 2000000004000,
77
+ workEndNs: "5000000000",
78
+ endWallMs: 2000000005000,
79
+ endNs: "6000000000",
80
+ }),
81
+ });
82
+ const originalJSON = JSON.stringify(renewalSnapshot(originalRecord));
83
+ const creation = Object.freeze({
84
+ authorizationScope: "merchant-A",
85
+ logicalOperationId: "replacement-A",
86
+ authorizationRevision: 1,
87
+ recordJSON: originalJSON,
88
+ });
89
+ const expectedBinding = originalRecord.requestBinding;
90
+ const failFetch = () => {
91
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
92
+ };
93
+ afterEach(() => vi.unstubAllGlobals());
94
+ function isolated() {
95
+ vi.stubGlobal("fetch", failFetch);
96
+ return convexTest(schema, modules);
97
+ }
98
+
99
+ it("J01 retains the complete original record when duplicate identity conflicts", async () => {
100
+ const t = isolated();
101
+ const created = await t.mutation(create, creation);
102
+ expect(created.status).toBe("created");
103
+ const before = await t.query(load, { operationId: created.operationId });
104
+ expect(before.recordJSON).toBe(originalJSON);
105
+ expect(before.revision).toBe(0);
106
+ const duplicate = await t.mutation(create, creation);
107
+ expect(duplicate).toEqual({
108
+ status: "existing",
109
+ operationId: created.operationId,
110
+ });
111
+ const reorderedJSON = JSON.stringify(
112
+ Object.fromEntries(Object.entries(originalRecord).reverse()),
113
+ );
114
+ expect(reorderedJSON).not.toBe(originalJSON);
115
+ expect(JSON.parse(reorderedJSON)).toEqual(originalRecord);
116
+ const reorderedDuplicate = await t.mutation(create, {
117
+ ...creation,
118
+ recordJSON: reorderedJSON,
119
+ });
120
+ expect(reorderedDuplicate).toEqual({
121
+ status: "existing",
122
+ operationId: created.operationId,
123
+ });
124
+ expect(await t.query(load, { operationId: created.operationId })).toEqual(
125
+ before,
126
+ );
127
+ const conflictingRecord = JSON.stringify(
128
+ renewalSnapshot({
129
+ ...originalRecord,
130
+ dispatch: { ...originalRecord.dispatch, key: "different-key" },
131
+ }),
132
+ );
133
+ const conflicting = await t.mutation(create, {
134
+ ...creation,
135
+ recordJSON: conflictingRecord,
136
+ });
137
+ expect(conflicting).toEqual({
138
+ status: "conflict",
139
+ reason: "identity_changed",
140
+ });
141
+ expect(await t.query(load, { operationId: created.operationId })).toEqual(
142
+ before,
143
+ );
144
+ expect(JSON.parse(before.recordJSON)).toEqual(originalRecord);
145
+ });
146
+
147
+ it("J02 concurrent PREPARED CAS has only one fresh acquired reply", async () => {
148
+ const t = isolated();
149
+ const op = await t.mutation(create, creation);
150
+ expect(op.status).toBe("created");
151
+ const retained = await t.query(load, { operationId: op.operationId });
152
+ expect(retained.recordJSON).toBe(originalJSON);
153
+ expect(retained.revision).toBe(0);
154
+ const args = {
155
+ operationId: op.operationId,
156
+ expectedRevision: 0,
157
+ stage: "attach",
158
+ expectedRequestBinding: expectedBinding,
159
+ recordJSON: originalJSON,
160
+ };
161
+ const replies = await Promise.all([
162
+ t.mutation(reserve, args),
163
+ t.mutation(reserve, args),
164
+ ]);
165
+ const acquired = replies.filter((r) => r.disposition === "acquired");
166
+ const existing = replies.filter((r) => r.disposition === "existing");
167
+ expect(acquired).toHaveLength(1);
168
+ expect(existing).toHaveLength(1);
169
+ expect(existing[0].reservation).toEqual(acquired[0].reservation);
170
+ expect(acquired[0].previousRevision).toBe(0);
171
+ expect(acquired[0].committedRevision).toBe(1);
172
+ const again = await t.mutation(reserve, args);
173
+ expect(again.disposition).toBe("existing");
174
+ expect(again.reservation).toEqual(acquired[0].reservation);
175
+ const saved = await t.query(load, { operationId: op.operationId });
176
+ expect(saved.recordJSON).toBe(originalJSON);
177
+ expect(saved.revision).toBe(1);
178
+ const { recordJSON: acquiredRecordJSON, ...expectedSummary } =
179
+ acquired[0].reservation;
180
+ expect(acquiredRecordJSON).toBe(originalJSON);
181
+ expect(Object.keys(expectedSummary)).toHaveLength(17);
182
+ expect(saved.activeAttempt).toEqual(expectedSummary);
183
+ expect(
184
+ Object.prototype.hasOwnProperty.call(saved.activeAttempt, "recordJSON"),
185
+ ).toBe(false);
186
+ expect(Object.prototype.hasOwnProperty.call(saved, "acquired")).toBe(false);
187
+ expect(
188
+ Object.prototype.hasOwnProperty.call(saved.activeAttempt, "acquired"),
189
+ ).toBe(false);
190
+ });
191
+
192
+ it.each([
193
+ [
194
+ "key",
195
+ {
196
+ ...originalRecord,
197
+ dispatch: { ...originalRecord.dispatch, key: "other" },
198
+ },
199
+ ],
200
+ [
201
+ "account",
202
+ {
203
+ ...originalRecord,
204
+ account: {
205
+ mode: "connected",
206
+ stripeAccount: "acct_other",
207
+ livemode: false,
208
+ },
209
+ },
210
+ ],
211
+ ["api", { ...originalRecord, apiVersion: "different-api" }],
212
+ ["presence", { ...originalRecord, default_settings: null }],
213
+ ])(
214
+ "J03 rejects changed complete %s before a reservation",
215
+ async (_name, changed) => {
216
+ const t = isolated();
217
+ const op = await t.mutation(create, creation);
218
+ expect(op.status).toBe("created");
219
+ const before = await t.query(load, { operationId: op.operationId });
220
+ expect(before.recordJSON).toBe(originalJSON);
221
+ expect(before.revision).toBe(0);
222
+ expect(before.activeAttempt).toBeNull();
223
+ const result = await t.mutation(reserve, {
224
+ operationId: op.operationId,
225
+ expectedRevision: 0,
226
+ stage: "attach",
227
+ expectedRequestBinding: expectedBinding,
228
+ recordJSON: JSON.stringify(renewalSnapshot(changed)),
229
+ });
230
+ expect(result).toEqual({
231
+ disposition: "conflict",
232
+ reason: "identity_changed",
233
+ });
234
+ const saved = await t.query(load, { operationId: op.operationId });
235
+ expect(saved.revision).toBe(0);
236
+ expect(saved.activeAttempt).toBeNull();
237
+ expect(saved.recordJSON).toBe(originalJSON);
238
+ expect(saved).toEqual(before);
239
+ },
240
+ );
241
+
242
+ it("J03b same complete record with wrong binding cannot acquire a reservation", async () => {
243
+ const t = isolated();
244
+ const op = await t.mutation(create, creation);
245
+ expect(op.status).toBe("created");
246
+ const before = await t.query(load, { operationId: op.operationId });
247
+ expect(before.recordJSON).toBe(originalJSON);
248
+ expect(before.revision).toBe(0);
249
+ expect(before.activeAttempt).toBeNull();
250
+ const refused = await t.mutation(reserve, {
251
+ operationId: op.operationId,
252
+ expectedRevision: 0,
253
+ stage: "attach",
254
+ expectedRequestBinding: "different-binding",
255
+ recordJSON: originalJSON,
256
+ });
257
+ expect(refused).toEqual({
258
+ disposition: "conflict",
259
+ reason: "identity_changed",
260
+ });
261
+ expect(await t.query(load, { operationId: op.operationId })).toEqual(before);
262
+ });
263
+
264
+ it("J04 stage append is idempotent and conflicting duplicate never overwrites", async () => {
265
+ const t = isolated();
266
+ const op = await t.mutation(create, creation);
267
+ expect(op.status).toBe("created");
268
+ const retained = await t.query(load, { operationId: op.operationId });
269
+ expect(retained.recordJSON).toBe(originalJSON);
270
+ expect(retained.revision).toBe(0);
271
+ expect(retained.activeAttempt).toBeNull();
272
+ const acquired = await t.mutation(reserve, {
273
+ operationId: op.operationId,
274
+ expectedRevision: 0,
275
+ stage: "attach",
276
+ expectedRequestBinding: expectedBinding,
277
+ recordJSON: originalJSON,
278
+ });
279
+ expect(acquired.disposition).toBe("acquired");
280
+ const dataNode = objectNode([
281
+ ["event", scalarNode("dispatch")],
282
+ [
283
+ "request",
284
+ objectNode([
285
+ ["scope", scalarNode(originalRecord.dispatch.scope)],
286
+ ["apiVersion", scalarNode(originalRecord.dispatch.apiVersion)],
287
+ ["method", scalarNode(originalRecord.dispatch.method)],
288
+ ["path", scalarNode(originalRecord.dispatch.path)],
289
+ [
290
+ "payload",
291
+ objectNode([
292
+ [
293
+ "from_subscription",
294
+ scalarNode(originalRecord.dispatch.payload.from_subscription),
295
+ ],
296
+ ]),
297
+ ],
298
+ ["key", scalarNode(originalRecord.dispatch.key)],
299
+ [
300
+ "firstDispatchedAt",
301
+ scalarNode(originalRecord.dispatch.firstDispatchedAt),
302
+ ],
303
+ ]),
304
+ ],
305
+ ]);
306
+ const expectedData = { event: "dispatch", request: originalRecord.dispatch };
307
+ expect(materialize(dataNode)).toEqual(expectedData);
308
+ const binding = await eventDigest(
309
+ objectNode([
310
+ ["sequence", scalarNode(1)],
311
+ ["data", dataNode],
312
+ ]),
313
+ );
314
+ expect(binding).toMatch(
315
+ /^unbound-qualification-event:v2:sha256:[0-9a-f]{64}$/,
316
+ );
317
+ const event = {
318
+ reservation: acquired.reservation,
319
+ expectedSequence: 0,
320
+ event: {
321
+ sequence: 1,
322
+ binding,
323
+ dataJSON: JSON.stringify(renewalSnapshot(expectedData)),
324
+ },
325
+ };
326
+ const first = await t.mutation(append, event);
327
+ expect(first.sequence).toBe(1);
328
+ expect(first.binding).toBe(event.event.binding);
329
+ expect(await t.mutation(append, event)).toEqual(first);
330
+ const before = await t.query(read, {
331
+ operationId: op.operationId,
332
+ attemptId: acquired.reservation.attemptId,
333
+ });
334
+ await expect(
335
+ t.mutation(append, {
336
+ ...event,
337
+ event: {
338
+ ...event.event,
339
+ dataJSON: JSON.stringify({ event: "dispatch", wrong: true }),
340
+ },
341
+ }),
342
+ ).rejects.toThrow("RENEWAL_JOURNAL_CONFLICT");
343
+ expect(
344
+ await t.query(read, {
345
+ operationId: op.operationId,
346
+ attemptId: acquired.reservation.attemptId,
347
+ }),
348
+ ).toEqual(before);
349
+ expect(before.events).toHaveLength(1);
350
+ expect(
351
+ Object.prototype.hasOwnProperty.call(before.events[0], "dataJSON"),
352
+ ).toBe(false);
353
+ const { reservation: receiptReservation, ...descriptor } = first;
354
+ expect(receiptReservation).toEqual(acquired.reservation);
355
+ expect(before.reservation).toEqual(acquired.reservation);
356
+ expect(before.events[0]).toEqual(descriptor);
357
+ });
358
+
359
+ // Genuine C9/full18/19 retention, publication failure and ancestor closure require
360
+ // the later actual-ACK fixture. No synthetic DTO is called an actual provider ACK.
361
+
362
+ // Large unqualified storage DATA: valid individual values must remain readable.
363
+ it("H01 three full events have a bounded descriptor-only history manifest", async () => {
364
+ const limit = 1048576;
365
+ const recipe = Object.freeze([1, 2, 3] as const);
366
+ const padding = "h".repeat(380000);
367
+ const events = recipe.map((sequence) =>
368
+ Object.freeze({
369
+ sequence,
370
+ data: Object.freeze({
371
+ event: "unqualified-storage-history",
372
+ sequence,
373
+ padding,
374
+ }),
375
+ }),
376
+ );
377
+ let fetchCalls = 0;
378
+ vi.stubGlobal("fetch", () => {
379
+ fetchCalls++;
380
+ throw Error("UNEXPECTED_EXTERNAL_FETCH");
381
+ });
382
+ const t = convexTest(schema, modules);
383
+ function fits(value: Parameters<typeof getConvexSize>[0]) {
384
+ expect(getConvexSize(value) <= limit).toBe(true);
385
+ }
386
+ fits(creation);
387
+ const op = await t.mutation(create, creation);
388
+ expect(op.status).toBe("created");
389
+ fits(op);
390
+ const loadArgs = { operationId: op.operationId };
391
+ fits(loadArgs);
392
+ const loaded = await t.query(load, loadArgs);
393
+ fits(loaded);
394
+ expect(loaded.recordJSON).toBe(originalJSON);
395
+ expect(loaded.revision).toBe(0);
396
+ expect(loaded.activeAttempt).toBeNull();
397
+ const reserveArgs = {
398
+ operationId: op.operationId,
399
+ expectedRevision: 0,
400
+ stage: "attach",
401
+ expectedRequestBinding: expectedBinding,
402
+ recordJSON: originalJSON,
403
+ };
404
+ fits(reserveArgs);
405
+ const acquired = await t.mutation(reserve, reserveArgs);
406
+ expect(acquired.disposition).toBe("acquired");
407
+ fits(acquired);
408
+ expect(acquired.reservation.recordJSON).toBe(originalJSON);
409
+ expect(acquired.reservation.basisJSON).toBe(
410
+ JSON.stringify(renewalSnapshot(originalRecord.basis)),
411
+ );
412
+ const readArgs = {
413
+ operationId: op.operationId,
414
+ attemptId: acquired.reservation.attemptId,
415
+ };
416
+ fits(readArgs);
417
+ const descriptors: Record<string, string | number>[] = [];
418
+ const eventJSONs: string[] = [];
419
+ for (const { sequence, data } of events) {
420
+ const dataJSON = JSON.stringify(renewalSnapshot(data));
421
+ expect(dataJSON.length <= 500000).toBe(true);
422
+ expect(new TextEncoder().encode(dataJSON).length <= 500000).toBe(true);
423
+ const node = objectNode([
424
+ ["event", scalarNode(data.event)],
425
+ ["sequence", scalarNode(sequence)],
426
+ ["padding", scalarNode(padding)],
427
+ ]);
428
+ expect(materialize(node)).toEqual(data);
429
+ const binding = await eventDigest(
430
+ objectNode([
431
+ ["sequence", scalarNode(sequence)],
432
+ ["data", node],
433
+ ]),
434
+ );
435
+ expect(binding).toMatch(
436
+ /^unbound-qualification-event:v2:sha256:[0-9a-f]{64}$/,
437
+ );
438
+ const args = {
439
+ reservation: acquired.reservation,
440
+ expectedSequence: sequence - 1,
441
+ event: { sequence, binding, dataJSON },
442
+ };
443
+ fits(args);
444
+ const receipt = await t.mutation(append, args);
445
+ fits(receipt);
446
+ expect(receipt.sequence).toBe(sequence);
447
+ expect(receipt.binding).toBe(binding);
448
+ expect(receipt.reservation).toEqual(acquired.reservation);
449
+ const { reservation: unusedReservation, ...descriptor } = receipt;
450
+ void unusedReservation;
451
+ descriptors.push(descriptor);
452
+ eventJSONs.push(dataJSON);
453
+ if (sequence < 3) {
454
+ const prior = await t.query(read, readArgs);
455
+ fits(prior);
456
+ expect(prior.reservation).toEqual(acquired.reservation);
457
+ expect(
458
+ prior.events.map((event: { sequence: number }) => event.sequence),
459
+ ).toEqual(recipe.slice(0, sequence));
460
+ }
461
+ }
462
+ // Each physical read returns a bounded value. Payload JSONs are joined only
463
+ // in test memory; no prerequisite returns all large payloads in one RPC.
464
+ async function physical() {
465
+ const operations = await t.run((ctx) =>
466
+ ctx.db.query("renewalOperations").take(3),
467
+ );
468
+ const attempts = await t.run((ctx) =>
469
+ ctx.db.query("renewalOperationAttempts").take(3),
470
+ );
471
+ const storedEvents = await t.run((ctx) =>
472
+ ctx.db.query("renewalOperationEvents").take(4),
473
+ );
474
+ const payloadIds = await t.run(async (ctx) =>
475
+ (await ctx.db.query("renewalOperationPayloads").take(5)).map(
476
+ (row) => row._id,
477
+ ),
478
+ );
479
+ for (const reply of [operations, attempts, storedEvents, payloadIds])
480
+ fits(reply);
481
+ const payloads = [];
482
+ for (const id of payloadIds) {
483
+ const row = await t.run((ctx) =>
484
+ ctx.db.get("renewalOperationPayloads", id),
485
+ );
486
+ expect(row).not.toBeNull();
487
+ if (!row) throw Error("HISTORY_PAYLOAD_MISSING");
488
+ fits(row);
489
+ expect(getDocumentSize(row) <= limit).toBe(true);
490
+ payloads.push(row);
491
+ }
492
+ for (const row of [...operations, ...attempts, ...storedEvents])
493
+ expect(getDocumentSize(row) <= limit).toBe(true);
494
+ expect(operations).toHaveLength(1);
495
+ expect(attempts).toHaveLength(1);
496
+ expect(storedEvents).toHaveLength(3);
497
+ expect(payloads).toHaveLength(4);
498
+ expect(operations[0].state).toBe("RESERVED");
499
+ expect(operations[0].revision).toBe(1);
500
+ expect(attempts[0].lastSequence).toBe(3);
501
+ expect(
502
+ payloads.find((row) => row._id === acquired.reservation.payloadId)?.json,
503
+ ).toBe(originalJSON);
504
+ for (let index = 0; index < descriptors.length; index++) {
505
+ const descriptor = descriptors[index];
506
+ const row = storedEvents.find(
507
+ (candidate) => candidate._id === descriptor.eventId,
508
+ );
509
+ expect(row).toBeDefined();
510
+ if (!row) throw Error("HISTORY_EVENT_MISSING");
511
+ const { _id, _creationTime, ...fields } = row;
512
+ void _creationTime;
513
+ expect({ ...fields, eventId: _id }).toEqual(descriptor);
514
+ expect(row.sequence).toBe(index + 1);
515
+ expect(
516
+ payloads.find((payload) => payload._id === descriptor.payloadId)
517
+ ?.json === eventJSONs[index],
518
+ ).toBe(true);
519
+ }
520
+ return { operations, attempts, storedEvents, payloads };
521
+ }
522
+ const before = await physical();
523
+ const oldFullShape = {
524
+ reservation: acquired.reservation,
525
+ events: descriptors.map((descriptor, index) => ({
526
+ ...descriptor,
527
+ dataJSON: eventJSONs[index],
528
+ })),
529
+ };
530
+ const oldFullBytes = getConvexSize(oldFullShape);
531
+ expect(oldFullBytes > limit).toBe(true);
532
+ let status = "unsettled";
533
+ let resultBytes = -1;
534
+ try {
535
+ const manifest = await t.query(read, readArgs);
536
+ status = "fulfilled";
537
+ resultBytes = getConvexSize(manifest);
538
+ expect(resultBytes <= limit).toBe(true);
539
+ expect(manifest.reservation).toEqual(acquired.reservation);
540
+ expect(manifest.events).toEqual(descriptors);
541
+ expect(
542
+ manifest.events.every(
543
+ (event: object) =>
544
+ !Object.prototype.hasOwnProperty.call(event, "dataJSON"),
545
+ ),
546
+ ).toBe(true);
547
+ } catch (error) {
548
+ if (status === "unsettled") status = "rejected";
549
+ throw error;
550
+ } finally {
551
+ const after = await physical();
552
+ const unchanged = JSON.stringify(after) === JSON.stringify(before);
553
+ console.info(
554
+ "HISTORY_MANIFEST",
555
+ JSON.stringify({
556
+ status,
557
+ resultBytes,
558
+ oldFullBytes,
559
+ unchanged,
560
+ events: 3,
561
+ fetchCalls,
562
+ }),
563
+ );
564
+ expect(unchanged).toBe(true);
565
+ expect(fetchCalls).toBe(0);
566
+ }
567
+ });