@fantastic.dev/better-stripe 0.109.1 → 0.111.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 (100) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts +41 -0
  4. package/dist/client/billing/renewalAttach/internal/observation/freshActor.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js +40 -3
  6. package/dist/client/billing/renewalAttach/internal/observation/freshActor.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts +10 -1
  8. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js +162 -57
  10. package/dist/client/billing/renewalAttach/internal/observation/freshTransport.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.d.ts +14 -0
  12. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.js +109 -0
  14. package/dist/client/billing/renewalAttach/internal/observation/invoiceAuthorization.js.map +1 -0
  15. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.d.ts +20 -0
  16. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.js +176 -0
  18. package/dist/client/billing/renewalAttach/internal/observation/invoicePlan.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/observation/profile.js.map +1 -1
  20. package/dist/client/billing/renewalAttach/internal/observation/types.d.ts +1 -1
  21. package/dist/client/billing/renewalAttach/internal/observation/types.d.ts.map +1 -1
  22. package/dist/client/billing/renewalAttach/internal/observation/types.js.map +1 -1
  23. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts +24 -0
  24. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.d.ts.map +1 -1
  25. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js +1 -0
  26. package/dist/client/billing/renewalAttach/internal/operations/sourceOperations.js.map +1 -1
  27. package/dist/client/billing/renewalObservation/evidence-invoice.d.ts.map +1 -1
  28. package/dist/client/billing/renewalObservation/evidence-invoice.js +3 -0
  29. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -1
  30. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +84 -32
  31. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  32. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +42 -16
  33. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  34. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +52 -0
  35. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  36. package/dist/client/connect/payoutSyncTestHelpers.d.ts +26 -0
  37. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  38. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  39. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  40. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  41. package/dist/component/balanceFunding/queries.d.ts +1 -1
  42. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  43. package/dist/component/earnings/triggers.d.ts +44 -0
  44. package/dist/component/earnings/triggers.d.ts.map +1 -1
  45. package/dist/component/renewalWitnesses/eligibility.d.ts +36 -0
  46. package/dist/component/renewalWitnesses/eligibility.d.ts.map +1 -0
  47. package/dist/component/renewalWitnesses/eligibility.js +60 -0
  48. package/dist/component/renewalWitnesses/eligibility.js.map +1 -0
  49. package/dist/component/renewalWitnesses/protocol.d.ts +75 -0
  50. package/dist/component/renewalWitnesses/protocol.d.ts.map +1 -0
  51. package/dist/component/renewalWitnesses/protocol.js +82 -0
  52. package/dist/component/renewalWitnesses/protocol.js.map +1 -0
  53. package/dist/component/renewalWitnesses/schema.d.ts +99 -0
  54. package/dist/component/renewalWitnesses/schema.d.ts.map +1 -0
  55. package/dist/component/renewalWitnesses/schema.js +36 -0
  56. package/dist/component/renewalWitnesses/schema.js.map +1 -0
  57. package/dist/component/renewalWitnesses/source.d.ts +22 -0
  58. package/dist/component/renewalWitnesses/source.d.ts.map +1 -0
  59. package/dist/component/renewalWitnesses/source.js +108 -0
  60. package/dist/component/renewalWitnesses/source.js.map +1 -0
  61. package/dist/component/schema.d.ts +42 -16
  62. package/dist/component/schema.js +2 -0
  63. package/dist/component/schema.js.map +1 -1
  64. package/dist/component/usage/allowance.fixtures.d.ts +26 -0
  65. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  66. package/dist/component/usageCredits/accounting.fixtures.d.ts +42 -16
  67. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  68. package/dist/shared/renewalWitness.d.ts +51 -0
  69. package/dist/shared/renewalWitness.d.ts.map +1 -0
  70. package/dist/shared/renewalWitness.js +127 -0
  71. package/dist/shared/renewalWitness.js.map +1 -0
  72. package/docs/renewal-invoice-reads.md +85 -0
  73. package/docs/renewal-witness-protocol.md +88 -0
  74. package/package.json +1 -1
  75. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +69 -3
  76. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +189 -59
  77. package/src/client/billing/renewalAttach/internal/observation/invoiceActor.integration.test.ts +142 -0
  78. package/src/client/billing/renewalAttach/internal/observation/invoiceActorControls.integration.test.ts +495 -0
  79. package/src/client/billing/renewalAttach/internal/observation/invoiceAuthorization.ts +145 -0
  80. package/src/client/billing/renewalAttach/internal/observation/invoicePlan.ts +284 -0
  81. package/src/client/billing/renewalAttach/internal/observation/profile.ts +1 -1
  82. package/src/client/billing/renewalAttach/internal/observation/types.ts +7 -1
  83. package/src/client/billing/renewalAttach/internal/operations/sourceOperations.ts +30 -0
  84. package/src/client/billing/renewalAttach/internal/producer/producerConfigureWriteControls.integration.test.ts +74 -62
  85. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +158 -0
  86. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +11 -1
  87. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +4 -0
  88. package/src/client/billing/renewalObservation/evidence-invoice-identity.test.ts +13 -0
  89. package/src/client/billing/renewalObservation/evidence-invoice.ts +8 -0
  90. package/src/component/renewalOperations/configureJournal.fixtures.ts +25 -3
  91. package/src/component/renewalWitnesses/bounds.test.ts +204 -0
  92. package/src/component/renewalWitnesses/codec.test.ts +84 -0
  93. package/src/component/renewalWitnesses/controls.test.ts +250 -0
  94. package/src/component/renewalWitnesses/eligibility.ts +78 -0
  95. package/src/component/renewalWitnesses/protocol.test.ts +63 -0
  96. package/src/component/renewalWitnesses/protocol.ts +103 -0
  97. package/src/component/renewalWitnesses/schema.ts +36 -0
  98. package/src/component/renewalWitnesses/source.ts +157 -0
  99. package/src/component/schema.ts +2 -0
  100. package/src/shared/renewalWitness.ts +179 -0
