@fantastic.dev/better-stripe 0.109.0 → 0.110.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 (53) 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 +4 -0
  29. package/dist/client/billing/renewalObservation/evidence-invoice.js.map +1 -1
  30. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  31. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  32. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  33. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  34. package/dist/component/balanceFunding/queries.d.ts +1 -1
  35. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  36. package/docs/renewal-invoice-reads.md +85 -0
  37. package/docs/renewal-material-observation.md +4 -1
  38. package/package.json +1 -1
  39. package/src/client/billing/renewalAttach/internal/observation/freshActor.ts +69 -3
  40. package/src/client/billing/renewalAttach/internal/observation/freshTransport.ts +189 -59
  41. package/src/client/billing/renewalAttach/internal/observation/invoiceActor.integration.test.ts +142 -0
  42. package/src/client/billing/renewalAttach/internal/observation/invoiceActorControls.integration.test.ts +495 -0
  43. package/src/client/billing/renewalAttach/internal/observation/invoiceAuthorization.ts +145 -0
  44. package/src/client/billing/renewalAttach/internal/observation/invoicePlan.ts +284 -0
  45. package/src/client/billing/renewalAttach/internal/observation/profile.ts +1 -1
  46. package/src/client/billing/renewalAttach/internal/observation/types.ts +7 -1
  47. package/src/client/billing/renewalAttach/internal/operations/sourceOperations.ts +30 -0
  48. package/src/client/billing/renewalAttach/internal/producer/producerConfigureWriteControls.integration.test.ts +74 -62
  49. package/src/client/billing/renewalAttach/internal/test-fixtures/invoiceObservation.ts +158 -0
  50. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +11 -1
  51. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +4 -0
  52. package/src/client/billing/renewalObservation/evidence-invoice-identity.test.ts +61 -0
  53. package/src/client/billing/renewalObservation/evidence-invoice.ts +9 -0
