@voltro/plugin-billing 0.89.2 → 0.91.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 (40) hide show
  1. package/CHANGELOG.md +1943 -0
  2. package/README.md +0 -435
  3. package/THIRD-PARTY-NOTICES.md +22 -646
  4. package/dist/catalog.js +169 -70
  5. package/dist/custodyInventory.js +101 -65
  6. package/dist/dunning.js +14 -6
  7. package/dist/eventDelivery.js +14 -5
  8. package/dist/historicalUsage.js +94 -0
  9. package/dist/index.d.ts +777 -68
  10. package/dist/index.js +354 -233
  11. package/dist/invoiceHistoryJournal.js +204 -179
  12. package/dist/invoiceHistoryProgress.js +130 -106
  13. package/dist/invoiceHistoryWork.js +188 -186
  14. package/dist/invoicePaymentEpoch.js +145 -0
  15. package/dist/invoicePaymentObservation.js +64 -0
  16. package/dist/invoiceSnapshot.js +56 -46
  17. package/dist/invoiceStore.js +124 -90
  18. package/dist/paidInvoiceCoverage.js +84 -0
  19. package/dist/plans.js +15 -2
  20. package/dist/providers.js +149 -92
  21. package/dist/provision.js +84 -73
  22. package/dist/rpc.d.ts +53 -13
  23. package/dist/rpc.js +141 -78
  24. package/dist/service.js +1208 -722
  25. package/dist/stores.js +240 -148
  26. package/dist/stripeIdentity.js +17 -17
  27. package/dist/stripeInvoiceHistory.js +21 -21
  28. package/dist/stripeInvoicePayments.js +129 -0
  29. package/dist/stripeInvoiceSnapshot.js +65 -46
  30. package/dist/stripeProvider.js +570 -201
  31. package/dist/stripeRest.js +10 -10
  32. package/dist/subscriptionObservation.js +93 -0
  33. package/dist/subscriptionWriteStore.js +325 -0
  34. package/dist/table.js +75 -66
  35. package/dist/types.d.ts +415 -27
  36. package/dist/types.js +21 -4
  37. package/dist/web/index.d.ts +93 -3
  38. package/dist/web/index.js +76 -33
  39. package/dist/web/writeRequest.js +65 -0
  40. package/package.json +9 -9
@@ -1,16 +1,16 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { invoiceHistoryPreview as t } from "./invoiceHistory.js";
3
- import { Stripe as n, makeStripeClient as r, periodOf as i, quantityOf as a, stripeCall as o, unixToDate as s } from "./stripeClient.js";
4
- import { stripeInvoiceSnapshot as c } from "./stripeInvoiceSnapshot.js";
5
- import { stripeAccountIdentity as l, stripeCustomerSnapshot as u } from "./stripeIdentity.js";
6
- import { stripeInvoiceHistory as d } from "./stripeInvoiceHistory.js";
2
+ import { Stripe as t, makeStripeClient as n, periodOf as r, quantityOf as i, stripeCall as a, unixToDate as o } from "./stripeClient.js";
3
+ import { stripeInvoiceSnapshot as s } from "./stripeInvoiceSnapshot.js";
4
+ import { stripeInvoiceHistory as c } from "./stripeInvoiceHistory.js";
5
+ import { invoiceHistoryPreview as l } from "./invoiceHistory.js";
6
+ import { stripeAccountIdentity as u, stripeCustomerSnapshot as d } from "./stripeIdentity.js";
7
7
  import { verifyStripeBillingEvent as f } from "./stripeVerifiedEvent.js";
8
8
  import { Effect as p } from "effect";
9
9
  // src/stripeProvider.ts
10
- var m = async (e) => {
10
+ var m = async (e) => [...new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(e)))].map((e) => e.toString(16).padStart(2, "0")).join(""), h = async (e) => {
11
11
  let t = e ?? globalThis.crypto.randomUUID();
12
12
  return "voltro-billing-" + [...new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(t))).slice(0, 8)].map((e) => String.fromCharCode(97 + e % 26)).join("");