@@ -0,0 +1,495 @@
1
+ import { expect, vi } from "vitest";
2
+ import {
3
+ configureAdmissionCase,
4
+ admissionControls,
5
+ } from "../test-fixtures/producerConfigureAdmission.js";
6
+ import {
7
+ observerIdentity,
8
+ authorizeObservation,
9
+ readerControls,
10
+ } from "../test-fixtures/observationReader.js";
11
+ import {
12
+ prepareInvoiceObservation,
13
+ authorizeInvoices,
14
+ invoiceControls,
15
+ } from "../test-fixtures/invoiceObservation.js";
16
+ import {
17
+ captureFreshInvoiceRenewalObservation,
18
+ captureFreshRenewalObservation,
19
+ } from "./freshActor.js";
20
+
21
+ let fetchHook: null | ((path: string, method: string) => Promise<void>) = null;
22
+ const options = {
23
+ identity: observerIdentity,
24
+ hostQuery: authorizeObservation,
25
+ hostInvoiceQuery: authorizeInvoices,
26
+ beforeFetch: async (path: string, method: string) => {
27
+ await fetchHook?.(path, method);
28
+ },
29
+ };
30
+ async function prepare(h: Parameters<typeof prepareInvoiceObservation>[0]) {
31
+ fetchHook = null;
32
+ return prepareInvoiceObservation(h);
33
+ }
34
+ type State = Awaited<ReturnType<typeof prepare>>;
35
+ type Harness = Parameters<typeof prepare>[0];
36
+ async function observe(h: Harness, state: State) {
37
+ let result: Awaited<
38
+ ReturnType<
39
+ Awaited<
40
+ ReturnType<typeof captureFreshInvoiceRenewalObservation>
41
+ >["invoke"]
42
+ >
43
+ > | null = null;
44
+ await h.inAnotherAction(async (ctx) => {
45
+ const actor = await captureFreshInvoiceRenewalObservation(h.sdk, {
46
+ actualActionCtx: ctx,
47
+ operationId: state.operationId,
48
+ parentOperationId: state.parentOperationId,
49
+ });
50
+ result = await actor.invoke();
51
+ });
52
+ // Assigned by the joined real Action continuation.
53
+ if (result === null) throw Error("NO_RESULT");
54
+ return result as Awaited<
55
+ ReturnType<
56
+ Awaited<
57
+ ReturnType<typeof captureFreshInvoiceRenewalObservation>
58
+ >["invoke"]
59
+ >
60
+ >;
61
+ }
62
+
63
+ const controls = [
64
+ "missing",
65
+ "equal",
66
+ "deleted",
67
+ "malformed",
68
+ "foreign-mode",
69
+ "foreign-account",
70
+ "foreign-body",
71
+ "foreign-parent",
72
+ "foreign-customer",
73
+ "wrong-url",
74
+ "duplicate",
75
+ "cursor-injection",
76
+ "oversize",
77
+ "empty-continuation",
78
+ "second-overflow",
79
+ "fence-drift",
80
+ "foreign-line-cursor",
81
+ "cross-invoice-line-alias",
82
+ ] as const;
83
+ for (const control of controls)
84
+ configureAdmissionCase(
85
+ "invoice acquisition refusal: " + control,
86
+ prepare,
87
+ async (h, state) => {
88
+ const before = h.calls.length;
89
+ const first = state.inventories[0];
90
+ let extra = 0;
91
+ if (control === "missing") state.reads.subscription.latest_invoice = null;
92
+ if (control === "equal")
93
+ state.reads.subscription.latest_invoice = "in_original";
94
+ if (control === "deleted")
95
+ state.reads.subscription.latest_invoice = {
96
+ id: "in_current",
97
+ object: "invoice",
98
+ deleted: true,
99
+ };
100
+ if (control === "malformed")
101
+ state.reads.subscription.latest_invoice = "in_current/../foreign";
102
+ if (control === "foreign-mode")
103
+ state.reads.subscription.latest_invoice = {
104
+ id: "in_current",
105
+ object: "invoice",
106
+ livemode: true,
107
+ };
108
+ if (control === "foreign-account")
109
+ state.reads.subscription.latest_invoice = {
110
+ id: "in_current",
111
+ object: "invoice",
112
+ customer_account: "acct_foreign",
113
+ };
114
+ if (control === "foreign-body") {
115
+ first.invoice.customer_account = "acct_foreign";
116
+ extra = 1;
117
+ }
118
+ if (control === "foreign-parent") {
119
+ first.invoice.parent.subscription_details.subscription = "sub_foreign";
120
+ extra = 1;
121
+ }
122
+ if (control === "foreign-customer") {
123
+ first.invoice.customer = "cus_foreign";
124
+ extra = 1;
125
+ }
126
+ if (control === "wrong-url") {
127
+ first.page.url = "https://foreign.test/lines";
128
+ extra = 2;
129
+ }
130
+ if (control === "duplicate") {
131
+ first.page.data.push(structuredClone(first.page.data[0]));
132
+ extra = 2;
133
+ }
134
+ if (control === "cursor-injection") {
135
+ first.page.data[0].id = "il_bad&limit=1000";
136
+ first.page.has_more = true;
137
+ extra = 2;
138
+ }
139
+ if (control === "oversize") {
140
+ first.page.data = Array.from({ length: 101 }, (_, i) => ({
141
+ ...first.page.data[0],
142
+ id: "il_" + i,
143
+ }));
144
+ extra = 2;
145
+ }
146
+ if (control === "empty-continuation") {
147
+ first.page.data = [];
148
+ first.page.has_more = true;
149
+ extra = 2;
150
+ }
151
+ if (control === "second-overflow") {
152
+ first.page.has_more = true;
153
+ h.setControlledRead(
154
+ "/v1/invoices/in_original/lines?limit=100&starting_after=il_original",
155
+ { ...first.page, data: [{ ...first.page.data[0], id: "il_next" }] },
156
+ );
157
+ extra = 3;
158
+ }
159
+ if (control === "foreign-line-cursor") {
160
+ first.page.data[0].invoice = "in_foreign";
161
+ first.page.has_more = true;
162
+ extra = 2;
163
+ }
164
+ if (control === "cross-invoice-line-alias") {
165
+ state.inventories[1].page.data[0].id = first.page.data[0].id;
166
+ extra = 4;
167
+ }
168
+ if (control === "fence-drift") {
169
+ let subs = 0;
170
+ fetchHook = async (path) => {
171
+ if (path === "/v1/subscriptions/sub_original" && ++subs === 2)
172
+ state.reads.subscription.description = "FENCE_DRIFT";
173
+ };
174
+ extra = 5;
175
+ }
176
+ const result = await observe(h, state);
177
+ expect(result.invoiceContext).toBeNull();
178
+ expect(["unavailable", "conflict"]).toContain(result.invoiceInventory);
179
+ expect(result.invoiceReason).toBeTypeOf("string");
180
+ expect(result.evidence?.invoiceEvidence.predicate).not.toBe(
181
+ "invoice_lines_correlated",
182
+ );
183
+ expect(h.calls.slice(before)).toHaveLength(6 + extra);
184
+ expect(
185
+ h.calls
186
+ .slice(before)
187
+ .every(
188
+ (c) =>
189
+ c.method === "GET" && !c.hasBody && c.idempotencyKey === null,
190
+ ),
191
+ ).toBe(true);
192
+ },
193
+ options,
194
+ );
195
+
196
+ for (const role of ["original", "both", "maximum"] as const)
197
+ configureAdmissionCase(
198
+ "bounded complete second pages: " + role,
199
+ prepare,
200
+ async (h, state) => {
201
+ const before = h.calls.length;
202
+ if (role === "maximum") {
203
+ const sub = state.reads.subscription;
204
+ for (const [owner, level] of [
205
+ [sub, "sub"],
206
+ [sub.items.data[0], "item"],
207
+ ] as const) {
208
+ const original = owner.discounts[0];
209
+ owner.discounts = Array.from({ length: 19 }, (_, i) => {
210
+ const discount = structuredClone(original);
211
+ discount.id = "di_" + level + i;
212
+ discount.source.coupon.id = "maximum-" + level + i;
213
+ h.setControlledRead(
214
+ "/v1/coupons/" + discount.source.coupon.id,
215
+ discount.source.coupon,
216
+ );
217
+ return discount;
218
+ });
219
+ }
220
+ }
221
+ for (const index of role === "original" ? [0] : [0, 1]) {
222
+ const { page, invoice } = state.inventories[index];
223
+ const line = page.data[0];
224
+ const addon = {
225
+ ...structuredClone(line),
226
+ id: "il_extra_" + index,
227
+ parent: {
228
+ type: "invoice_item_details",
229
+ subscription_item_details: null,
230
+ invoice_item_details: { invoice_item: "ii_extra" },
231
+ },
232
+ };
233
+ Object.assign(page, { has_more: true, data: [addon] });
234
+ h.setControlledRead(
235
+ `/v1/invoices/${invoice.id}/lines?limit=100&starting_after=${addon.id}`,
236
+ { ...page, has_more: false, data: [line] },
237
+ );
238
+ }
239
+ const result = await observe(h, state);
240
+ expect(result.invoiceInventory).toBe("complete");
241
+ expect(result.evidence?.invoiceEvidence.predicate).toBe(
242
+ "invoice_lines_correlated",
243
+ );
244
+ expect(result.invoiceContext?.original.linePages).toHaveLength(2);
245
+ expect(Object.isFrozen(result.invoiceContext?.original.linePages)).toBe(
246
+ true,
247
+ );
248
+ const calls = h.calls.slice(before);
249
+ expect(calls).toHaveLength(
250
+ role === "maximum" ? 51 : role === "both" ? 13 : 12,
251
+ );
252
+ expect(
253
+ calls.filter((c) => c.query.includes("starting_after")).length,
254
+ ).toBe(role === "original" ? 1 : 2);
255
+ },
256
+ options,
257
+ );
258
+
259
+ for (let denied = 1; denied <= 6; denied++)
260
+ configureAdmissionCase(
261
+ "invoice capability revocation at authorization " + denied,
262
+ prepare,
263
+ async (h, state) => {
264
+ invoiceControls.reply = (grant) =>
265
+ invoiceControls.count >= denied ? null : grant;
266
+ const before = h.calls.length;
267
+ await expect(observe(h, state)).rejects.toThrow();
268
+ expect(h.calls.slice(before)).toHaveLength(6 + denied - 1);
269
+ expect(invoiceControls.count).toBe(denied);
270
+ },
271
+ options,
272
+ );
273
+
274
+ for (const control of [
275
+ "base-revoked",
276
+ "subject",
277
+ "customer",
278
+ "revision",
279
+ "extra-field",
280
+ "expiry",
281
+ "profile-removed",
282
+ ] as const)
283
+ configureAdmissionCase(
284
+ "invoice grant guard: " + control,
285
+ prepare,
286
+ async (h, state) => {
287
+ const before = h.calls.length;
288
+ let extra = 0;
289
+ if (control === "base-revoked") {
290
+ readerControls.reply = (grant) =>
291
+ invoiceControls.count > 0 ? null : grant;
292
+ extra = 1;
293
+ }
294
+ if (control === "subject")
295
+ invoiceControls.reply = (grant) => ({
296
+ ...grant,
297
+ tokenIdentifier: "foreign",
298
+ });
299
+ if (control === "customer")
300
+ invoiceControls.reply = (grant) => ({
301
+ ...grant,
302
+ providerScope: {
303
+ ...(invoiceControls.args.providerScope as object),
304
+ customerId: "cus_foreign",
305
+ },
306
+ });
307
+ if (control === "revision") {
308
+ invoiceControls.reply = (grant) => ({
309
+ ...grant,
310
+ authorizationRevision: invoiceControls.count > 1 ? 2 : 1,
311
+ });
312
+ extra = 1;
313
+ }
314
+ if (control === "extra-field")
315
+ invoiceControls.reply = (grant) => ({ ...grant, extra: true });
316
+ if (control === "expiry") {
317
+ invoiceControls.grant.expiresAtMs = Date.now() + 100;
318
+ fetchHook = async (path) => {
319
+ if (path === "/v1/invoices/in_original")
320
+ vi.setSystemTime(Date.now() + 100);
321
+ };
322
+ extra = 1;
323
+ }
324
+ if (control === "profile-removed") {
325
+ fetchHook = async (path) => {
326
+ if (path === "/v1/invoices/in_original")
327
+ admissionControls.invoices.splice(0);
328
+ };
329
+ extra = 1;
330
+ }
331
+ await expect(observe(h, state)).rejects.toThrow();
332
+ expect(h.calls.slice(before)).toHaveLength(6 + extra);
333
+ },
334
+ options,
335
+ );
336
+
337
+ for (const revoked of [false, true])
338
+ configureAdmissionCase(
339
+ "actual invoice SDK rejection, final grant revoked=" + revoked,
340
+ prepare,
341
+ async (h, state) => {
342
+ const before = h.calls.length;
343
+ fetchHook = async (path) => {
344
+ if (path === "/v1/invoices/in_original") {
345
+ if (revoked) invoiceControls.deny = true;
346
+ throw Error("CONTROLLED_REJECT");
347
+ }
348
+ };
349
+ if (revoked) await expect(observe(h, state)).rejects.toThrow();
350
+ else {
351
+ const result = await observe(h, state);
352
+ expect(result.status).toBe("observation_provider_rejected");
353
+ expect(result.failure?.resource).toBe("invoice");
354
+ expect(result.failure?.outcome).toBe("unknown");
355
+ expect(result.history.attachmentReceipt.scheduleId).toBe(
356
+ "sub_sched_owned",
357
+ );
358
+ expect(result.reads).toBeNull();
359
+ expect(result.invoiceContext).toBeNull();
360
+ }
361
+ expect(h.calls.slice(before)).toHaveLength(7);
362
+ },
363
+ options,
364
+ );
365
+
366
+ configureAdmissionCase(
367
+ "invoice grant does not expand the original base observer profile",
368
+ prepare,
369
+ async (h, state) => {
370
+ const before = h.calls.length;
371
+ await h.inAnotherAction(async (ctx) => {
372
+ const actor = await captureFreshRenewalObservation(h.sdk, {
373
+ actualActionCtx: ctx,
374
+ operationId: state.operationId,
375
+ parentOperationId: state.parentOperationId,
376
+ });
377
+ const result = await actor.invoke();
378
+ expect(
379
+ Object.prototype.hasOwnProperty.call(result, "invoiceContext"),
380
+ ).toBe(false);
381
+ expect(result.evidence?.invoiceEvidence.reason).toBe("not_supplied");
382
+ });
383
+ expect(h.calls.slice(before)).toHaveLength(6);
384
+ expect(invoiceControls.count).toBe(0);
385
+ },
386
+ options,
387
+ );
388
+
389
+ for (const mode of [
390
+ "minimal-expanded",
391
+ "full-expanded",
392
+ "decimal",
393
+ "currency",
394
+ "proration",
395
+ ] as const)
396
+ configureAdmissionCase(
397
+ "invoice wire material: " + mode,
398
+ prepare,
399
+ async (h, state) => {
400
+ const current = state.inventories[1];
401
+ if (mode === "minimal-expanded")
402
+ state.reads.subscription.latest_invoice = {
403
+ id: current.invoice.id,
404
+ object: "invoice",
405
+ };
406
+ if (mode === "full-expanded")
407
+ state.reads.subscription.latest_invoice = structuredClone(
408
+ current.invoice,
409
+ );
410
+ if (mode === "decimal") {
411
+ current.page.data[0].quantity_decimal = "3.000";
412
+ current.page.data[0].pricing.unit_amount_decimal = "2000.000000000000";
413
+ }
414
+ if (mode === "currency") current.page.data[0].currency = "eur";
415
+ if (mode === "proration")
416
+ current.page.data[0].parent.subscription_item_details.proration = true;
417
+ const result = await observe(h, state);
418
+ expect(result.invoiceInventory).toBe("complete");
419
+ expect(result.evidence?.invoiceEvidence.predicate).toBe(
420
+ mode === "currency"
421
+ ? "conflict"
422
+ : mode === "proration"
423
+ ? "unknown"
424
+ : "invoice_lines_correlated",
425
+ );
426
+ if (mode === "decimal")
427
+ expect(
428
+ result.evidence?.invoiceEvidence.current?.unitAmountDecimal,
429
+ ).toBe("2000.000000000000");
430
+ },
431
+ options,
432
+ );
433
+
434
+ configureAdmissionCase(
435
+ "invoice acquisition preserves genuine optional weekly configure acknowledgement",
436
+ (h) => {
437
+ fetchHook = null;
438
+ return prepareInvoiceObservation(h, { retained: true });
439
+ },
440
+ async (h, state) => {
441
+ const result = await observe(h, state);
442
+ expect(result.history.configureReceipt).not.toBeNull();
443
+ expect(result.evidence?.invoiceEvidence.predicate).toBe(
444
+ "invoice_lines_correlated",
445
+ );
446
+ expect(result.evidence?.currentMaterial.predicate).toBe(
447
+ "current_target_material_match",
448
+ );
449
+ expect(result.evidence?.acknowledgementEstablished).toBe(false);
450
+ },
451
+ { ...options, targetInterval: "week" },
452
+ );
453
+
454
+ configureAdmissionCase(
455
+ "one original timeout closes a hanging invoice GET and denies late release",
456
+ prepare,
457
+ async (h, state) => {
458
+ const before = h.calls.length;
459
+ let release!: () => void, notify!: () => void;
460
+ const held = new Promise<void>((resolve) => {
461
+ release = resolve;
462
+ });
463
+ const started = new Promise<void>((resolve) => {
464
+ notify = resolve;
465
+ });
466
+ fetchHook = async (path) => {
467
+ if (path === "/v1/invoices/in_original") {
468
+ notify();
469
+ await held;
470
+ }
471
+ };
472
+ await h.inAnotherAction(async (ctx) => {
473
+ const actor = await captureFreshInvoiceRenewalObservation(h.sdk, {
474
+ actualActionCtx: ctx,
475
+ operationId: state.operationId,
476
+ parentOperationId: state.parentOperationId,
477
+ });
478
+ const pending = actor.invoke();
479
+ const rejected = expect(pending).rejects.toThrow(
480
+ "OBSERVATION_HISTORY_READER_EXPIRED",
481
+ );
482
+ await started;
483
+ await vi.advanceTimersByTimeAsync(30000);
484
+ await rejected;
485
+ const authorizations = invoiceControls.count;
486
+ fetchHook = null;
487
+ release();
488
+ await vi.advanceTimersByTimeAsync(0);
489
+ expect(invoiceControls.count).toBe(authorizations);
490
+ await expect(actor.invoke()).rejects.toThrow();
491
+ });
492
+ expect(h.calls.slice(before)).toHaveLength(7);
493
+ },
494
+ options,
495
+ );
@@ -0,0 +1,145 @@
1
+ import { types } from "node:util";
2
+ import { getFunctionAddress } from "convex/server";
3
+ import {
4
+ COMPILED_INVOICE_OBSERVATION_ENTRIES,
5
+ COMPILED_FRESH_OBSERVATION_ENTRIES,
6
+ type InvoiceObservationProfile,
7
+ type InvoiceAuthorizationArgs,
8
+ } from "../operations/sourceOperations.js";
9
+ import {
10
+ readMaintainedRootComponent,
11
+ readCheckedJournalActionRPC,
12
+ } from "../producer/classOwnedActionRoot.js";
13
+ import { readObservationInvocation } from "./invocation.js";
14
+ import { closed, freeze } from "../c10/ownData.js";
15
+ import {
16
+ captureReaderQueryDATA,
17
+ readerNeed as need,
18
+ readerText as text,
19
+ } from "./readerAuthorization.js";
20
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
21
+ import type { createInvoiceReadPlan } from "./invoicePlan.js";
22
+
23
+ export function invoiceProfileGuard(profile: InvoiceObservationProfile) {
24
+ need(!types.isProxy(profile));
25
+ closed(profile, ["freshProfile", "readProfile", "authorizationQuery"]);
26
+ need(
27
+ Object.isFrozen(profile) &&
28
+ profile.readProfile === "endive-pinned-invoices-fence-7-v1" &&
29
+ COMPILED_INVOICE_OBSERVATION_ENTRIES.includes(profile),
30
+ );
31
+ need(
32
+ COMPILED_INVOICE_OBSERVATION_ENTRIES.filter(
33
+ (p) => p.freshProfile === profile.freshProfile,
34
+ ).length === 1 &&
35
+ COMPILED_FRESH_OBSERVATION_ENTRIES.includes(profile.freshProfile),
36
+ );
37
+ // Maintained Convex api/internal references are proxies. The fixed Source
38
+ // association and captured semantic address bind this reference instead.
39
+ }
40
+ export function captureInvoiceObservationProfile(root: object) {
41
+ if (COMPILED_INVOICE_OBSERVATION_ENTRIES.length === 0)
42
+ throw Error("INVOICE_OBSERVATION_UNBOUND");
43
+ const component = readMaintainedRootComponent(root);
44
+ const entries = COMPILED_INVOICE_OBSERVATION_ENTRIES.filter((p) => {
45
+ need(!types.isProxy(p));
46
+ closed(p, ["freshProfile", "readProfile", "authorizationQuery"]);
47
+ return p.freshProfile.historyEntry.component === component;
48
+ });
49
+ need(entries.length === 1);
50
+ invoiceProfileGuard(entries[0]);
51
+ return entries[0];
52
+ }
53
+ /** Independent fixed invoice capability. No caller-supplied reference or grant. */
54
+ export function createInvoiceAuthorization(
55
+ token: object,
56
+ profile: InvoiceObservationProfile,
57
+ pins: ReturnType<typeof createInvoiceReadPlan>["pins"],
58
+ ) {
59
+ const state = readObservationInvocation(token),
60
+ captured = state.readCaptured();
61
+ need(profile.freshProfile.historyEntry === state.historyEntry);
62
+ const query = profile.authorizationQuery;
63
+ const address = JSON.stringify(getFunctionAddress(query));
64
+ const rpc = readCheckedJournalActionRPC(state.binding);
65
+ const base = captured.authorization;
66
+ const args: InvoiceAuthorizationArgs = freeze({
67
+ capability: "renewal_invoice_evidence_v1",
68
+ componentScope: base.componentScope,
69
+ parentOperationId: base.parentOperationId,
70
+ operationId: base.operationId,
71
+ providerScope: { ...base.providerScope, customerId: pins.customerId },
72
+ originalInvoiceId: pins.originalInvoiceId,
73
+ currentInvoiceId: pins.currentInvoiceId,
74
+ });
75
+ let grant: ReturnType<
76
+ typeof captureReaderQueryDATA<Record<string, unknown>>
77
+ > | null = null;
78
+ let expiresAt: number | null = null;
79
+ function guard() {
80
+ state.guard();
81
+ invoiceProfileGuard(profile);
82
+ need(
83
+ profile.authorizationQuery === query &&
84
+ JSON.stringify(getFunctionAddress(query)) === address,
85
+ );
86
+ need(readCheckedJournalActionRPC(state.binding) === rpc);
87
+ if (expiresAt !== null) need(state.check().wallMs < expiresAt);
88
+ }
89
+ return Object.freeze({
90
+ guard,
91
+ async authorize() {
92
+ guard();
93
+ await state.authorizeUnchanged();
94
+ guard();
95
+ const raw: unknown = await state.owned(
96
+ () => rpc.runQuery.call(rpc.receiver, query, args),
97
+ guard,
98
+ );
99
+ const reply = captureReaderQueryDATA(raw);
100
+ const data = closed(reply, [
101
+ "capability",
102
+ "componentScope",
103
+ "parentOperationId",
104
+ "operationId",
105
+ "providerScope",
106
+ "originalInvoiceId",
107
+ "currentInvoiceId",
108
+ "tokenIdentifier",
109
+ "authorizationId",
110
+ "authorizationRevision",
111
+ "expiresAtMs",
112
+ ]);
113
+ matchConfigureDATA(
114
+ {
115
+ capability: data.capability,
116
+ componentScope: data.componentScope,
117
+ parentOperationId: data.parentOperationId,
118
+ operationId: data.operationId,
119
+ providerScope: data.providerScope,
120
+ originalInvoiceId: data.originalInvoiceId,
121
+ currentInvoiceId: data.currentInvoiceId,
122
+ },
123
+ args,
124
+ );
125
+ need(data.tokenIdentifier === base.tokenIdentifier);
126
+ text(data.authorizationId);
127
+ need(
128
+ typeof data.authorizationRevision === "number" &&
129
+ Number.isSafeInteger(data.authorizationRevision) &&
130
+ data.authorizationRevision > 0,
131
+ );
132
+ need(
133
+ typeof data.expiresAtMs === "number" &&
134
+ Number.isSafeInteger(data.expiresAtMs) &&
135
+ data.expiresAtMs > state.check().wallMs,
136
+ );
137
+ if (grant) matchConfigureDATA(reply, grant);
138
+ else {
139
+ grant = data;
140
+ expiresAt = data.expiresAtMs;
141
+ }
142
+ guard();
143
+ },
144
+ });
145
+ }