@@ -0,0 +1,284 @@
1
+ import { observationData as object } from "./types.js";
2
+ import type {
3
+ ObservationReadRow,
4
+ ObservationReads,
5
+ ObservationRecord,
6
+ } from "./types.js";
7
+ import type { InvoiceContextV1 } from "../../../renewalObservation/evidence-v1-types.js";
8
+ import { invoiceReferenceV1 } from "../../../renewalObservation/evidence-invoice-lines.js";
9
+ import { baseReadRows, validateBaseRouting } from "./profile.js";
10
+ import { matchConfigureDATA } from "../producer/configureJournalData.js";
11
+ import { captureReaderQueryDATA } from "./readerAuthorization.js";
12
+
13
+ export class InvoiceAcquisitionStop extends Error {
14
+ constructor(
15
+ readonly reason: string,
16
+ readonly kind: "unavailable" | "conflict" = "unavailable",
17
+ ) {
18
+ super(reason);
19
+ }
20
+ }
21
+ function need(
22
+ value: unknown,
23
+ reason: string,
24
+ kind: "unavailable" | "conflict" = "unavailable",
25
+ ): asserts value {
26
+ if (!value) throw new InvoiceAcquisitionStop(reason, kind);
27
+ }
28
+ function pointer(
29
+ raw: unknown,
30
+ account: string,
31
+ mode: boolean,
32
+ customer: ReturnType<typeof object>,
33
+ subscription: ReturnType<typeof object>,
34
+ ) {
35
+ need(raw !== null && raw !== undefined, "INVOICE_POINTER_UNAVAILABLE");
36
+ const id = typeof raw === "string" ? raw : object(raw).id;
37
+ need(
38
+ typeof id === "string" && id.length <= 255 && /^in_[A-Za-z0-9_]+$/.test(id),
39
+ "INVOICE_POINTER_INVALID",
40
+ );
41
+ if (typeof raw !== "string") {
42
+ const expanded = object(raw);
43
+ try {
44
+ if (Object.prototype.hasOwnProperty.call(expanded, "customer"))
45
+ invoiceReferenceV1(
46
+ expanded.customer,
47
+ String(customer.id),
48
+ "customer",
49
+ customer,
50
+ );
51
+ if (Object.prototype.hasOwnProperty.call(expanded, "parent")) {
52
+ const parent = object(expanded.parent);
53
+ need(
54
+ parent.type === "subscription_details",
55
+ "INVOICE_POINTER_SCOPE_MISMATCH",
56
+ "conflict",
57
+ );
58
+ invoiceReferenceV1(
59
+ object(parent.subscription_details).subscription,
60
+ String(subscription.id),
61
+ "subscription",
62
+ subscription,
63
+ );
64
+ }
65
+ } catch {
66
+ throw new InvoiceAcquisitionStop(
67
+ "INVOICE_POINTER_SCOPE_MISMATCH",
68
+ "conflict",
69
+ );
70
+ }
71
+ need(
72
+ expanded.object === "invoice" && expanded.deleted !== true,
73
+ "INVOICE_POINTER_INVALID",
74
+ );
75
+ need(
76
+ (!Object.prototype.hasOwnProperty.call(expanded, "customer_account") ||
77
+ expanded.customer_account === account) &&
78
+ (!Object.prototype.hasOwnProperty.call(expanded, "livemode") ||
79
+ expanded.livemode === mode),
80
+ "INVOICE_POINTER_SCOPE_MISMATCH",
81
+ "conflict",
82
+ );
83
+ }
84
+ return id;
85
+ }
86
+ /** Fixed bounded acquisition plan from already captured complete DATA, never authority. */
87
+ export function createInvoiceReadPlan(
88
+ record: ObservationRecord,
89
+ reads: ObservationReads,
90
+ startOrdinal: number,
91
+ ) {
92
+ validateBaseRouting(record, reads);
93
+ const original = object(record.originalBundle.wireSubscription),
94
+ current = object(reads.subscription);
95
+ const customer = object(reads.billingCustomer),
96
+ oldCustomer = object(record.originalBundle.wireBillingCustomer);
97
+ const scope = record.configuration.preparation.expected;
98
+ need(
99
+ typeof oldCustomer.id === "string" && customer.id === oldCustomer.id,
100
+ "INVOICE_CUSTOMER_MISMATCH",
101
+ "conflict",
102
+ );
103
+ const originalInvoiceId = pointer(
104
+ original.latest_invoice,
105
+ scope.customerAccountId,
106
+ scope.livemode,
107
+ oldCustomer,
108
+ original,
109
+ );
110
+ const currentInvoiceId = pointer(
111
+ current.latest_invoice,
112
+ scope.customerAccountId,
113
+ scope.livemode,
114
+ customer,
115
+ current,
116
+ );
117
+ need(
118
+ originalInvoiceId !== currentInvoiceId,
119
+ "invoice_relation_mismatch",
120
+ "conflict",
121
+ );
122
+ const pins = Object.freeze({
123
+ originalInvoiceId,
124
+ currentInvoiceId,
125
+ customerId: oldCustomer.id,
126
+ });
127
+ const result = [
128
+ { invoice: null as unknown, linePages: [] as unknown[] },
129
+ { invoice: null as unknown, linePages: [] as unknown[] },
130
+ ];
131
+ let role = 0,
132
+ stage: "invoice" | "lines" | "fence" | "done" = "invoice",
133
+ cursor: string | null = null,
134
+ count = 0;
135
+ const seen = new Set<string>();
136
+ const id = () => (role === 0 ? originalInvoiceId : currentInvoiceId);
137
+ function row(): ObservationReadRow {
138
+ need(stage !== "done" && count < 7, "INVOICE_READ_BUDGET");
139
+ const path = `/v1/invoices/${encodeURIComponent(id())}`;
140
+ return Object.freeze({
141
+ resource:
142
+ stage === "fence"
143
+ ? "subscription"
144
+ : stage === "invoice"
145
+ ? "invoice"
146
+ : "invoice_lines",
147
+ id: stage === "fence" ? scope.subscriptionId : id(),
148
+ ordinal: startOrdinal + count + 1,
149
+ method: "GET",
150
+ body: undefined,
151
+ path:
152
+ stage === "fence"
153
+ ? baseReadRows(record)[1].path
154
+ : stage === "invoice"
155
+ ? path
156
+ : `${path}/lines?limit=100${cursor === null ? "" : "&starting_after=" + encodeURIComponent(cursor)}`,
157
+ options: Object.freeze({
158
+ apiVersion: "2026-09-30.endive",
159
+ maxNetworkRetries: 0,
160
+ }),
161
+ });
162
+ }
163
+ function accept(raw: unknown) {
164
+ need(stage !== "done" && count++ < 7, "INVOICE_READ_BUDGET");
165
+ const body = object(raw);
166
+ if (stage === "fence") {
167
+ try {
168
+ matchConfigureDATA(body, current);
169
+ } catch {
170
+ throw new InvoiceAcquisitionStop(
171
+ "SUBSCRIPTION_FENCE_DRIFT",
172
+ "conflict",
173
+ );
174
+ }
175
+ stage = "done";
176
+ return;
177
+ }
178
+ if (stage === "invoice") {
179
+ need(
180
+ body.id === id() &&
181
+ body.object === "invoice" &&
182
+ body.deleted !== true &&
183
+ body.customer_account === scope.customerAccountId &&
184
+ body.livemode === scope.livemode,
185
+ "INVOICE_SCOPE_MISMATCH",
186
+ "conflict",
187
+ );
188
+ try {
189
+ invoiceReferenceV1(
190
+ body.customer,
191
+ pins.customerId,
192
+ "customer",
193
+ role === 0 ? oldCustomer : customer,
194
+ );
195
+ const parent = object(body.parent);
196
+ need(
197
+ parent.type === "subscription_details",
198
+ "INVOICE_SUBSCRIPTION_MISMATCH",
199
+ "conflict",
200
+ );
201
+ invoiceReferenceV1(
202
+ object(parent.subscription_details).subscription,
203
+ scope.subscriptionId,
204
+ "subscription",
205
+ role === 0 ? original : current,
206
+ );
207
+ invoiceReferenceV1(
208
+ (role === 0 ? original : current).latest_invoice,
209
+ id(),
210
+ "invoice",
211
+ body,
212
+ );
213
+ } catch (error) {
214
+ if (error instanceof InvoiceAcquisitionStop) throw error;
215
+ throw new InvoiceAcquisitionStop(
216
+ "INVOICE_RELATION_MISMATCH",
217
+ "conflict",
218
+ );
219
+ }
220
+ result[role].invoice = raw;
221
+ stage = "lines";
222
+ } else {
223
+ need(
224
+ body.object === "list" &&
225
+ body.url === `/v1/invoices/${id()}/lines` &&
226
+ typeof body.has_more === "boolean" &&
227
+ Array.isArray(body.data),
228
+ "INVOICE_LINES_INCOMPLETE",
229
+ );
230
+ const rows = body.data;
231
+ need(
232
+ rows.length <= 100 &&
233
+ !(rows.length === 0 && (body.has_more || cursor !== null)),
234
+ "INVOICE_LINES_INCOMPLETE",
235
+ );
236
+ for (const value of rows) {
237
+ const line = object(value);
238
+ need(
239
+ line.object === "line_item" && line.livemode === scope.livemode,
240
+ "INVOICE_LINE_SCOPE_MISMATCH",
241
+ "conflict",
242
+ );
243
+ try {
244
+ invoiceReferenceV1(line.invoice, id(), "invoice");
245
+ } catch {
246
+ throw new InvoiceAcquisitionStop(
247
+ "INVOICE_LINE_SCOPE_MISMATCH",
248
+ "conflict",
249
+ );
250
+ }
251
+ need(
252
+ typeof line.id === "string" &&
253
+ line.id.length <= 255 &&
254
+ /^il_[A-Za-z0-9_]+$/.test(line.id) &&
255
+ !seen.has(line.id),
256
+ "INVOICE_CURSOR_INVALID",
257
+ );
258
+ seen.add(line.id);
259
+ }
260
+ need(!(cursor !== null && body.has_more), "INVOICE_PAGE_BUDGET");
261
+ result[role].linePages.push(raw);
262
+ if (body.has_more) cursor = String(object(rows[rows.length - 1]).id);
263
+ else if (role === 0) {
264
+ role = 1;
265
+ stage = "invoice";
266
+ cursor = null;
267
+ } else stage = "fence";
268
+ }
269
+ captureReaderQueryDATA(result);
270
+ }
271
+ return Object.freeze({
272
+ pins,
273
+ row,
274
+ accept,
275
+ done: () => stage === "done",
276
+ context(): InvoiceContextV1 {
277
+ need(stage === "done", "INVOICE_LINES_INCOMPLETE");
278
+ return captureReaderQueryDATA({
279
+ original: result[0],
280
+ current: result[1],
281
+ });
282
+ },
283
+ });
284
+ }
@@ -70,7 +70,7 @@ function ids(record: ObservationRecord) {
70
70
  };
