@voltro/plugin-billing 0.90.0 → 0.91.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stores.js CHANGED
@@ -1,32 +1,32 @@
1
- import { BillingError as e } from "./types.js";
1
+ import { captureSubscriptionObservation as e } from "./subscriptionObservation.js";
2
2
  import { dataStoreSubscriptionWriteStore as t } from "./subscriptionWriteStore.js";
3
- import { dataStoreDunningNoticeStore as n } from "./dunning.js";
4
- import { dataStoreCheckoutOperationStore as r } from "./checkoutStore.js";
5
- import { dataStoreBillingCloseStore as i } from "./closeStore.js";
6
- import { recordDataStoreUsageEvent as a } from "./usageEvents.js";
3
+ import { dataStoreInvoiceHistoryJournal as n } from "./invoiceHistoryJournal.js";
4
+ import { dataStoreInvoiceHistoryProgressStore as r } from "./invoiceHistoryProgress.js";
5
+ import { dataStoreInvoiceHistoryWorkStore as i } from "./invoiceHistoryWork.js";
6
+ import { dataStoreCustomerStore as a } from "./customerStore.js";
7
7
  import { dataStoreInvoiceStore as o } from "./invoiceStore.js";
8
- import { dataStoreCustomerStore as s } from "./customerStore.js";
9
- import { dataStoreInvoiceHistoryJournal as c } from "./invoiceHistoryJournal.js";
10
- import { dataStoreInvoiceHistoryWorkStore as l } from "./invoiceHistoryWork.js";
11
- import { dataStoreInvoiceHistoryProgressStore as u } from "./invoiceHistoryProgress.js";
12
- import { BILLING_SUBSCRIPTIONS_TABLE as d, BILLING_USAGE_TABLE as f, billingTables as p } from "./table.js";
13
- import { captureSubscriptionObservation as m } from "./subscriptionObservation.js";
8
+ import { recordDataStoreUsageEvent as s } from "./usageEvents.js";
9
+ import { dataStoreCheckoutOperationStore as c } from "./checkoutStore.js";
10
+ import { dataStoreBillingCloseStore as l } from "./closeStore.js";
11
+ import { BILLING_SUBSCRIPTIONS_TABLE as u, BILLING_USAGE_TABLE as d, billingTables as f } from "./table.js";
12
+ import { dataStoreDunningNoticeStore as p } from "./dunning.js";
13
+ import { BillingError as m } from "./types.js";
14
14
  import { Effect as h } from "effect";
15
15
  import { _voltroIdempotencyTable as g, and as _, ensureTableRegistered as v, eq as y, lt as b } from "@voltro/database";
16
16
  import { InMemoryDataStore as x } from "@voltro/runtime";
17
17
  import { createLogger as S } from "@voltro/logger";
18
18
  // src/stores.ts