13
- }, h = (e) => {
13
+ }, g = (e) => {
14
14
  let t = e.status === "open" ? "open" : e.status === "complete" ? "complete" : e.status === "expired" ? "expired" : null;
15
15
  if (t === null) throw Error("Checkout provider status is unavailable.");
16
16
  let n = /* @__PURE__ */ new Date(e.expires_at * 1e3);
@@ -25,7 +25,11 @@ var m = async (e) => {
25
25
  url: e.url,
26
26
  expiresAt: n
27
27
  };
28
- }, g = {
28
+ }, _ = (e) => {
29
+ if (!(e instanceof t.errors.StripeInvalidRequestError || e instanceof t.errors.StripeCardError || e instanceof t.errors.StripePermissionError || e instanceof t.errors.StripeAuthenticationError)) return null;
30
+ let n = typeof e.code == "string" && /^[a-z0-9_]{1,80}$/.test(e.code) ? ` (${e.code})` : "";
31
+ return (/^[A-Za-z_]{1,80}$/.test(e.type) ? e.type : "StripeError") + n;
32
+ }, v = {
29
33
  active: "active",
30
34
  trialing: "trialing",
31
35
  past_due: "pastDue",
@@ -34,23 +38,55 @@ var m = async (e) => {
34
38
  incomplete: "incomplete",
35
39
  incomplete_expired: "canceled",
36
40
  paused: "pastDue"
37
- }, _ = (e) => {
41
+ }, y = (e) => {
38
42
  let t = e.metadata?.tenantId;
39
43
  if (typeof t == "string" && t.length > 0) return t;
40
44
  let n = e.client_reference_id;
41
45
  return typeof n == "string" && n.length > 0 ? n : null;
42
- }, v = (e) => {
43
- let t = e.items?.data ?? [];
44
- return t.find((e) => e.price?.recurring?.usage_type !== "metered") ?? t[0];
45
- }, y = (e) => {
46
- let t = v(e)?.price;
47
- return typeof t?.id == "string" ? t.id : null;
48
- }, b = (e) => typeof e == "string" ? e : typeof e?.id == "string" ? e.id : null, x = (e, t) => {
49
- let n = y(e), r = n !== null && t ? t(n) : null;
50
- if (r !== null) return r;
51
- let i = e.metadata?.plan;
52
- return typeof i == "string" && i.length > 0 ? i : null;
53
- }, S = [
46
+ }, b = (e) => (e.items?.data ?? []).filter((e) => e.price?.recurring?.usage_type !== "metered"), x = (e, t) => {
47
+ let n = e.items?.data ?? [], r = b(e), i = new Set(r.flatMap((e) => {
48
+ let n = typeof e.price?.id == "string" ? t?.(e.price.id) : null;
49
+ return n ? [n.seatPriceId] : [];
50
+ }));
51
+ return r.find((e) => !i.has(e.price?.id)) ?? n[0];
52
+ }, S = (e, t) => {
53
+ let n = x(e, t)?.price;
54
+ return typeof n?.id == "string" ? n.id : null;
55
+ }, C = (e, t) => {
56
+ let n = S(e, t), r = n === null ? null : t?.(n) ?? null;
57
+ return {
58
+ pricing: r,
59
+ item: r === null ? void 0 : b(e).find((e) => e.price?.id === r.seatPriceId)
60
+ };
61
+ }, w = (e, t) => {
62
+ let { pricing: n, item: r } = C(e, t);
63
+ return n === null ? i(e) : n.includedSeats + (r?.quantity ?? 0);
64
+ }, T = (e) => typeof e == "string" ? e : typeof e?.id == "string" ? e.id : null, E = (e, t, n) => {
65
+ let r = S(e, n), i = r !== null && t ? t(r) : null;
66
+ if (i !== null) return i;
67
+ let a = e.metadata?.plan;
68
+ return typeof a == "string" && a.length > 0 ? a : null;
69
+ }, D = [
70
+ "charge.captured",
71
+ "charge.refunded",
72
+ "charge.updated",
73
+ "charge.dispute.created",
74
+ "charge.dispute.updated",
75
+ "charge.dispute.closed",
76
+ "charge.dispute.funds_reinstated",
77
+ "charge.dispute.funds_withdrawn",
78
+ "refund.created",
79
+ "refund.updated",
80
+ "refund.failed",
81
+ "credit_note.created",
82
+ "credit_note.updated",
83
+ "credit_note.voided",
84
+ "invoice.updated",
85
+ "invoice.deleted",
86
+ "invoice.voided",
87
+ "invoice.marked_uncollectible",
88
+ "invoice_payment.paid"
89
+ ], O = [
54
90
  "checkout.session.completed",
55
91
  "customer.created",
56
92
  "customer.deleted",
@@ -60,176 +96,491 @@ var m = async (e) => {
60
96
  "customer.subscription.resumed",
61
97
  "customer.subscription.updated",
62
98
  "invoice.paid",
63
- "invoice.payment_failed"
64
- ], C = (t, n) => {
65
- let r = s(t.created);
99
+ "invoice.payment_failed",
100
+ ...D
101
+ ], k = (t, n, i) => {
102
+ let a = o(t.created);
66
103
  switch (t.type) {
67
104
  case "customer.subscription.created":
68
105
  case "customer.subscription.updated":
69
106
  case "customer.subscription.resumed":
70
107
  case "customer.subscription.paused": {
71
- let e = t.data.object, o = _(e), c = x(e, n), l = g[e.status];
72
- if (o === null || c === null || l === void 0) return null;
73
- let u = i(e);
108
+ let e = t.data.object, s = y(e), c = E(e, n, i), l = v[e.status];
109
+ if (s === null || c === null || l === void 0) return null;
110
+ let u = r(e);
74
111
  return {
75
112
  _tag: "subscriptionUpserted",
76
- tenantId: o,
113
+ tenantId: s,
77
114
  providerSubscriptionId: e.id,
78
115
  plan: c,
79
116
  status: l,
80
- quantity: a(e),
117
+ quantity: w(e, i),
81
118
  currentPeriodStart: u.start,
82
119
  currentPeriodEnd: u.end,
83
- cancelAt: s(e.cancel_at),
84
- occurredAt: r
120
+ cancelAt: o(e.cancel_at),
121
+ occurredAt: a
85
122
  };
86
123
  }
87
124
  case "customer.subscription.deleted": {
88
- let e = t.data.object, n = _(e);
125
+ let e = t.data.object, n = y(e);
89
126
  return n === null ? null : {
90
127
  _tag: "subscriptionCanceled",
91
128
  tenantId: n,
92
129
  providerSubscriptionId: e.id,
93
- occurredAt: r
130
+ occurredAt: a
94
131
  };
95
132
  }
96
133
  case "invoice.paid":
97
134
  case "invoice.payment_failed": {
98
- let n = t.data.object, i = D(n);
99
- if (i === null || i.length === 0 || typeof n.id != "string" || n.id.length === 0) throw new e({
135
+ let n = t.data.object, r = G(n);
136
+ if (r === null || r.length === 0 || typeof n.id != "string" || n.id.length === 0) throw new e({
100
137
  source: "stripe.normalizeEvent",
101
138
  message: "The invoice trigger requires exact customer and invoice identities.",
102
139
  transient: !1
103
140
  });
104
141
  return {
105
142
  _tag: t.type === "invoice.paid" ? "invoicePaid" : "invoicePaymentFailed",
106
- providerCustomerId: i,
143
+ providerCustomerId: r,
107
144
  providerInvoiceId: n.id,
108
145
  amountMinor: n.amount_due,
109
146
  currency: n.currency,
110
- occurredAt: r
147
+ occurredAt: a
111
148
  };
112
149
  }
113
150
  case "checkout.session.completed": {
114
- let e = t.data.object, n = _(e), i = b(e.customer);
115
- return n === null || i === null ? null : {
151
+ let e = t.data.object, n = y(e), r = T(e.customer);
152
+ return n === null || r === null ? null : {
116
153
  _tag: "customerLinked",
117
154
  tenantId: n,
118
- providerCustomerId: i,
119
- occurredAt: r
155
+ providerCustomerId: r,
156
+ occurredAt: a
120
157
  };
121
158
  }
122
159
  case "customer.deleted": {
123
160
  let e = t.data.object;
124
161
  return {
125
162
  _tag: "customerUnlinked",
126
- tenantId: _(e),
163
+ tenantId: y(e),
127
164
  providerCustomerId: e.id,
128
- occurredAt: r
165
+ occurredAt: a
129
166
  };
130
167
  }
131
168
  case "customer.created": {
132
- let e = t.data.object, n = _(e);
169
+ let e = t.data.object, n = y(e);
133
170
  return n === null ? null : {
134
171
  _tag: "customerLinked",
135
172
  tenantId: n,
136
173
  providerCustomerId: e.id,
137
- occurredAt: r
174
+ occurredAt: a
138
175
  };
139
176
  }
177
+ case "charge.captured":
178
+ case "charge.refunded":
179
+ case "charge.updated":
180
+ case "credit_note.created":
181
+ case "credit_note.updated":
182
+ case "credit_note.voided":
183
+ case "invoice.updated":
184
+ case "invoice.deleted":
185
+ case "invoice.voided":
186
+ case "invoice.marked_uncollectible": return A(G(t.data.object), a);
140
187
  default: return null;
141
188
  }
142
- }, w = {
189
+ }, A = (t, n) => {
190
+ if (typeof t != "string" || !t || t.length > 191 || t.trim() !== t) throw new e({
191
+ source: "stripe.normalizeEvent",
192
+ message: "The payment correction requires an exact customer identity.",
193
+ transient: !1
194
+ });
195
+ return {
196
+ _tag: "invoicePaymentsCorrected",
197
+ providerCustomerId: t,
198
+ occurredAt: n
199
+ };
200
+ }, j = (t, n, r, i) => p.gen(function* () {
201
+ let s = yield* p.try({
202
+ try: () => k(n, r, i),
203
+ catch: (t) => t instanceof e ? t : new e({
204
+ source: "stripe.normalizeEvent",
205
+ message: "The provider event could not be normalized.",
206
+ transient: !1
207
+ })
208
+ });
209
+ if (s !== null || !D.includes(n.type)) return s;
210
+ let c = yield* u(t);
211
+ if (n.livemode !== c.livemode || n.account !== void 0 && n.account !== null && n.account !== c.providerAccountId) return yield* p.fail(new e({
212
+ source: "stripe.normalizeEvent",
213
+ message: "The payment correction belongs to another Stripe account or mode.",
214
+ transient: !1
215
+ }));
216
+ let l = null;
217
+ switch (n.type) {
218
+ case "charge.dispute.created":
219
+ case "charge.dispute.updated":
220
+ case "charge.dispute.closed":
221
+ case "charge.dispute.funds_reinstated":
222
+ case "charge.dispute.funds_withdrawn":
223
+ case "refund.created":
224
+ case "refund.updated":
225
+ case "refund.failed": {
226
+ let r = T(n.data.object.charge);
227
+ if (r === null) return yield* p.fail(new e({
228
+ source: "stripe.normalizeEvent",
229
+ message: "The payment correction has no original charge identity.",
230
+ transient: !1
231
+ }));
232
+ let i = yield* a("stripe.charges.retrieve", () => t.charges.retrieve(r));
233
+ if (i.id !== r || i.livemode !== c.livemode) return yield* p.fail(new e({
234
+ source: "stripe.normalizeEvent",
235
+ message: "The original correction charge could not be confirmed.",
236
+ transient: !1
237
+ }));
238
+ l = T(i.customer);
239
+ break;
240
+ }
241
+ case "invoice_payment.paid": {
242
+ let r = T(n.data.object.invoice);
243
+ if (r === null) return yield* p.fail(new e({
244
+ source: "stripe.normalizeEvent",
245
+ message: "The payment allocation has no invoice identity.",
246
+ transient: !1
247
+ }));
248
+ let i = yield* a("stripe.invoices.retrieve", () => t.invoices.retrieve(r));
249
+ if (i.id !== r || i.livemode !== c.livemode) return yield* p.fail(new e({
250
+ source: "stripe.normalizeEvent",
251
+ message: "The payment allocation invoice could not be confirmed.",
252
+ transient: !1
253
+ }));
254
+ l = T(i.customer);
255
+ break;
256
+ }
257
+ default: return yield* p.fail(new e({
258
+ source: "stripe.normalizeEvent",
259
+ message: "The correction join is unsupported.",
260
+ transient: !1
261
+ }));
262
+ }
263
+ let d = yield* u(t);
264
+ return d.providerAccountId !== c.providerAccountId || d.livemode !== c.livemode ? yield* p.fail(new e({
265
+ source: "stripe.normalizeEvent",
266
+ message: "The Stripe account changed during payment correction discovery.",
267
+ transient: !0
268
+ })) : yield* p.try({
269
+ try: () => A(l, o(n.created)),
270
+ catch: (t) => t instanceof e ? t : new e({
271
+ source: "stripe.normalizeEvent",
272
+ message: "The correction customer could not be confirmed.",
273
+ transient: !1
274
+ })
275
+ });
276
+ }), M = {
143
277
  prorate: "create_prorations",
144
278
  none: "none",
145
279
  always_invoice: "always_invoice"
146
- }, T = (y) => {
147
- let T = r(y), A = y.planForPriceId, j = (e) => {
148
- let t = i(e);
280
+ }, N = [
281
+ "day",
282
+ "week",
283
+ "month",
284
+ "year"
285
+ ], P = (e) => N.includes(e) ? e : null, F = (e) => e === "graduated" || e === "volume" ? e : null, I = (e) => e === "licensed" || e === "metered" ? e : null, L = 10, R = 8, z = 10, B = "voltro_usage_key", V = (e) => e === "inclusive" || e === "exclusive" || e === "unspecified" ? e : null, H = (e) => {
286
+ let t = e.billing_scheme === "tiered" && Array.isArray(e.tiers);
287
+ return {
288
+ id: e.id,
289
+ active: e.active,
290
+ currency: e.currency,
291
+ unitAmountMinor: e.billing_scheme === "per_unit" && typeof e.unit_amount == "number" ? e.unit_amount : null,
292
+ tiers: t ? e.tiers.map((e) => ({
293
+ upTo: typeof e.up_to == "number" ? e.up_to : null,
294
+ unitAmountMinor: typeof e.unit_amount == "number" ? e.unit_amount : null,
295
+ unitAmountDecimal: e.unit_amount_decimal == null ? typeof e.unit_amount == "number" ? String(e.unit_amount) : null : e.unit_amount_decimal.toString(),
296
+ flatAmountMinor: typeof e.flat_amount == "number" ? e.flat_amount : null
297
+ })) : null,
298
+ tiersMode: t ? F(e.tiers_mode) : null,
299
+ interval: P(e.recurring?.interval),
300
+ usageType: I(e.recurring?.usage_type)
301
+ };
302
+ }, U = (i) => {
303
+ let b = n(i), D = i.planForPriceId, k = i.seatPricingForPriceId, A = (e) => {
304
+ let t = r(e);
149
305
  return {
150
- status: g[e.status] ?? "incomplete",
151
- plan: x(e, A),
152
- quantity: a(e),
306
+ status: v[e.status] ?? "incomplete",
307
+ plan: E(e, D, k),
308
+ quantity: w(e, k),
153
309
  currentPeriodStart: t.start,
154
310
  currentPeriodEnd: t.end,
155
- cancelAt: s(e.cancel_at)
311
+ cancelAt: o(e.cancel_at)
312
+ };
313
+ }, N = (e) => {
314
+ let t = x(e, k), n = C(e, k);
315
+ return {
316
+ ...A(e),
317
+ providerSubscriptionId: e.id,
318
+ providerCustomerId: T(e.customer),
319
+ tenantId: y(e),
320
+ writeOperationId: typeof e.metadata?.voltro_write_operation == "string" ? e.metadata.voltro_write_operation : null,
321
+ providerPlanItemId: t?.id ?? null,
322
+ providerPlanPriceId: S(e, k),
323
+ providerItemsComplete: e.items.has_more === !1,
324
+ providerLatestInvoiceId: T(e.latest_invoice),
325
+ providerPlanQuantity: t?.quantity ?? null,
326
+ providerPlanCurrency: t?.price.currency ?? null,
327
+ providerIncludedSeats: n.pricing?.includedSeats ?? null,
328
+ providerAdditionalSeatQuantity: n.pricing === null ? null : n.item?.quantity ?? 0,
329
+ providerObservedAt: (() => {
330
+ let t = e.lastResponse?.headers.date, n = typeof t == "string" ? Date.parse(t) : NaN;
331
+ return Number.isFinite(n) ? new Date(n) : null;
332
+ })(),
333
+ priceIds: (e.items?.data ?? []).map((e) => e.price?.id).filter((e) => typeof e == "string")
156
334
  };
157
- }, M = (e) => ({
158
- ...j(e),
159
- providerSubscriptionId: e.id,
160
- providerCustomerId: b(e.customer),
161
- tenantId: _(e),
162
- priceIds: (e.items?.data ?? []).map((e) => e.price?.id).filter((e) => typeof e == "string")
163
- }), N = y.closeSettleSeconds ?? 600;
164
- if (!Number.isSafeInteger(N) || N < 0) throw TypeError("closeSettleSeconds must be a nonnegative integer.");
165
- let P = (e) => {
335
+ }, P = i.closeSettleSeconds ?? 600;
336
+ if (!Number.isSafeInteger(P) || P < 0) throw TypeError("closeSettleSeconds must be a nonnegative integer.");
337
+ let F = (e) => {
166
338
  let t = e.lastResponse.headers.date, n = typeof t == "string" ? Date.parse(t) : NaN;
167
339
  if (!Number.isFinite(n)) throw Error("Provider clock evidence is required for billing closure.");
168
340
  return n;
169
- }, F = async (e) => {
341
+ }, I = async (e) => {
170
342
  let t = e.providerSubscriptionId;
171
- if (e.mode === "periodEnd") return T.subscriptions.update(t, {
343
+ if (e.mode === "periodEnd") return Z(t, e.operation, () => ({
172
344
  cancel_at_period_end: !0,
173
345
  expand: ["items.data.price"]
174
- });
346
+ }));
175
347
  let n = e.closeOperation;
176
348
  if (!n.id || !Number.isFinite(n.cancelAt.getTime()) || n.cancelAt.getTime() % 1e3 != 0) throw Error("A retained close operation and provider deadline are required.");
177
- let r = await T.subscriptions.retrieve(t, { expand: ["items.data.price"] });
349
+ let r = await b.subscriptions.retrieve(t, { expand: ["items.data.price"] });
178
350
  if (r.status === "canceled") return r;
179
351
  let i = n.cancelAt.getTime() / 1e3;
180
352
  if (r.cancel_at !== null && r.cancel_at <= i) return r;
181
353
  let a = "voltro-close:" + n.id;
182
- return P(r) >= n.cancelAt.getTime() ? T.subscriptions.cancel(t, {
354
+ return F(r) >= n.cancelAt.getTime() ? b.subscriptions.cancel(t, {
183
355
  invoice_now: !0,
184
356
  prorate: !0
185
- }, { idempotencyKey: a + ":cancel" }) : T.subscriptions.update(t, {
357
+ }, { idempotencyKey: a + ":cancel" }) : b.subscriptions.update(t, {
186
358
  cancel_at: i,
187
359
  proration_behavior: "create_prorations",
188
360
  expand: ["items.data.price"]
189
361
  }, { idempotencyKey: a + ":schedule" });
190
- }, I = (e) => T.subscriptions.retrieve(e, { expand: ["items.data.price"] }), L = (e, t) => {
191
- let n = i(e), r = v(e)?.price;
362
+ }, U = (e) => b.subscriptions.retrieve(e, { expand: ["items.data.price"] }), q = (e, t) => {
363
+ let n = r(e), i = x(e, k)?.price;
192
364
  return {
193
- plan: x(e, A) ?? "free",
194
- quantity: a(e),
365
+ plan: E(e, D, k) ?? "free",
366
+ quantity: w(e, k),
195
367
  prorationMinor: t,
196
- currency: (r?.currency ?? "usd").toLowerCase(),
368
+ currency: (i?.currency ?? "usd").toLowerCase(),
197
369
  currentPeriodStart: n.start,
198
370
  currentPeriodEnd: n.end
199
371
  };
200
- }, R = (e, t) => {
201
- let n = v(e)?.id;
372
+ }, J = (e, t) => {
373
+ let n = t.priceId ?? S(e, k), r = n === null ? null : k?.(n) ?? null, i = t.quantity ?? w(e, k);
202
374
  return {
203
- items: [{
204
- ...n === void 0 ? {} : { id: n },
205
- ...t.priceId === void 0 ? {} : { price: t.priceId },
206
- ...t.quantity === void 0 ? {} : { quantity: t.quantity }
207
- }],
208
- proration_behavior: w[t.proration ?? "prorate"],
209
- ...t.priceId !== void 0 && A ? { metadata: {
210
- ...e.metadata,
211
- plan: A(t.priceId) ?? ""
212
- } } : {}
375
+ pricing: r,
376
+ seats: r === null ? i : Math.max(i, r.includedSeats)
213
377
  };
378
+ }, Y = async (e, t) => {
379
+ if (t.meteredPriceIds === void 0) return [];
380
+ if (e.items.has_more !== !1) throw Error("The complete subscription item list is required to replace metered prices.");
381
+ let n = [...new Set(t.meteredPriceIds)], r = new Set(t.replacesMeteredPriceIds ?? []), i = e.items.data.filter((e) => e.price?.recurring?.usage_type === "metered"), a = n.filter((e) => !i.some((t) => t.price.id === e)), o = i.filter((e) => !n.includes(e.price.id) && r.has(e.price.id)), s = [];
382
+ for (let e of a) {
383
+ let t = (await b.prices.retrieve(e)).recurring?.meter ?? null, n = t === null ? -1 : o.findIndex((e) => e.price.recurring?.meter === t);
384
+ n < 0 ? s.push({ price: e }) : (s.push({
385
+ id: o[n].id,
386
+ price: e
387
+ }), o.splice(n, 1));
388
+ }
389
+ for (let e of o) s.push({
390
+ id: e.id,
391
+ deleted: !0
392
+ });
393
+ return s;
394
+ }, X = async (e, t) => {
395
+ let n = t.operation?.itemId ?? x(e, k)?.id, r = C(e, k), i = J(e, t), a = i.pricing === null ? r.pricing === null ? t.quantity : i.seats : 1, o = i.pricing === null ? 0 : i.seats - i.pricing.includedSeats, s = r.item === void 0 ? o > 0 && i.pricing !== null ? [{
396
+ price: i.pricing.seatPriceId,
397
+ quantity: o
398
+ }] : [] : [o > 0 && i.pricing !== null ? {
399
+ id: r.item.id,
400
+ price: i.pricing.seatPriceId,
401
+ quantity: o
402
+ } : {
403
+ id: r.item.id,
404
+ deleted: !0
405
+ }];
406
+ return {
407
+ items: [
408
+ {
409
+ ...n === void 0 ? {} : { id: n },
410
+ ...t.priceId === void 0 ? {} : { price: t.priceId },
411
+ ...a === void 0 ? {} : { quantity: a }
412
+ },
413
+ ...s,
414
+ ...await Y(e, t)
415
+ ],
416
+ proration_behavior: M[t.proration ?? "prorate"],
417
+ ...t.priceId === void 0 ? {} : { metadata: { plan: t.operation?.plan ?? D?.(t.priceId) ?? "" } }
418
+ };
419
+ }, Z = async (e, t, n) => {
420
+ let r = !1;
421
+ try {
422
+ let i = await U(e);
423
+ if (t !== void 0 && i.metadata?.voltro_write_operation === t.id) return r = !0, await p.runPromise(t.applied(N(i))), i;
424
+ let a = await n(i);
425
+ if (t === void 0) return await b.subscriptions.update(e, a);
426
+ if (!t.id || t.itemId !== null && !i.items.data.some((e) => e.id === t.itemId) || t.expectedPriceId !== null && !i.items.data.some((e) => e.id === t.itemId && e.price.id === t.expectedPriceId)) throw Error("Original subscription item custody is unavailable.");
427
+ await p.runPromise(t.beforeDispatch()), r = !0;
428
+ let o;
429
+ try {
430
+ o = await b.subscriptions.update(e, {
431
+ ...a,
432
+ metadata: {
433
+ ...a.metadata,
434
+ voltro_write_operation: t.id
435
+ }
436
+ }, {
437
+ idempotencyKey: "voltro-write:" + t.id,
438
+ maxNetworkRetries: 0
439
+ });
440
+ } catch (e) {
441
+ let n = _(e);
442
+ throw n !== null && await p.runPromise(t.rejected(n)).catch(() => void 0), e;
443
+ }
444
+ return await p.runPromise(t.applied(N(o))), o;
445
+ } catch (e) {
446
+ throw !r && t !== void 0 && await p.runPromise(t.notDispatched()), e;
447
+ }
448
+ }, Q = (e) => {
449
+ let t = e.quantity ?? 1, n = (e, t) => ({ adjustable_quantity: {
450
+ enabled: !0,
451
+ minimum: e,
452
+ maximum: t
453
+ } }), r = k?.(e.priceId) ?? null;
454
+ if (r === null) return [{
455
+ price: e.priceId,
456
+ quantity: t,
457
+ ...e.adjustableQuantity ? n(e.adjustableQuantity.min, e.adjustableQuantity.max) : {}
458
+ }];
459
+ let i = Math.max(0, t - r.includedSeats);
460
+ if (i === 0) return [{
461
+ price: e.priceId,
462
+ quantity: 1
463
+ }];
464
+ let a = e.adjustableQuantity === void 0 ? null : {
465
+ min: Math.max(1, e.adjustableQuantity.min - r.includedSeats),
466
+ max: e.adjustableQuantity.max - r.includedSeats
467
+ }, o = a !== null && a.max >= Math.max(a.min, i);
468
+ return [{
469
+ price: e.priceId,
470
+ quantity: 1
471
+ }, {
472
+ price: r.seatPriceId,
473
+ quantity: i,
474
+ ...o ? n(a.min, a.max) : {}
475
+ }];
214
476
  };
215
477
  return {
216
478
  name: "stripe",
217
- fetchAccountIdentity: () => l(T),
218
- fetchCustomerSnapshot: (e) => u(T, e),
219
- supportsMeteredUsage: y.supportsMeteredUsage ?? !0,
479
+ supportsNativeSubscriptionWrites: !0,
480
+ fetchAccountIdentity: () => u(b),
481
+ fetchCustomerSnapshot: (e) => d(b, e),
482
+ fetchPrices: (e) => a("stripe.prices.retrieve", async () => {
483
+ let t = [...new Set(e)].filter((e) => e.length > 0), n = [];
484
+ for (let e = 0; e < t.length; e += R) {
485
+ let r = await Promise.all(t.slice(e, e + R).map(async (e) => {
486
+ try {
487
+ return H(await b.prices.retrieve(e, { expand: ["tiers"] }));
488
+ } catch (e) {
489
+ if (e.statusCode === 404) return null;
490
+ throw e;
491
+ }
492
+ }));
493
+ for (let e of r) e !== null && n.push(e);
494
+ }
495
+ return n;
496
+ }),
497
+ fetchPriceVersions: (e) => a("stripe.prices.list", async () => {
498
+ let t;
499
+ try {
500
+ t = await b.prices.retrieve(e);
501
+ } catch (e) {
502
+ if (e.statusCode === 404) return [];
503
+ throw e;
504
+ }
505
+ let n = typeof t.product == "string" ? t.product : t.product.id, r = [], i;
506
+ for (let e = 0; e < L; e++) {
507
+ let e = await b.prices.list({
508
+ product: n,
509
+ limit: 100,
510
+ expand: ["data.tiers"],
511
+ ...i === void 0 ? {} : { starting_after: i }
512
+ });
513
+ for (let t of e.data) {
514
+ let e = typeof t.product == "string" ? t.product : t.product.id;
515
+ r.push({
516
+ ...H(t),
517
+ createdAt: /* @__PURE__ */ new Date(t.created * 1e3),
518
+ productId: e,
519
+ taxBehavior: V(t.tax_behavior)
520
+ });
521
+ }
522
+ if (!e.has_more) return r;
523
+ if (i = e.data.at(-1)?.id, i === void 0) break;
524
+ }
525
+ throw Error("price history exceeds the bounded read");
526
+ }),
527
+ fetchPriceMeters: (e) => a("stripe.billing.meters.retrieve", async () => {
528
+ let t = /* @__PURE__ */ new Map(), n = [];
529
+ for (let r of [...new Set(e)].filter((e) => e.length > 0)) {
530
+ let e;
531
+ try {
532
+ e = await b.prices.retrieve(r);
533
+ } catch (e) {
534
+ if (e.statusCode === 404) continue;
535
+ throw e;
536
+ }
537
+ let i = e.recurring?.meter ?? null;
538
+ if (i === null) continue;
539
+ let a = t.get(i);
540
+ a === void 0 && (a = (await b.billing.meters.retrieve(i)).event_name, t.set(i, a)), n.push({
541
+ priceId: r,
542
+ meterEventName: a
543
+ });
544
+ }
545
+ return n;
546
+ }),
547
+ ensureInvoiceItem: (e) => a("stripe.invoiceItems.create", async () => {
548
+ let n = { gte: Math.floor(e.notBefore.getTime() / 1e3) }, r;
549
+ for (let t = 0; t < z; t++) {
550
+ let i = await b.invoiceItems.list({
551
+ customer: e.providerCustomerId,
552
+ created: n,
553
+ limit: 100,
554
+ ...r === void 0 ? {} : { starting_after: r }
555
+ }), a = i.data.find((t) => t.metadata?.[B] === e.idempotencyKey);
556
+ if (a !== void 0) return { providerInvoiceItemId: a.id };
557
+ if (!i.has_more || (r = i.data.at(-1)?.id, r === void 0)) break;
558
+ if (t === 9) throw Error("invoice item lookup exceeds the bounded read");
559
+ }
560
+ return { providerInvoiceItemId: (await b.invoiceItems.create({
561
+ customer: e.providerCustomerId,
562
+ ...e.providerSubscriptionId === void 0 ? {} : { subscription: e.providerSubscriptionId },
563
+ price_data: {
564
+ currency: e.currency,
565
+ product: e.productId,
566
+ unit_amount_decimal: t.Decimal.from(e.unitAmountDecimal),
567
+ ...e.taxBehavior === null ? {} : { tax_behavior: e.taxBehavior }
568
+ },
569
+ quantity: e.quantity,
570
+ period: {
571
+ start: Math.floor(e.period.start.getTime() / 1e3),
572
+ end: Math.floor(e.period.end.getTime() / 1e3) - 1
573
+ },
574
+ description: e.description,
575
+ metadata: { [B]: e.idempotencyKey }
576
+ }, { idempotencyKey: e.idempotencyKey })).id };
577
+ }),
578
+ supportsMeteredUsage: i.supportsMeteredUsage ?? !0,
220
579
  usageRequiresCustomer: !0,
221
- createCheckoutSession: (e) => o("stripe.checkout.sessions.create", async () => h(await T.checkout.sessions.create({
580
+ createCheckoutSession: (e) => a("stripe.checkout.sessions.create", async () => g(await b.checkout.sessions.create({
222
581
  mode: "subscription",
223
- integration_identifier: await m(e.idempotencyKey),
224
- line_items: [{
225
- price: e.priceId,
226
- quantity: e.quantity ?? 1,
227
- ...e.adjustableQuantity ? { adjustable_quantity: {
228
- enabled: !0,
229
- minimum: e.adjustableQuantity.min,
230
- maximum: e.adjustableQuantity.max
231
- } } : {}
232
- }, ...(e.meteredPriceIds ?? []).map((e) => ({ price: e }))],
582
+ integration_identifier: await h(e.idempotencyKey),
583
+ line_items: [...Q(e), ...(e.meteredPriceIds ?? []).map((e) => ({ price: e }))],
233
584
  success_url: e.successUrl,
234
585
  cancel_url: e.cancelUrl,
235
586
  client_reference_id: e.tenantId,
@@ -251,10 +602,10 @@ var m = async (e) => {
251
602
  } },
252
603
  allow_promotion_codes: !0
253
604
  }, e.idempotencyKey === void 0 ? void 0 : { idempotencyKey: e.idempotencyKey }))),
254
- findCheckoutSession: (e) => o("stripe.checkout.sessions.find", async () => {
605
+ findCheckoutSession: (e) => a("stripe.checkout.sessions.find", async () => {
255
606
  let t = null, n = 0, r, i = null;
256
607
  do {
257
- let a = await T.checkout.sessions.list({
608
+ let a = await b.checkout.sessions.list({
258
609
  ...e.providerCustomerId === void 0 ? {} : { customer: e.providerCustomerId },
259
610
  limit: 100,
260
611
  ...r === void 0 ? {} : { starting_after: r }
@@ -266,7 +617,7 @@ var m = async (e) => {
266
617
  for (let r of a.data) {
267
618
  if (++n > 1e4) throw Error("Checkout history is too large to establish an unambiguous operation receipt.");
268
619
  if (r.metadata?.voltroBillingOperation !== e.operationId) continue;
269
- let i = h(r);
620
+ let i = g(r);
270
621
  if (i.tenantId !== e.tenantId || e.providerCustomerId !== void 0 && i.providerCustomerId !== e.providerCustomerId || t !== null) throw Error("Checkout receipt does not match a unique tenant operation.");
271
622
  t = i;
272
623
  }
@@ -279,7 +630,7 @@ var m = async (e) => {
279
630
  r = o;
280
631
  } while (1);
281
632
  }),
282
- createPortalSession: (e) => o("stripe.billingPortal.sessions.create", async () => ({ url: (await T.billingPortal.sessions.create({
633
+ createPortalSession: (e) => a("stripe.billingPortal.sessions.create", async () => ({ url: (await b.billingPortal.sessions.create({
283
634
  customer: e.providerCustomerId,
284
635
  return_url: e.returnUrl
285
636
  })).url })),
@@ -289,9 +640,9 @@ var m = async (e) => {
289
640
  source: "stripe.billing.meterEvents.create",
290
641
  message: `no Stripe customer linked for tenant '${t.tenantId}'`,
291
642
  transient: !1
292
- })) : o("stripe.billing.meterEvents.create", async () => {
643
+ })) : a("stripe.billing.meterEvents.create", async () => {
293
644
  try {
294
- await T.billing.meterEvents.create({
645
+ await b.billing.meterEvents.create({
295
646
  event_name: t.entitlementKey,
296
647
  identifier: t.idempotencyKey ?? `${t.tenantId}:${t.entitlementKey}:${t.periodEnd?.toISOString() ?? "current"}`,
297
648
  payload: {
@@ -300,17 +651,17 @@ var m = async (e) => {
300
651
  }
301
652
  });
302
653
  } catch (e) {
303
- if (E(e)) return;
654
+ if (W(e)) return;
304
655
  throw e;
305
656
  }
306
657
  });
307
658
  },
308
- updateSubscription: (e) => o("stripe.subscriptions.update", async () => {
309
- let t = await I(e.providerSubscriptionId), n = await T.subscriptions.update(e.providerSubscriptionId, R(t, e)), r = await k(T, n);
310
- return L(n, r);
659
+ updateSubscription: (e) => a("stripe.subscriptions.update", async () => {
660
+ let t = await Z(e.providerSubscriptionId, e.operation, (t) => X(t, e));
661
+ return q(t, null);
311
662
  }),
312
- previewSubscriptionChange: (e) => o("stripe.invoices.createPreview", async () => {
313
- let t = await I(e.providerSubscriptionId), n = R(t, e), r = (await T.invoices.createPreview({
663
+ previewSubscriptionChange: (e) => a("stripe.invoices.createPreview", async () => {
664
+ let t = await U(e.providerSubscriptionId), n = await X(t, e), r = (await b.invoices.createPreview({
314
665
  subscription: e.providerSubscriptionId,
315
666
  subscription_details: {
316
667
  items: n.items,
@@ -318,83 +669,106 @@ var m = async (e) => {
318
669
  }
319
670
  })).lines.data.filter((e) => e.parent?.subscription_item_details?.proration === !0).reduce((e, t) => e + t.amount, 0);
320
671
  return {
321
- ...L(t, r),
322
- ...e.quantity === void 0 ? {} : { quantity: e.quantity },
323
- ...e.priceId !== void 0 && A ? { plan: A(e.priceId) ?? "free" } : {}
672
+ ...q(t, r),
673
+ prorationMinor: r,
674
+ quantity: J(t, e).seats,
675
+ ...e.priceId !== void 0 && D ? { plan: D(e.priceId) ?? "free" } : {}
324
676
  };
325
677
  }),
326
- fetchSubscriptionSnapshot: (e) => o("stripe.subscriptions.retrieve", async () => {
678
+ fetchSubscriptionSnapshot: (e) => a("stripe.subscriptions.retrieve", async () => {
327
679
  try {
328
- return M(await I(e));
680
+ return N(await U(e));
329
681
  } catch (e) {
330
- if (e instanceof n.errors.StripeInvalidRequestError && e.statusCode === 404) return null;
682
+ if (e instanceof t.errors.StripeInvalidRequestError && e.statusCode === 404) return null;
331
683
  throw e;
332
684
  }
333
685
  }),
334
- fetchSubscription: (e) => o("stripe.subscriptions.retrieve", async () => {
686
+ fetchSubscription: (e) => a("stripe.subscriptions.retrieve", async () => {
335
687
  try {
336
- return j(await I(e));
688
+ return A(await U(e));
337
689
  } catch (e) {
338
- if (e instanceof n.errors.StripeInvalidRequestError && e.statusCode === 404) return null;
690
+ if (e instanceof t.errors.StripeInvalidRequestError && e.statusCode === 404) return null;
339
691
  throw e;
340
692
  }
341
693
  }),
342
- listSubscriptions: (e) => o("stripe.subscriptions.list", async () => {
694
+ listSubscriptions: (e) => a("stripe.subscriptions.list", async () => {
343
695
  let t = [];
344
- for await (let n of T.subscriptions.list({
696
+ for await (let n of b.subscriptions.list({
345
697
  limit: 100,
346
698
  expand: ["data.items.data.price"],
347
699
  ...e.providerCustomerId === void 0 ? {} : { customer: e.providerCustomerId }
348
- })) t.push(M(n));
700
+ })) t.push(N(n));
349
701
  return t;
350
702
  }),
351
- prepareSubscriptionClose: (e) => o("stripe.subscriptions.closeQuote", async () => {
352
- let t = await T.subscriptions.retrieve(e, { expand: ["items.data.price"] });
353
- return { cancelAt: new Date(P(t) + N * 1e3) };
703
+ prepareSubscriptionClose: (e) => a("stripe.subscriptions.closeQuote", async () => {
704
+ let t = await b.subscriptions.retrieve(e, { expand: ["items.data.price"] });
705
+ return { cancelAt: new Date(F(t) + P * 1e3) };
354
706
  }),
355
- cancelSubscription: (e) => o("stripe.subscriptions.cancel", async () => j(await F(e))),
356
- resumeSubscription: (e) => o("stripe.subscriptions.update", async () => j(await T.subscriptions.update(e, {
707
+ cancelSubscription: (e) => a("stripe.subscriptions.cancel", async () => A(await I(e))),
708
+ resumeSubscription: (e, t) => a("stripe.subscriptions.update", async () => A(await Z(e, t, () => ({
357
709
  cancel_at_period_end: !1,
358
710
  expand: ["items.data.price"]
359
- }))),
360
- ensureCustomer: (e) => o("stripe.customers.create", async () => {
361
- let t = (await T.customers.search({
711
+ })))),
712
+ ensureCustomer: (e) => a("stripe.customers.create", async () => {
713
+ let t = (await b.customers.search({
362
714
  query: `metadata['tenantId']:'${e.tenantId.replace(/['\\]/g, "")}'`,
363
715
  limit: 2
364
716
  })).data.find((t) => t.metadata?.tenantId === e.tenantId);
365
- return t === void 0 ? (await T.customers.create({ metadata: { tenantId: e.tenantId } }, { idempotencyKey: `voltro-billing-customer:${e.tenantId}` })).id : t.id;
717
+ return t === void 0 ? (await b.customers.create({ metadata: { tenantId: e.tenantId } }, { idempotencyKey: `voltro-billing-customer:${e.tenantId}` })).id : t.id;
366
718
  }),
367
- expireOpenCheckouts: (e) => o("stripe.checkout.sessions.expire", async () => {
719
+ expireOpenCheckouts: (e) => a("stripe.checkout.sessions.expire", async () => {
368
720
  let t = 0;
369
- for await (let n of T.checkout.sessions.list({
721
+ for await (let n of b.checkout.sessions.list({
370
722
  customer: e.providerCustomerId,
371
723
  status: "open",
372
724
  limit: 100
373
- })) (e.exceptOperationId === void 0 || n.metadata?.voltroBillingOperation !== e.exceptOperationId) && (await T.checkout.sessions.expire(n.id), t += 1);
725
+ })) (e.exceptOperationId === void 0 || n.metadata?.voltroBillingOperation !== e.exceptOperationId) && (await b.checkout.sessions.expire(n.id), t += 1);
374
726
  return t;
375
727
  }),
376
- addSubscriptionPrices: (e) => o("stripe.subscriptionItems.create", async () => {
377
- for (let t of e.priceIds) await T.subscriptionItems.create({
378
- subscription: e.providerSubscriptionId,
379
- price: t,
380
- proration_behavior: "none"
381
- });
728
+ addSubscriptionPrices: (e) => a("stripe.subscriptionItems.create", async () => {
729
+ let t = e.providerSubscriptionId, n = async () => {
730
+ let e = [];
731
+ for await (let n of b.subscriptionItems.list({
732
+ subscription: t,
733
+ limit: 100
734
+ })) e.push(n);
735
+ return e;
736
+ }, r = (e, t) => e.some((e) => e.price?.id === t), i = await n();
737
+ for (let a of new Set(e.priceIds)) {
738
+ if (r(i, a)) continue;
739
+ let e = await m(JSON.stringify([
740
+ t,
741
+ a,
742
+ i.map((e) => e.id).sort()
743
+ ]));
744
+ try {
745
+ i.push(await b.subscriptionItems.create({
746
+ subscription: t,
747
+ price: a,
748
+ proration_behavior: "none"
749
+ }, { idempotencyKey: `voltro-billing-price:${e}` }));
750
+ } catch (e) {
751
+ if (i = await n().catch(() => {
752
+ throw e;
753
+ }), !r(i, a)) throw e;
754
+ }
755
+ }
382
756
  }),
383
- customerEmail: (e) => o("stripe.customers.retrieve", async () => {
384
- let t = await T.customers.retrieve(e);
757
+ customerEmail: (e) => a("stripe.customers.retrieve", async () => {
758
+ let t = await b.customers.retrieve(e);
385
759
  return t.deleted === !0 ? null : typeof t.email == "string" && t.email.length > 0 ? t.email : null;
386
760
  }),
387
- fetchInvoiceSnapshot: (e) => c(T, e),
388
- listInvoiceHistory: (e) => d(T, e),
389
- listInvoices: (e) => l(T).pipe(p.flatMap((t) => d(T, {
761
+ fetchInvoiceSnapshot: (e) => s(b, e),
762
+ listInvoiceHistory: (e) => c(b, e),
763
+ listInvoices: (e) => u(b).pipe(p.flatMap((t) => c(b, {
390
764
  account: t,
391
765
  providerCustomerId: e.providerCustomerId,
392
766
  limit: e.limit ?? 20
393
- })), p.map((e) => e.invoices.map(t))),
394
- verifyWebhook: (e) => f(T, e),
395
- eventContext: (e) => O(e) ? {
396
- providerCustomerId: D(e.data.object),
397
- createdAt: s(e.created)
767
+ })), p.map((e) => e.invoices.map(l))),
768
+ verifyWebhook: (e) => f(b, e),
769
+ eventContext: (e) => K(e) ? {
770
+ providerCustomerId: G(e.data.object),
771
+ createdAt: o(e.created)
398
772
  } : {
399
773
  providerCustomerId: null,
400
774
  createdAt: null
@@ -410,44 +784,14 @@ var m = async (e) => {
410
784
  transient: !1
411
785
  })
412
786
  });
413
- let n = yield* l(T), r = yield* o("stripe.events.list", () => T.events.list({
787
+ let n = yield* u(b), r = yield* a("stripe.events.list", () => b.events.list({
414
788
  delivery_success: !1,
415
- types: [...S],
416
789
  limit: t.limit,
417
790
  ...t.cursor === null ? {} : { starting_after: t.cursor }
418
791
  }));
419
- return yield* p.try({
792
+ yield* p.try({
420
793
  try: () => {
421
794
  if (!Array.isArray(r.data) || r.data.length > t.limit || typeof r.has_more != "boolean" || r.has_more && r.data.length === 0) throw Error("Incomplete event page");
422
- let e = r.data.map((e) => {
423
- let t = {
424
- id: e.id,
425
- providerCustomerId: D(e.data.object),
426
- createdAt: s(e.created)
427
- };
428
- if (e.livemode !== n.livemode || e.account !== void 0 && e.account !== null && e.account !== n.providerAccountId) return {
429
- ...t,
430
- event: null,
431
- rejected: !0
432
- };
433
- try {
434
- return {
435
- ...t,
436
- event: C(e, A)
437
- };
438
- } catch {
439
- return {
440
- ...t,
441
- event: null,
442
- rejected: !0
443
- };
444
- }
445
- }), i = r.has_more ? e.at(-1)?.id ?? null : null;
446
- if (r.has_more && (i === null || i === t.cursor)) throw Error("Nonadvancing event page");
447
- return {
448
- events: e,
449
- nextCursor: i
450
- };
451
795
  },
452
796
  catch: () => new e({
453
797
  source: "stripe.events.list",
@@ -455,24 +799,49 @@ var m = async (e) => {
455
799
  transient: !0
456
800
  })
457
801
  });
802
+ let i = yield* p.forEach(r.data, (e) => {
803
+ let t = {
804
+ id: e.id,
805
+ providerCustomerId: G(e.data.object),
806
+ createdAt: o(e.created)
807
+ };
808
+ return O.includes(e.type) ? e.livemode !== n.livemode || e.account !== void 0 && e.account !== null && e.account !== n.providerAccountId ? p.succeed({
809
+ ...t,
810
+ event: null,
811
+ rejected: !0
812
+ }) : j(b, e, D, k).pipe(p.map((e) => ({
813
+ ...t,
814
+ event: e,
815
+ providerCustomerId: t.providerCustomerId ?? (e !== null && "providerCustomerId" in e ? e.providerCustomerId : null)
816
+ })), p.catch(() => p.succeed({
817
+ ...t,
818
+ event: null,
819
+ rejected: !0
820
+ }))) : p.succeed({
821
+ ...t,
822
+ providerCustomerId: null,
823
+ event: null
824
+ });
825
+ }), s = yield* u(b);
826
+ if (s.providerAccountId !== n.providerAccountId || s.livemode !== n.livemode) return yield* p.fail(new e({
827
+ source: "stripe.events.list",
828
+ message: "The Stripe account changed during event recovery.",
829
+ transient: !0
830
+ }));
831
+ let c = r.has_more ? i.at(-1)?.id ?? null : null;
832
+ return r.has_more && (c === null || c === t.cursor) ? yield* p.fail(new e({
833
+ source: "stripe.events.list",
834
+ message: "The event recovery cursor did not advance.",
835
+ transient: !0
836
+ })) : {
837
+ events: i,
838
+ nextCursor: c
839
+ };
458
840
  }),
459
- normalizeEvent: (t) => p.try({
460
- try: () => O(t) ? C(t, A) : null,
461
- catch: (t) => t instanceof e ? t : new e({
462
- source: "stripe.normalizeEvent",
463
- message: "The provider event could not be normalized.",
464
- transient: !1
465
- })
466
- })
841
+ normalizeEvent: (e) => K(e) ? j(b, e, D, k) : p.succeed(null)
467
842
  };
468
- }, E = (e) => e instanceof n.errors.StripeInvalidRequestError && typeof e.message == "string" && e.message.startsWith("An event already exists with identifier"), D = (e) => {
843
+ }, W = (e) => e instanceof t.errors.StripeInvalidRequestError && typeof e.message == "string" && e.message.startsWith("An event already exists with identifier"), G = (e) => {
469
844
  let t = e;
470
- return t.object === "customer" ? typeof t.id == "string" ? t.id : null : b(t.customer ?? null);
471
- }, O = (e) => typeof e == "object" && !!e && typeof e.type == "string" && typeof e.data == "object", k = async (e, t) => {
472
- try {
473
- return (await e.invoices.createPreview({ subscription: t.id })).lines.data.filter((e) => e.parent?.subscription_item_details?.proration === !0).reduce((e, t) => e + t.amount, 0);
474
- } catch {
475
- return 0;
476
- }
477
- };
478
- export { S as STRIPE_WEBHOOK_EVENTS, E as isDuplicateMeterEvent, C as normalizeStripeEvent, T as stripeProvider };
845
+ return t.object === "customer" ? typeof t.id == "string" ? t.id : null : T(t.customer ?? null);
846
+ }, K = (e) => typeof e == "object" && !!e && typeof e.type == "string" && typeof e.data == "object";
847
+ export { O as STRIPE_WEBHOOK_EVENTS, W as isDuplicateMeterEvent, k as normalizeStripeEvent, U as stripeProvider };