71
71
  }
72
72
  function row(
73
- resource: Resource,
73
+ resource: Exclude<Resource, "invoice" | "invoice_lines">,
74
74
  id: string,
75
75
  ordinal: number,
76
76
  ): ObservationReadRow {
@@ -25,7 +25,13 @@ export interface OwnerSample {
25
25
  readonly retired: false;
26
26
  }
27
27
  export type Resource =
28
- "schedule" | "subscription" | "price" | "customer" | "coupon";
28
+ | "schedule"
29
+ | "subscription"
30
+ | "price"
31
+ | "customer"
32
+ | "coupon"
33
+ | "invoice"
34
+ | "invoice_lines";
29
35
  export interface ObservationReadRow {
30
36
  readonly resource: Resource;
31
37
  readonly id: string;
@@ -1,10 +1,40 @@
1
1
  import type { ObservationHistorySourceEntry } from "../observation/readerAuthorization.js";
2
2
  import type { ObservationRecord } from "../observation/types.js";
3
+ import type { FunctionReference } from "convex/server";
3
4
  export type FreshObservationProfile = Readonly<{
4
5
  historyEntry: ObservationHistorySourceEntry;
5
6
  readProfile: "endive-schedule-first-44-v1";
6
7
  coversObservation(record: ObservationRecord): boolean;
7
8
  }>;
9
+ export type InvoiceAuthorizationArgs = {
10
+ capability: "renewal_invoice_evidence_v1";
11
+ componentScope: string;
12
+ parentOperationId: string;
13
+ operationId: string;
14
+ providerScope: {
15
+ mode: "platform";
16
+ stripeAccount: null;
17
+ livemode: boolean;
18
+ customerAccountId: string;
19
+ customerId: string;
20
+ subscriptionId: string;
21
+ scheduleId: string;
22
+ };
23
+ originalInvoiceId: string;
24
+ currentInvoiceId: string;
25
+ };
26
+ export type InvoiceObservationProfile = Readonly<{
27
+ freshProfile: FreshObservationProfile;
28
+ readProfile: "endive-pinned-invoices-fence-7-v1";
29
+ authorizationQuery: FunctionReference<
30
+ "query",
31
+ "public" | "internal",
32
+ InvoiceAuthorizationArgs,
33
+ unknown
34
+ >;
35
+ }>;
36
+ export const COMPILED_INVOICE_OBSERVATION_ENTRIES: readonly InvoiceObservationProfile[] =
37
+ Object.freeze([]);
8
38
  /** Fixed internal operation associations. No production producer or class is bound. */
9
39
  export const COMPILED_INITIAL_ENTRIES: readonly unknown[] = Object.freeze([]);
10
40
  export const COMPILED_RECOVERY_ENTRIES: readonly unknown[] = Object.freeze([]);
@@ -294,9 +294,10 @@ it.each(["GET", "POST"])(
294
294
  );
295
295
  },
296
296
  );