19
- var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, w = S({ scope: "@voltro/plugin-billing" }), T = (t, n) => h.tryPromise({
20
- try: t,
21
- catch: (t) => t instanceof e ? t : (w.warn("billing store operation failed", {
22
- source: n,
23
- detail: String(t?.message ?? t)
24
- }), new e({
25
- source: n,
26
- message: `${n} failed`,
19
+ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, w = S({ scope: "@voltro/plugin-billing" }), T = (e, t) => h.tryPromise({
20
+ try: e,
21
+ catch: (e) => e instanceof m ? e : (w.warn("billing store operation failed", {
22
+ source: t,
23
+ detail: String(e?.message ?? e)
24
+ }), new m({
25
+ source: t,
26
+ message: `${t} failed`,
27
27
  transient: !0
28
28
  }))
29
- }), E = () => new e({
29
+ }), E = () => new m({
30
30
  source: "subscriptionStore",
31
31
  message: "Subscription observation changed before exact patch.",
32
32
  transient: !0
@@ -42,35 +42,35 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
42
42
  "trialing",
43
43
  "pastDue",
44
44
  "incomplete"
45
- ]), j = (e) => A.has(e), M = (e) => e.find((e) => j(e.status)) ?? e[0] ?? null, N = (e, t) => e === null ? !1 : t === null || t.getTime() < e.getTime(), P = (e, t) => {
45
+ ]), j = (e) => A.has(e), M = (e) => e.find((e) => j(e.status)) ?? e[0] ?? null, N = (e, t) => e === null ? !1 : t === null || t.getTime() < e.getTime(), P = (t, n) => {
46
46
  try {
47
- return m(e.providerObservation, {
48
- ...e,
49
- ...t
47
+ return e(t.providerObservation, {
48
+ ...t,
49
+ ...n
50
50
  });
51
51
  } catch {
52
52
  return null;
53
53
  }
54
- }, F = (e) => {
55
- let t = {
56
- tenantId: String(e.tenantId),
57
- provider: String(e.provider),
58
- providerSubscriptionId: String(e.providerSubscriptionId),
59
- plan: String(e.plan),
60
- status: String(e.status),
61
- quantity: e.quantity == null ? 1 : Number(e.quantity),
62
- currentPeriodStart: e.currentPeriodStart == null ? null : new Date(e.currentPeriodStart),
63
- currentPeriodEnd: e.currentPeriodEnd == null ? null : new Date(e.currentPeriodEnd),
64
- cancelAt: e.cancelAt == null ? null : new Date(e.cancelAt),
65
- pastDueSince: e.pastDueSince == null ? null : new Date(e.pastDueSince),
66
- statusEventAt: e.statusEventAt == null ? null : new Date(e.statusEventAt)
54
+ }, F = (t) => {
55
+ let n = {
56
+ tenantId: String(t.tenantId),
57
+ provider: String(t.provider),
58
+ providerSubscriptionId: String(t.providerSubscriptionId),
59
+ plan: String(t.plan),
60
+ status: String(t.status),
61
+ quantity: t.quantity == null ? 1 : Number(t.quantity),
62
+ currentPeriodStart: t.currentPeriodStart == null ? null : new Date(t.currentPeriodStart),
63
+ currentPeriodEnd: t.currentPeriodEnd == null ? null : new Date(t.currentPeriodEnd),
64
+ cancelAt: t.cancelAt == null ? null : new Date(t.cancelAt),
65
+ pastDueSince: t.pastDueSince == null ? null : new Date(t.pastDueSince),
66
+ statusEventAt: t.statusEventAt == null ? null : new Date(t.statusEventAt)
67
67
  };
68
68
  return {
69
- ...t,
70
- providerObservation: m(e.providerObservation, t)
69
+ ...n,
70
+ providerObservation: e(t.providerObservation, n)
71
71
  };
72
72
  }, I = async (e, t) => (await e.query(D({
73
- table: d,
73
+ table: u,
74
74
  predicate: y("tenantId", t),
75
75
  order: [{
76
76
  column: "updatedAt",
@@ -101,7 +101,7 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
101
101
  if (r.providerSubscriptionId !== t.providerSubscriptionId || r.tenantId !== t.tenantId || r.provider !== t.provider || r.plan !== t.plan || r.status !== t.status || r.quantity !== t.quantity || !O(r.currentPeriodStart, t.currentPeriodStart) || !O(r.currentPeriodEnd, t.currentPeriodEnd) || !O(r.cancelAt, t.cancelAt) || !O(r.statusEventAt, t.statusEventAt) || JSON.stringify(r.providerObservation ?? null) !== JSON.stringify(n)) throw L();
102
102
  }, B = (e) => ({
103
103
  ...D({
104
- table: d,
104
+ table: u,
105
105
  predicate: y("providerSubscriptionId", e)
106
106
  }),
107
107
  lock: "update"
@@ -149,7 +149,7 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
149
149
  }, (e) => e.status === n);
150
150
  }), q = (t) => ({
151
151
  upsert: (n) => T(async () => {
152
- let r = structuredClone(n), i = m(r.providerObservation, r), a = /* @__PURE__ */ new Date(), o = C("bsub"), s = await t.insertIgnoreWithOutcome(d, {
152
+ let r = structuredClone(n), i = e(r.providerObservation, r), a = /* @__PURE__ */ new Date(), o = C("bsub"), s = await t.insertIgnoreWithOutcome(u, {
153
153
  id: o,
154
154
  providerSubscriptionId: r.providerSubscriptionId,
155
155
  ...R(r, i),
@@ -161,28 +161,28 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
161
161
  if (s.row.id !== o) throw L();
162
162
  return z(s.row, r, i);
163
163
  }
164
- await t.transactional(async (t) => {
165
- let n = B(r.providerSubscriptionId), o = await t.query(n), s = o[0];
166
- if (o.length !== 1 || s === void 0) throw L();
167
- if (s.tenantId !== r.tenantId || s.provider !== r.provider) throw new e({
164
+ await t.transactional(async (e) => {
165
+ let t = B(r.providerSubscriptionId), n = await e.query(t), o = n[0];
166
+ if (n.length !== 1 || o === void 0) throw L();
167
+ if (o.tenantId !== r.tenantId || o.provider !== r.provider) throw new m({
168
168
  source: "subscriptionStore",
169
169
  message: "The provider subscription belongs to different native custody.",
170
170
  transient: !1
171
171
  });
172
- if (N(s.statusEventAt == null ? null : new Date(s.statusEventAt), r.statusEventAt) || k(String(s.status)) && !k(r.status)) return;
173
- if (await t.update("_voltro_billing_subscriptions", String(s.id), {
172
+ if (N(o.statusEventAt == null ? null : new Date(o.statusEventAt), r.statusEventAt) || k(String(o.status)) && !k(r.status)) return;
173
+ if (await e.update("_voltro_billing_subscriptions", String(o.id), {
174
174
  ...R(r, i),
175
175
  updatedAt: a
176
176
  }) === null) throw L();
177
- let c = await t.query(n);
178
- if (c.length !== 1 || c[0].id !== s.id) throw L();
179
- z(c[0], r, i);
177
+ let s = await e.query(t);
178
+ if (s.length !== 1 || s[0].id !== o.id) throw L();
179
+ z(s[0], r, i);
180
180
  });
181
181
  }, "subscriptionStore"),
182
182
  getByTenant: (e) => T(async () => M(await I(t, e)), "subscriptionStore"),
183
183
  listByTenant: (e) => T(() => I(t, e), "subscriptionStore"),
184
184
  listByStatus: (e) => T(async () => (await t.query(D({
185
- table: d,
185
+ table: u,
186
186
  predicate: y("status", e),
187
187
  order: [{
188
188
  column: "updatedAt",
@@ -224,24 +224,24 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
224
224
  table: "_voltro_billing_usage",
225
225
  predicate: _(y("tenantId", t), y("entitlementKey", n), y("period", r)),
226
226
  take: 1
227
- })))[0] ?? null, Z = (t) => ({
228
- recordEvent: (n) => a(t, n, async (t, n) => {
229
- let r = Z(t), i = await h.runPromise(r.used(n.tenantId, n.entitlementKey, n.period));
230
- if (!Number.isSafeInteger(i + n.quantity)) throw new e({
227
+ })))[0] ?? null, Z = (e) => ({
228
+ recordEvent: (t) => s(e, t, async (e, t) => {
229
+ let n = Z(e), r = await h.runPromise(n.used(t.tenantId, t.entitlementKey, t.period));
230
+ if (!Number.isSafeInteger(r + t.quantity)) throw new m({
231
231
  source: "usageEvent",
232
232
  message: "Usage total exceeds exact integer storage.",
233
233
  transient: !1
234
234
  });
235
- return h.runPromise(r.increment(n.tenantId, n.entitlementKey, n.period, n.quantity));
235
+ return h.runPromise(n.increment(t.tenantId, t.entitlementKey, t.period, t.quantity));
236
236
  }),
237
- used: (e, n, r) => T(async () => {
238
- let i = await X(t, e, n, r);
237
+ used: (t, n, r) => T(async () => {
238
+ let i = await X(e, t, n, r);
239
239
  return i ? Number(i.used ?? 0) : 0;
240
240
  }, "usageStore"),
241
- consume: (e, n, r, i, a) => T(async () => {
241
+ consume: (t, n, r, i, a) => T(async () => {
242
242
  for (let o = 0; o < 32; o++) {
243
243
  o > 0 && await new Promise((e) => setTimeout(e, o));
244
- let s = await X(t, e, n, r), c = s ? Number(s.used ?? 0) : 0;
244
+ let s = await X(e, t, n, r), c = s ? Number(s.used ?? 0) : 0;
245
245
  if (c + i > a) return {
246
246
  allowed: !1,
247
247
  entitlement: n,
@@ -250,7 +250,7 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
250
250
  cost: i
251
251
  };
252
252
  if (s) {
253
- if (await t.updateMany("_voltro_billing_usage", {
253
+ if (await e.updateMany("_voltro_billing_usage", {
254
254
  used: c + i,
255
255
  updatedAt: /* @__PURE__ */ new Date()
256
256
  }, { where: _(y("id", String(s.id)), y("used", c)) }) === 1) return {
@@ -261,9 +261,9 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
261
261
  cost: i
262
262
  };
263
263
  } else {
264
- let o = C("buse"), s = await t.insertIgnore(f, {
264
+ let o = C("buse"), s = await e.insertIgnore(d, {
265
265
  id: o,
266
- tenantId: e,
266
+ tenantId: t,
267
267
  entitlementKey: n,
268
268
  period: r,
269
269
  used: i,
@@ -283,22 +283,22 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
283
283
  };
284
284
  }
285
285
  }
286
- throw Error(`billing usage consume: contention on (${e}, ${n}, ${r}) exceeded 32 attempts`);
286
+ throw Error(`billing usage consume: contention on (${t}, ${n}, ${r}) exceeded 32 attempts`);
287
287
  }, "usageStore"),
288
- increment: (e, n, r, i) => T(async () => {
288
+ increment: (t, n, r, i) => T(async () => {
289
289
  for (let a = 0; a < 32; a++) {
290
290
  a > 0 && await new Promise((e) => setTimeout(e, a));
291
- let o = await X(t, e, n, r);
291
+ let o = await X(e, t, n, r);
292
292
  if (o) {
293
- let e = Number(o.used ?? 0);
294
- if (await t.updateMany("_voltro_billing_usage", {
295
- used: e + i,
293
+ let t = Number(o.used ?? 0);
294
+ if (await e.updateMany("_voltro_billing_usage", {
295
+ used: t + i,
296
296
  updatedAt: /* @__PURE__ */ new Date()
297
- }, { where: _(y("id", String(o.id)), y("used", e)) }) === 1) return e + i;
297
+ }, { where: _(y("id", String(o.id)), y("used", t)) }) === 1) return t + i;
298
298
  } else {
299
- let a = C("buse"), o = await t.insertIgnore(f, {
299
+ let a = C("buse"), o = await e.insertIgnore(d, {
300
300
  id: a,
301
- tenantId: e,
301
+ tenantId: t,
302
302
  entitlementKey: n,
303
303
  period: r,
304
304
  used: i,
@@ -312,40 +312,40 @@ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
312
312
  if (String(o.id) === a) return i;
313
313
  }
314
314
  }
315
- throw Error(`billing usage increment: contention on (${e}, ${n}, ${r}) exceeded 32 attempts`);
315
+ throw Error(`billing usage increment: contention on (${t}, ${n}, ${r}) exceeded 32 attempts`);
316
316
  }, "usageStore"),
317
- pending: () => T(async () => (await t.query(D({ table: f }))).map(Y).filter((e) => e.used > e.reportedToProvider), "usageStore"),
318
- markReported: (e, n, r, i) => T(async () => {
319
- let a = await X(t, e, n, r);
320
- a && await t.updateMany(f, {
317
+ pending: () => T(async () => (await e.query(D({ table: d }))).map(Y).filter((e) => e.used > e.reportedToProvider), "usageStore"),
318
+ markReported: (t, n, r, i) => T(async () => {
319
+ let a = await X(e, t, n, r);
320
+ a && await e.updateMany(d, {
321
321
  reportedToProvider: i,
322
322
  updatedAt: /* @__PURE__ */ new Date()
323
323
  }, { where: _(y("id", String(a.id)), b("reportedToProvider", i)) });
324
324
  }, "usageStore"),
325
- claimDispatch: (e, n, r, i, { expected: a, from: o, through: s }) => T(async () => {
325
+ claimDispatch: (t, n, r, i, { expected: a, from: o, through: s }) => T(async () => {
326
326
  if (s <= o) return !1;
327
- let c = await X(t, e, n, r);
327
+ let c = await X(e, t, n, r);
328
328
  if (!c) return !1;
329
329
  let l = J[i];
330
- return await t.updateMany(f, {
330
+ return await e.updateMany(d, {
331
331
  [l]: s,
332
332
  updatedAt: /* @__PURE__ */ new Date()
333
333
  }, { where: _(y("id", String(c.id)), y(l, a), y("reportedToProvider", o)) }) === 1;
334
334
  }, "usageStore")
335
335
  }), Q = () => {
336
- for (let e of [...p(), g]) v(e);
336
+ for (let e of [...f(), g]) v(e);
337
337
  return $(new x());
338
338
  }, $ = (e) => ({
339
339
  subscriptionWrites: t(e),
340
- closures: i(e),
341
- checkouts: r(e),
342
- customers: s(e),
340
+ closures: l(e),
341
+ checkouts: c(e),
342
+ customers: a(e),
343
343
  subscriptions: q(e),
344
344
  invoices: o(e),
345
- historyJournal: c(e),
346
- historyWork: l(e),
347
- historyProgress: u(e),
345
+ historyJournal: n(e),
346
+ historyWork: i(e),
347
+ historyProgress: r(e),
348
348
  usage: Z(e),
349
- dunningNotices: n(e)
349
+ dunningNotices: p(e)
350
350
  });
351
351
  export { $ as dataStoreStores, q as dataStoreSubscriptionStore, Z as dataStoreUsageStore, j as isLive, N as isStaleStatusEvent, k as isTerminal, Q as memoryStores, M as selectCurrentSubscription };
@@ -1,20 +1,20 @@
1
- import { captureProviderAccount as e, captureProviderCustomer as t, exactProviderIdentifier as n, providerIdentityError as r, sameProviderAccount as i } from "./providerIdentity.js";
2
- import { stripeCall as a } from "./stripeClient.js";
1
+ import { stripeCall as e } from "./stripeClient.js";
2
+ import { captureProviderAccount as t, captureProviderCustomer as n, exactProviderIdentifier as r, providerIdentityError as i, sameProviderAccount as a } from "./providerIdentity.js";
3
3
  import { Effect as o } from "effect";
4
4
  // src/stripeIdentity.ts
5
5
  var s = (e) => o.try({
6
6
  try: e,
7
- catch: () => r()
8
- }), c = (t) => o.gen(function* () {
9
- let i = yield* a("stripe.accounts.retrieve", () => t.accounts.retrieve(null)), o = yield* s(() => {
10
- if (!n(i.id)) throw r();
11
- return i.id;
12
- }), c = yield* a("stripe.balance.retrieve", () => t.balance.retrieve()), l = yield* s(() => e({
7
+ catch: () => i()
8
+ }), c = (n) => o.gen(function* () {
9
+ let a = yield* e("stripe.accounts.retrieve", () => n.accounts.retrieve(null)), o = yield* s(() => {
10
+ if (!r(a.id)) throw i();
11
+ return a.id;
12
+ }), c = yield* e("stripe.balance.retrieve", () => n.balance.retrieve()), l = yield* s(() => t({
13
13
  providerAccountId: o,
14
14
  livemode: c.livemode
15
- })), u = yield* a("stripe.accounts.retrieve", () => t.accounts.retrieve(null));
15
+ })), u = yield* e("stripe.accounts.retrieve", () => n.accounts.retrieve(null));
16
16
  return yield* s(() => {
17
- if (u.id !== o) throw r();
17
+ if (u.id !== o) throw i();
18
18
  return l;
19
19
  });
20
20
  }), l = (l, u) => {
@@ -27,23 +27,23 @@ var s = (e) => o.try({
27
27
  };
28
28
  return o.gen(function* () {
29
29
  let o = yield* s(() => {
30
- if (!n(d.providerCustomerId)) throw r();
30
+ if (!r(d.providerCustomerId)) throw i();
31
31
  return Object.freeze({
32
- account: e(d.account),
32
+ account: t(d.account),
33
33
  providerCustomerId: d.providerCustomerId
34
34
  });
35
35
  }), u = yield* c(l);
36
36
  yield* s(() => {
37
- if (!i(u, o.account)) throw r();
37
+ if (!a(u, o.account)) throw i();
38
38
  });
39
- let f = yield* a("stripe.customers.retrieve", () => l.customers.retrieve(o.providerCustomerId)), p = yield* s(() => {
39
+ let f = yield* e("stripe.customers.retrieve", () => l.customers.retrieve(o.providerCustomerId)), p = yield* s(() => {
40
40
  let e = f.deleted;
41
- if (e !== void 0 && typeof e != "boolean" || f.id !== o.providerCustomerId || f.deleted !== !0 && f.livemode !== o.account.livemode) throw r();
41
+ if (e !== void 0 && typeof e != "boolean" || f.id !== o.providerCustomerId || f.deleted !== !0 && f.livemode !== o.account.livemode) throw i();
42
42
  return f.deleted === !0;
43
43
  }), m = yield* c(l);
44
44
  return yield* s(() => {
45
- if (!i(m, o.account)) throw r();
46
- return t({
45
+ if (!a(m, o.account)) throw i();
46
+ return n({
47
47
  account: o.account,
48
48
  providerCustomerId: o.providerCustomerId,
49
49
  deleted: p,
@@ -1,29 +1,29 @@
1
- import { BillingError as e } from "./types.js";
2
- import { sameProviderAccount as t } from "./providerIdentity.js";
3
- import { captureInvoiceHistoryInput as n, captureInvoiceHistoryPage as r, historyError as i } from "./invoiceHistory.js";
4
- import { stripeCall as a } from "./stripeClient.js";
5
- import { stripeAccountIdentity as o } from "./stripeIdentity.js";
1
+ import { stripeCall as e } from "./stripeClient.js";
2
+ import { stripeAccountIdentity as t } from "./stripeIdentity.js";
3
+ import { sameProviderAccount as n } from "./providerIdentity.js";
4
+ import { captureInvoiceHistoryInput as r, captureInvoiceHistoryPage as i, historyError as a } from "./invoiceHistory.js";
5
+ import { BillingError as o } from "./types.js";
6
6
  import { Effect as s } from "effect";
7
7
  // src/stripeInvoiceHistory.ts
8
- var c = (e, c) => s.gen(function* () {
9
- let f = yield* d(() => n(c)), p = yield* o(e);
10
- if (!t(p, f.account)) return yield* s.fail(i("The provider account differs before invoice history access."));
8
+ var c = (o, c) => s.gen(function* () {
9
+ let f = yield* d(() => r(c)), p = yield* t(o);
10
+ if (!n(p, f.account)) return yield* s.fail(a("The provider account differs before invoice history access."));
11
11
  let m = f.cursor;
12
12
  if (m !== void 0) {
13
- let t = yield* a("stripe.invoices.retrieve", () => e.invoices.retrieve(m.afterInvoiceId));
13
+ let t = yield* e("stripe.invoices.retrieve", () => o.invoices.retrieve(m.afterInvoiceId));
14
14
  yield* d(() => {
15
- if (t.id !== f.cursor?.afterInvoiceId || l(t.customer) !== f.providerCustomerId || t.livemode !== f.account.livemode) throw i("The invoice cursor belongs to another customer/account.");
15
+ if (t.id !== f.cursor?.afterInvoiceId || l(t.customer) !== f.providerCustomerId || t.livemode !== f.account.livemode) throw a("The invoice cursor belongs to another customer/account.");
16
16
  });
17
17
  }
18
- let h = yield* a("stripe.invoices.list", () => e.invoices.list({
18
+ let h = yield* e("stripe.invoices.list", () => o.invoices.list({
19
19
  customer: f.providerCustomerId,
20
20
  limit: f.limit,
21
21
  ...f.cursor === void 0 ? {} : { starting_after: f.cursor.afterInvoiceId }
22
22
  })), g = yield* d(() => {
23
- if (!Array.isArray(h.data) || h.data.length > f.limit || typeof h.has_more != "boolean" || h.has_more && h.data.length === 0) throw i("The provider invoice page is incomplete.");
23
+ if (!Array.isArray(h.data) || h.data.length > f.limit || typeof h.has_more != "boolean" || h.has_more && h.data.length === 0) throw a("The provider invoice page is incomplete.");
24
24
  let e = h.data.map((e) => {
25
25
  let t = u(e.status);
26
- if (l(e.customer) !== f.providerCustomerId || e.livemode !== f.account.livemode || !Number.isSafeInteger(e.created) || !Number.isSafeInteger(e.created * 1e3)) throw i();
26
+ if (l(e.customer) !== f.providerCustomerId || e.livemode !== f.account.livemode || !Number.isSafeInteger(e.created) || !Number.isSafeInteger(e.created * 1e3)) throw a();
27
27
  return {
28
28
  providerInvoiceId: e.id,
29
29
  providerCustomerId: f.providerCustomerId,
@@ -36,8 +36,8 @@ var c = (e, c) => s.gen(function* () {
36
36
  pdfUrl: e.invoice_pdf ?? null
37
37
  };
38
38
  }), t = e[e.length - 1];
39
- if (h.has_more && t === void 0) throw i();
40
- return r(f, {
39
+ if (h.has_more && t === void 0) throw a();
40
+ return i(f, {
41
41
  account: f.account,
42
42
  providerCustomerId: f.providerCustomerId,
43
43
  invoices: e,
@@ -48,8 +48,8 @@ var c = (e, c) => s.gen(function* () {
48
48
  } : null,
49
49
  observedAt: /* @__PURE__ */ new Date()
50
50
  });
51
- }), _ = yield* o(e);
52
- return t(_, f.account) ? g : yield* s.fail(i("The provider account changed during invoice history access.", !0));
51
+ }), _ = yield* t(o);
52
+ return n(_, f.account) ? g : yield* s.fail(a("The provider account changed during invoice history access.", !0));
53
53
  }), l = (e) => typeof e == "string" ? e : e?.id ?? null, u = (e) => {
54
54
  switch (e) {
55
55
  case "draft": return "draft";
@@ -57,10 +57,10 @@ var c = (e, c) => s.gen(function* () {
57
57
  case "paid": return "paid";
58
58
  case "uncollectible": return "uncollectible";
59
59
  case "void": return "void";
60
- default: throw i("The invoice history status is unsupported.");
60
+ default: throw a("The invoice history status is unsupported.");
61
61
  }
62
- }, d = (t) => s.try({
63
- try: t,
64
- catch: (t) => t instanceof e ? t : i()
62
+ }, d = (e) => s.try({
63
+ try: e,
64
+ catch: (e) => e instanceof o ? e : a()
65
65
  });
66
66
  export { c as stripeInvoiceHistory };
@@ -1,61 +1,61 @@
1
- import { BillingError as e } from "./types.js";
2
- import { assertInvoicePaymentObservation as t } from "./invoicePaymentObservation.js";
3
- import { invoiceSnapshotError as n } from "./invoiceSnapshot.js";
4
- import { stripeCall as r } from "./stripeClient.js";
1
+ import { stripeCall as e } from "./stripeClient.js";
2
+ import { invoiceSnapshotError as t } from "./invoiceSnapshot.js";
3
+ import { assertInvoicePaymentObservation as n } from "./invoicePaymentObservation.js";
4
+ import { BillingError as r } from "./types.js";
5
5
  import { Effect as i } from "effect";
6
6
  // src/stripeInvoicePayments.ts
7
7
  var a = (e) => typeof e == "string" ? e : e?.id ?? null, o = () => {
8
- throw n("The invoice payment graph could not be confirmed.");
8
+ throw t("The invoice payment graph could not be confirmed.");
9
9
  }, s = (e) => {
10
10
  if (e === null) return null;
11
11
  if (!Number.isSafeInteger(e) || e < 0 || !Number.isSafeInteger(e * 1e3)) return o();
12
12
  let t = /* @__PURE__ */ new Date(e * 1e3);
13
13
  return Number.isFinite(t.getTime()) ? t : o();
14
- }, c = (e, o) => {
14
+ }, c = (r, o) => {
15
15
  let c = Object.freeze({ ...o });
16
16
  return i.gen(function* () {
17
17
  let o = [], l = /* @__PURE__ */ new Set(), f, p = !1;
18
- for (let t = 0; t < 100; t++) {
19
- let t = yield* r("stripe.invoicePayments.list", () => e.invoicePayments.list({
18
+ for (let n = 0; n < 100; n++) {
19
+ let n = yield* e("stripe.invoicePayments.list", () => r.invoicePayments.list({
20
20
  invoice: c.providerInvoiceId,
21
21
  limit: 100,
22
22
  ...f === void 0 ? {} : { starting_after: f }
23
23
  }));
24
- if (!Array.isArray(t.data) || t.data.length > 100 || typeof t.has_more != "boolean" || (t.has_more || f !== void 0) && t.data.length === 0) return yield* i.fail(n("The invoice payment page is incomplete."));
25
- for (let f of t.data) {
24
+ if (!Array.isArray(n.data) || n.data.length > 100 || typeof n.has_more != "boolean" || (n.has_more || f !== void 0) && n.data.length === 0) return yield* i.fail(t("The invoice payment page is incomplete."));
25
+ for (let f of n.data) {
26
26
  if (!f.id || l.has(f.id) || a(f.invoice) !== c.providerInvoiceId || f.livemode !== c.livemode || f.currency !== c.currency || ![
27
27
  "open",
28
28
  "paid",
29
29
  "canceled"
30
- ].includes(f.status)) return yield* i.fail(n("The invoice payment belongs to a different source or has an invalid state."));
30
+ ].includes(f.status)) return yield* i.fail(t("The invoice payment belongs to a different source or has an invalid state."));
31
31
  l.add(f.id);
32
- let t = f.payment;
33
- if (!t || typeof t.type != "string" || !t.type) return yield* i.fail(n("The invoice payment source is unavailable."));
34
- let p = t.type === "payment_intent" ? a(t.payment_intent) : t.type === "charge" ? a(t.charge) : t.type === "payment_record" ? a(t.payment_record) : null;
32
+ let n = f.payment;
33
+ if (!n || typeof n.type != "string" || !n.type) return yield* i.fail(t("The invoice payment source is unavailable."));
34
+ let p = n.type === "payment_intent" ? a(n.payment_intent) : n.type === "charge" ? a(n.charge) : n.type === "payment_record" ? a(n.payment_record) : null;
35
35
  if ([
36
36
  "payment_intent",
37
37
  "charge",
38
38
  "payment_record"
39
- ].includes(t.type) && p === null) return yield* i.fail(n("The invoice payment source identity is missing."));
39
+ ].includes(n.type) && p === null) return yield* i.fail(t("The invoice payment source identity is missing."));
40
40
  let m = null;
41
- if (f.status === "paid" && t.type === "payment_intent" && p !== null) {
42
- let t = yield* r("stripe.paymentIntents.retrieve", () => e.paymentIntents.retrieve(p));
43
- if (t.id !== p || a(t.customer) !== c.providerCustomerId || t.currency !== c.currency || t.livemode !== c.livemode) return yield* i.fail(n("The payment intent belongs to a different customer or mode."));
44
- let o = a(t.latest_charge);
41
+ if (f.status === "paid" && n.type === "payment_intent" && p !== null) {
42
+ let n = yield* e("stripe.paymentIntents.retrieve", () => r.paymentIntents.retrieve(p));
43
+ if (n.id !== p || a(n.customer) !== c.providerCustomerId || n.currency !== c.currency || n.livemode !== c.livemode) return yield* i.fail(t("The payment intent belongs to a different customer or mode."));
44
+ let o = a(n.latest_charge);
45
45
  if (o !== null) {
46
46
  m = {
47
- ...yield* u(e, c, o, p),
48
- paymentIntentStatus: t.status,
49
- paymentIntentReceivedMinor: t.amount_received
47
+ ...yield* u(r, c, o, p),
48
+ paymentIntentStatus: n.status,
49
+ paymentIntentReceivedMinor: n.amount_received
50
50
  };
51
- let s = yield* r("stripe.paymentIntents.retrieve", () => e.paymentIntents.retrieve(p));
52
- if (s.id !== t.id || a(s.customer) !== a(t.customer) || s.currency !== t.currency || s.livemode !== t.livemode || s.status !== t.status || s.amount_received !== t.amount_received || a(s.latest_charge) !== o) return yield* i.fail(n("The payment intent changed during invoice observation.", !0));
51
+ let s = yield* e("stripe.paymentIntents.retrieve", () => r.paymentIntents.retrieve(p));
52
+ if (s.id !== n.id || a(s.customer) !== a(n.customer) || s.currency !== n.currency || s.livemode !== n.livemode || s.status !== n.status || s.amount_received !== n.amount_received || a(s.latest_charge) !== o) return yield* i.fail(t("The payment intent changed during invoice observation.", !0));
53
53
  }
54
- } else f.status === "paid" && t.type === "charge" && p !== null && (m = yield* u(e, c, p, null));
54
+ } else f.status === "paid" && n.type === "charge" && p !== null && (m = yield* u(r, c, p, null));
55
55
  let h = yield* d(() => s(f.status_transitions.paid_at));
56
56
  o.push({
57
57
  providerInvoicePaymentId: f.id,
58
- sourceType: t.type,
58
+ sourceType: n.type,
59
59
  sourceId: p,
60
60
  status: f.status,
61
61
  amountPaidMinor: f.amount_paid,
@@ -63,20 +63,20 @@ var a = (e) => typeof e == "string" ? e : e?.id ?? null, o = () => {
63
63
  cash: m
64
64
  });
65
65
  }
66
- if (!t.has_more) {
66
+ if (!n.has_more) {
67
67
  p = !0;
68
68
  break;
69
69
  }
70
- f = t.data.at(-1)?.id;
70
+ f = n.data.at(-1)?.id;
71
71
  }
72
- if (!p) return yield* i.fail(n("The complete payment graph exceeds its observation bound."));
72
+ if (!p) return yield* i.fail(t("The complete payment graph exceeds its observation bound."));
73
73
  let m = {
74
74
  protocol: "voltro.invoice-payments.v1",
75
75
  ...c,
76
76
  observedAt: /* @__PURE__ */ new Date(),
77
77
  payments: o
78
78
  };
79
- return yield* d(() => t(m)), m;
79
+ return yield* d(() => n(m)), m;
80
80
  });
81
81
  }, l = (e, t, n, r) => e.id !== n || a(e.customer) !== t.providerCustomerId || e.currency !== t.currency || e.livemode !== t.livemode || a(e.payment_intent) !== r ? o() : {
82
82
  providerChargeId: e.id,
@@ -90,17 +90,17 @@ var a = (e) => typeof e == "string" ? e : e?.id ?? null, o = () => {
90
90
  paid: e.paid,
91
91
  captured: e.captured,
92
92
  disputed: e.disputed
93
- }, u = (e, t, o, s) => i.gen(function* () {
94
- let c = yield* r("stripe.charges.retrieve", () => e.charges.retrieve(o)), u = yield* d(() => l(c, t, o, s)), f = [], p = /* @__PURE__ */ new Set(), m, h = !1;
93
+ }, u = (n, r, o, s) => i.gen(function* () {
94
+ let c = yield* e("stripe.charges.retrieve", () => n.charges.retrieve(o)), u = yield* d(() => l(c, r, o, s)), f = [], p = /* @__PURE__ */ new Set(), m, h = !1;
95
95
  for (let s = 0; s < 100; s++) {
96
- let s = yield* r("stripe.refunds.list", () => e.refunds.list({
96
+ let s = yield* e("stripe.refunds.list", () => n.refunds.list({
97
97
  charge: o,
98
98
  limit: 100,
99
99
  ...m === void 0 ? {} : { starting_after: m }
100
100
  }));
101
- if (!Array.isArray(s.data) || s.data.length > 100 || typeof s.has_more != "boolean" || (s.has_more || m !== void 0) && s.data.length === 0) return yield* i.fail(n("The refund page is incomplete."));
101
+ if (!Array.isArray(s.data) || s.data.length > 100 || typeof s.has_more != "boolean" || (s.has_more || m !== void 0) && s.data.length === 0) return yield* i.fail(t("The refund page is incomplete."));
102
102
  for (let e of s.data) {
103
- if (!e.id || p.has(e.id) || a(e.charge) !== o || e.currency !== t.currency) return yield* i.fail(n("The refund belongs to a different charge or repeats its identity."));
103
+ if (!e.id || p.has(e.id) || a(e.charge) !== o || e.currency !== r.currency) return yield* i.fail(t("The refund belongs to a different charge or repeats its identity."));
104
104
  p.add(e.id), f.push({
105
105
  providerRefundId: e.id,
106
106
  amountMinor: e.amount,
@@ -114,16 +114,16 @@ var a = (e) => typeof e == "string" ? e : e?.id ?? null, o = () => {
114
114
  }
115
115
  m = s.data.at(-1)?.id;
116
116
  }
117
- if (!h) return yield* i.fail(n("The complete payment graph exceeds its observation bound."));
118
- let g = yield* r("stripe.charges.retrieve", () => e.charges.retrieve(o)), _ = yield* d(() => l(g, t, o, s));
117
+ if (!h) return yield* i.fail(t("The complete payment graph exceeds its observation bound."));
118
+ let g = yield* e("stripe.charges.retrieve", () => n.charges.retrieve(o)), _ = yield* d(() => l(g, r, o, s));
119
119
  return JSON.stringify(u) === JSON.stringify(_) ? {
120
120
  ..._,
121
121
  refunds: f,
122
122
  paymentIntentStatus: null,
123
123
  paymentIntentReceivedMinor: null
124
- } : yield* i.fail(n("The payment changed during observation; retry the complete invoice read.", !0));
125
- }), d = (t) => i.try({
126
- try: t,
127
- catch: (t) => t instanceof e ? t : n("The invoice payment observation is invalid.")
124
+ } : yield* i.fail(t("The payment changed during observation; retry the complete invoice read.", !0));
125
+ }), d = (e) => i.try({
126
+ try: e,
127
+ catch: (e) => e instanceof r ? e : t("The invoice payment observation is invalid.")
128
128
  });
129
129
  export { c as stripeInvoicePayments };