297
- it("a returned ACK reader preserves output identity and closes after observed Source pointer drift", async () => {
298
- await configureAdmissionFixture(async (h) => {
299
- const { token } = await prepare(h);
297
+ configureAdmissionCase(
298
+ "a returned ACK reader preserves output identity and closes after observed Source pointer drift",
299
+ prepare,
300
+ async (h, { token }) => {
300
301
  const output = await captureAdmittedConfigureWrite(token).invoke();
301
302
  const view = readAdmittedConfigureAcknowledgement(token);
302
303
  expect(view.output === output).toBe(true);
@@ -314,12 +315,14 @@ it("a returned ACK reader preserves output identity and closes after observed So
314
315
  admissionControls.write[0].coversConfigure = covers;
315
316
  expect(() => readAdmittedConfigureAcknowledgement(token)).toThrow();
316
317
  expect(posts(h)).toHaveLength(1);
317
- });
318
- });
319
- it("a genuine second Action context retains the original configure attempt custody", async () => {
320
- await configureAdmissionFixture(async (h) => {
321
- const { token } = await prepare(h),
322
- actor = captureAdmittedConfigureWrite(token);
318
+ },
319
+ );
320
+
321
+ configureAdmissionCase(
322
+ "a genuine second Action context retains the original configure attempt custody",
323
+ prepare,
324
+ async (h, { token }) => {
325
+ const actor = captureAdmittedConfigureWrite(token);
323
326
  await h.inAnotherAction(async () => {
324
327
  const output = await actor.invoke();
325
328
  expect(object(output).status).toBe("configure_acknowledged");
@@ -329,57 +332,65 @@ it("a genuine second Action context retains the original configure attempt custo
329
332
  });
330
333
  expect(posts(h)).toHaveLength(1);
331
334
  expect(admissionControls.legacy).toBe(0);
332
- });
333
- });
335
+ },
336
+ );
334
337
 
335
- it.each(["event-payload-alias", "changed-id", "extra-field"])(
336
- "refuses %s in the final retention readback",
337
- async (scenario) => {
338
- let childId = "",
339
- eventPayload = "",
338
+ for (const scenario of [
339
+ "event-payload-alias",
340
+ "changed-id",
341
+ "extra-field",
342
+ ] as const) {
343
+ let childId = "",
344
+ eventPayload = "",
345
+ forged = false;
346
+ configureAdmissionCase(
347
+ "refuses " + scenario + " in the final retention readback",
348
+ async (h) => {
349
+ childId = "";
350
+ eventPayload = "";
340
351
  forged = false;
341
- await configureAdmissionFixture(
342
- async (h) => {
343
- const { token, child } = await prepare(h);
344
- childId = child.created.operationId;
345
- const output = await captureAdmittedConfigureWrite(token).invoke();
346
- expect(forged).toBe(true);
347
- expect(object(output).status).toBe("configure_unknown");
348
- expect(() => readAdmittedConfigureAcknowledgement(token)).toThrow();
349
- expect(posts(h)).toHaveLength(1);
350
- },
351
- {
352
- afterQuery: async (reply, reference, args) => {
353
- if (!reply || object(args).operationId !== childId) return;
354
- const own = object(reply);
355
- if (
356
- reference.endsWith("/readAttempt") &&
357
- Array.isArray(own.events) &&
358
- own.events.length === 3
359
- ) {
360
- const payload = object(own.events[2]).payloadId;
361
- if (typeof payload === "string") eventPayload = payload;
362
- }
363
- if (
364
- reference.endsWith("/readProviderAcknowledgement") &&
365
- eventPayload &&
366
- own.retention &&
367
- typeof own.retention === "object"
368
- ) {
369
- Reflect.set(
370
- own.retention,
371
- scenario === "extra-field" ? "extra" : "receiptPayloadId",
372
- scenario === "event-payload-alias"
373
- ? eventPayload
374
- : "controlled-changed-payload",
375
- );
376
- forged = true;
377
- }
378
- },
352
+ const state = await prepare(h);
353
+ childId = state.child.created.operationId;
354
+ return state;
355
+ },
356
+ async (h, { token }) => {
357
+ const output = await captureAdmittedConfigureWrite(token).invoke();
358
+ expect(forged).toBe(true);
359
+ expect(object(output).status).toBe("configure_unknown");
360
+ expect(() => readAdmittedConfigureAcknowledgement(token)).toThrow();
361
+ expect(posts(h)).toHaveLength(1);
362
+ },
363
+ {
364
+ afterQuery: async (reply, reference, args) => {
365
+ if (!reply || object(args).operationId !== childId) return;
366
+ const own = object(reply);
367
+ if (
368
+ reference.endsWith("/readAttempt") &&
369
+ Array.isArray(own.events) &&
370
+ own.events.length === 3
371
+ ) {
372
+ const payload = object(own.events[2]).payloadId;
373
+ if (typeof payload === "string") eventPayload = payload;
374
+ }
375
+ if (
376
+ reference.endsWith("/readProviderAcknowledgement") &&
377
+ eventPayload &&
378
+ own.retention &&
379
+ typeof own.retention === "object"
380
+ ) {
381
+ Reflect.set(
382
+ own.retention,
383
+ scenario === "extra-field" ? "extra" : "receiptPayloadId",
384
+ scenario === "event-payload-alias"
385
+ ? eventPayload
386
+ : "controlled-changed-payload",
387
+ );
388
+ forged = true;
389
+ }
379
390
  },
380
- );
381
- },
382
- );
391
+ },
392
+ );
393
+ }
383
394
 
384
395
  describe("concurrent admitted children", () => {
385
396
  let pending: Promise<void>,
@@ -522,9 +533,10 @@ describe("independent SDK root lifetime", () => {
522
533
  ).toBe("configure_acknowledged");
523
534
  });
524
535
  });
525
- it("retiring one SDK root cannot close a later independent root", async () => {
526
- await configureAdmissionFixture(async (h) => {
527
- const { token } = await prepare(h);
536
+ configureAdmissionCase(
537
+ "retiring one SDK root cannot close a later independent root",
538
+ prepare,
539
+ async (h, { token }) => {
528
540
  expect(() => readAdmittedConfigureAcknowledgement(prior)).toThrow();
529
541
  const output = await captureAdmittedConfigureWrite(token).invoke();
530
542
  expect(object(output).status).toBe("configure_acknowledged");
@@ -532,6 +544,6 @@ describe("independent SDK root lifetime", () => {
532
544
  readAdmittedConfigureAcknowledgement(token).output === output,
533
545
  ).toBe(true);
534
546
  expect(() => readAdmittedConfigureAcknowledgement(prior)).toThrow();
535
- });
536
- });
547
+ },
548
+ );
537
549
  });
@@ -0,0 +1,158 @@
1
+ import { makeFunctionReference, queryGeneric } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { prepareFreshObservation } from "./freshObservation.js";
5
+ import { admissionControls } from "./producerConfigureAdmission.js";
6
+ import { observerIdentity } from "./observationReader.js";
7
+
8
+ export const invoiceControls = {
9
+ args: {} as Record<string, unknown>,
10
+ grant: {} as Record<string, unknown>,
11
+ count: 0,
12
+ deny: false,
13
+ reply: null as null | ((grant: Record<string, unknown>) => unknown),
14
+ };
15
+ export const authorizeInvoices = queryGeneric({
16
+ args: {
17
+ capability: v.literal("renewal_invoice_evidence_v1"),
18
+ componentScope: v.string(),
19
+ parentOperationId: v.string(),
20
+ operationId: v.string(),
21
+ providerScope: v.object({
22
+ mode: v.literal("platform"),
23
+ stripeAccount: v.null(),
24
+ livemode: v.boolean(),
25
+ customerAccountId: v.string(),
26
+ customerId: v.string(),
27
+ subscriptionId: v.string(),
28
+ scheduleId: v.string(),
29
+ }),
30
+ originalInvoiceId: v.string(),
31
+ currentInvoiceId: v.string(),
32
+ },
33
+ handler: async (ctx, args) => {
34
+ invoiceControls.count++;
35
+ const who = await ctx.auth.getUserIdentity();
36
+ if (
37
+ who?.tokenIdentifier !== observerIdentity.tokenIdentifier ||
38
+ invoiceControls.deny ||
39
+ !isDeepStrictEqual(args, invoiceControls.args)
40
+ )
41
+ return null;
42
+ const grant = structuredClone(invoiceControls.grant);
43
+ return invoiceControls.reply ? invoiceControls.reply(grant) : grant;
44
+ },
45
+ });
46
+ export async function prepareInvoiceObservation(
47
+ h: Parameters<typeof prepareFreshObservation>[0],
48
+ options: { retained?: boolean } = {},
49
+ ) {
50
+ const state = await prepareFreshObservation(h, {
51
+ active: true,
52
+ retained: options.retained,
53
+ });
54
+ const configuration = JSON.parse(state.full.configure.operation.recordJSON)
55
+ .configureRecord.configuration;
56
+ const old = configuration.preparation.subscription;
57
+ const current = state.reads.subscription;
58
+ current.latest_invoice = "in_current";
59
+ const line = (original: boolean) => {
60
+ const sub = original ? old : current;
61
+ const item = sub.items.data[0];
62
+ const price = item.price;
63
+ return {
64
+ id: original ? "il_original" : "il_current",
65
+ object: "line_item",
66
+ invoice: original ? "in_original" : "in_current",
67
+ livemode: false,
68
+ currency: price.currency,
69
+ parent: {
70
+ type: "subscription_item_details",
71
+ invoice_item_details: null,
72
+ subscription_item_details: {
73
+ subscription: sub.id,
74
+ subscription_item: item.id,
75
+ proration: false,
76
+ },
77
+ },
78
+ pricing: {
79
+ type: "price_details",
80
+ price_details: { price: price.id, product: price.product },
81
+ unit_amount_decimal: price.unit_amount_decimal,
82
+ },
83
+ period: {
84
+ start: item.current_period_start,
85
+ end: item.current_period_end,
86
+ },
87
+ quantity: item.quantity,
88
+ quantity_decimal: String(item.quantity),
89
+ wire_unknown: { retained: true },
90
+ };
91
+ };
92
+ const inventories = ([true, false] as const).map((original) => {
93
+ const id = original ? "in_original" : "in_current";
94
+ const invoice = {
95
+ id,
96
+ object: "invoice",
97
+ customer: "cus_buyer",
98
+ customer_account: "acct_buyer",
99
+ livemode: false,
100
+ currency: "usd",
101
+ status: "open",
102
+ billing_reason: "subscription_cycle",
103
+ parent: {
104
+ type: "subscription_details",
105
+ subscription_details: { subscription: "sub_original" },
106
+ },
107
+ wire_unknown: { retained: true },
108
+ };
109
+ const page = {
110
+ object: "list",
111
+ url: `/v1/invoices/${id}/lines`,
112
+ has_more: false,
113
+ data: [line(original)],
114
+ wire_unknown: 42,
115
+ };
116
+ h.setControlledRead(`/v1/invoices/${id}`, invoice);
117
+ h.setControlledRead(`/v1/invoices/${id}/lines`, page);
118
+ return { invoice, page };
119
+ });
120
+ invoiceControls.args = {
121
+ capability: "renewal_invoice_evidence_v1",
122
+ componentScope: state.entry.componentScope,
123
+ parentOperationId: state.parentOperationId,
124
+ operationId: state.operationId,
125
+ providerScope: {
126
+ mode: "platform",
127
+ stripeAccount: null,
128
+ livemode: false,
129
+ customerAccountId: "acct_buyer",
130
+ customerId: "cus_buyer",
131
+ subscriptionId: "sub_original",
132
+ scheduleId: "sub_sched_owned",
133
+ },
134
+ originalInvoiceId: "in_original",
135
+ currentInvoiceId: "in_current",
136
+ };
137
+ invoiceControls.grant = {
138
+ ...invoiceControls.args,
139
+ tokenIdentifier: observerIdentity.tokenIdentifier,
140
+ authorizationId: "invoice-grant",
141
+ authorizationRevision: 1,
142
+ expiresAtMs: Date.now() + 60000,
143
+ };
144
+ invoiceControls.count = 0;
145
+ invoiceControls.deny = false;
146
+ invoiceControls.reply = null;
147
+ const profile = Object.freeze({
148
+ freshProfile: state.profile,
149
+ readProfile: "endive-pinned-invoices-fence-7-v1",
150
+ authorizationQuery: makeFunctionReference("initialOwner:authorizeInvoices"),
151
+ });
152
+ admissionControls.invoices.splice(
153
+ 0,
154
+ admissionControls.invoices.length,
155
+ profile,
156
+ );
157
+ return { ...state, invoiceProfile: profile, inventories };
158
+ }