@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
@@ -0,0 +1,145 @@
1
+ import { BillingError as e } from "./types.js";
2
+ import { and as t, eq as n, gt as r, id as i, integer as a, isNotNull as o, neq as s, or as c, table as l, text as u, timestamp as d } from "@voltro/database";
3
+ // src/invoicePaymentEpoch.ts
4
+ var f = "_voltro_billing_invoice_payment_heads", p = "_voltro_billing_invoice_payment_corrections", m = "_voltro_billing_account_invoices", h = "voltro.invoice-payment-epoch.v1", g = 2147483647, _ = l(f, {
5
+ id: i({ prefix: "bipe" }),
6
+ protocol: u(),
7
+ tenantId: u(),
8
+ provider: u(),
9
+ providerAccountId: u().maxLength(191),
10
+ livemode: a(),
11
+ providerCustomerId: u().maxLength(191),
12
+ identityKey: u().maxLength(64),
13
+ epoch: a(),
14
+ createdAt: d(),
15
+ updatedAt: d()
16
+ }).unique("billingInvoicePaymentHeadIdentity", ["identityKey"]).index("billingInvoicePaymentHeadTenant", ["tenantId"]), v = l(p, {
17
+ id: i({ prefix: "bipc" }),
18
+ scopeKey: u().maxLength(64),
19
+ headId: u(),
20
+ providerEventId: u().maxLength(191),
21
+ epoch: a(),
22
+ createdAt: d()
23
+ }).unique("billingInvoicePaymentCorrectionIdentity", ["scopeKey", "providerEventId"]).unique("billingInvoicePaymentCorrectionEpoch", ["scopeKey", "epoch"]), y = (t = "Original invoice payment custody requires reconciliation.", n = !1) => new e({
24
+ source: "invoicePaymentEpoch",
25
+ message: t,
26
+ transient: n
27
+ }), b = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, x = (e) => typeof e == "number" && Number.isInteger(e) && e >= 0 && e <= 2147483647, S = (e) => {
28
+ if (![
29
+ e.tenantId,
30
+ e.provider,
31
+ e.providerAccountId,
32
+ e.providerCustomerId
33
+ ].every(b) || e.providerAccountId.length > 191 || e.providerCustomerId.length > 191 || typeof e.livemode != "boolean") throw y();
34
+ return Object.freeze({
35
+ tenantId: e.tenantId,
36
+ provider: e.provider,
37
+ providerAccountId: e.providerAccountId,
38
+ livemode: e.livemode,
39
+ providerCustomerId: e.providerCustomerId
40
+ });
41
+ }, C = (e) => {
42
+ if (!b(e.headId) || !x(e.epoch)) throw y();
43
+ return Object.freeze({
44
+ headId: e.headId,
45
+ epoch: e.epoch
46
+ });
47
+ }, w = async (e) => {
48
+ let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
49
+ h,
50
+ e.provider,
51
+ e.providerAccountId,
52
+ e.livemode,
53
+ e.providerCustomerId
54
+ ])));
55
+ return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
56
+ }, T = (e, t, n = !1) => ({
57
+ table: e,
58
+ predicate: t,
59
+ ...n ? { lock: "update" } : {},
60
+ order: [],
61
+ take: 2,
62
+ skip: void 0,
63
+ projection: void 0
64
+ }), E = async (e, i, a, l) => {
65
+ let u = await e.query(T(f, n("identityKey", a), l));
66
+ if (u.length > 1) throw y();
67
+ let d = u[0];
68
+ if (!d) return null;
69
+ if (!b(d.id) || d.protocol !== h || d.identityKey !== a || d.tenantId !== i.tenantId || d.provider !== i.provider || d.providerAccountId !== i.providerAccountId || d.livemode !== +!!i.livemode || d.providerCustomerId !== i.providerCustomerId || !x(d.epoch)) throw y();
70
+ let g = d.id, _ = d.epoch, v = await e.query({
71
+ ...T(p, t(n("scopeKey", a), c(s("headId", g), r("epoch", _))), l),
72
+ projection: ["id"]
73
+ }), S = await e.query({
74
+ ...T(m, t(n("provider", i.provider), n("providerAccountId", i.providerAccountId), n("livemode", +!!i.livemode), n("providerCustomerId", i.providerCustomerId), c(t(o("paymentHeadId"), s("paymentHeadId", g)), r("paymentEpoch", _))), l),
75
+ projection: ["id"]
76
+ });
77
+ if (v.length || S.length) throw y();
78
+ if (_ > 0) {
79
+ let r = await e.query(T(p, t(n("scopeKey", a), n("epoch", _)), l));
80
+ if (r.length !== 1 || r[0]?.headId !== g || !b(r[0]?.providerEventId)) throw y();
81
+ }
82
+ return {
83
+ headId: g,
84
+ epoch: _
85
+ };
86
+ }, D = async (e, t, n = !1) => {
87
+ let r = S(t);
88
+ return E(e, r, await w(r), n);
89
+ }, O = async (e, r, i, a) => {
90
+ let s = S(r), l = await w(s);
91
+ return e.transactional(async (e) => {
92
+ let r = await E(e, s, l, !0);
93
+ if (r === null) {
94
+ if (!i) throw y();
95
+ let a = await e.query({
96
+ ...T(m, t(n("provider", s.provider), n("providerAccountId", s.providerAccountId), n("livemode", +!!s.livemode), n("providerCustomerId", s.providerCustomerId), c(o("paymentHeadId"), o("paymentEpoch"))), !0),
97
+ projection: ["id"]
98
+ }), u = await e.query({
99
+ ...T(p, n("scopeKey", l), !0),
100
+ projection: ["id"]
101
+ });
102
+ if (a.length || u.length) throw y();
103
+ let d = /* @__PURE__ */ new Date();
104
+ if (await e.insertIgnore(f, {
105
+ id: "bipe_" + globalThis.crypto.randomUUID(),
106
+ protocol: h,
107
+ ...s,
108
+ livemode: +!!s.livemode,
109
+ identityKey: l,
110
+ epoch: 0,
111
+ createdAt: d,
112
+ updatedAt: d
113
+ }, { conflictColumns: ["identityKey"] }), r = await E(e, s, l, !0), r === null) throw y("Invoice payment custody could not be retained.", !0);
114
+ }
115
+ return a(e, r, l);
116
+ });
117
+ }, k = async (e, r, i) => {
118
+ if (!b(i) || i.length > 191) throw y();
119
+ return O(e, r, !0, async (e, a, o) => {
120
+ let s = t(n("scopeKey", o), n("providerEventId", i)), c = await e.query(T(p, s, !0));
121
+ if (c.length > 1) throw y();
122
+ if (c[0]) {
123
+ let e = c[0];
124
+ if (e.headId !== a.headId || !x(e.epoch) || e.epoch < 1 || e.epoch > a.epoch) throw y();
125
+ return a;
126
+ }
127
+ if (a.epoch === 2147483647) throw y("Invoice payment correction generation is exhausted.");
128
+ let l = a.epoch + 1, u = /* @__PURE__ */ new Date(), d = "bipc_" + globalThis.crypto.randomUUID();
129
+ if (await e.insert(p, {
130
+ id: d,
131
+ scopeKey: o,
132
+ headId: a.headId,
133
+ providerEventId: i,
134
+ epoch: l,
135
+ createdAt: u
136
+ }), !await e.update(f, a.headId, {
137
+ epoch: l,
138
+ updatedAt: u
139
+ })) throw y("Invoice payment correction was not retained.", !0);
140
+ let m = await E(e, S(r), o, !0), h = await e.query(T(p, s, !0));
141
+ if (!m || m.headId !== a.headId || m.epoch !== l || h.length !== 1 || h[0]?.id !== d || h[0]?.headId !== a.headId || h[0]?.epoch !== l) throw y("Invoice payment correction could not be read back.", !0);
142
+ return m;
143
+ });
144
+ };
145
+ export { g as MAX_INVOICE_PAYMENT_EPOCH, v as billingInvoicePaymentCorrectionsTable, _ as billingInvoicePaymentHeadsTable, C as captureInvoicePaymentEpoch, S as captureInvoicePaymentOwner, D as currentInvoicePaymentEpoch, k as invalidateInvoicePayments, O as withInvoicePaymentEpoch };
@@ -0,0 +1,64 @@
1
+ import { Schema as e } from "effect";
2
+ // src/invoicePaymentObservation.ts
3
+ var t = e.Number.check(e.makeFilter((e) => Number.isSafeInteger(e) && e >= 0)), n = e.Number.check(e.makeFilter((e) => Number.isSafeInteger(e))), r = e.NonEmptyString, i = e.Struct({
4
+ providerRefundId: r,
5
+ amountMinor: t,
6
+ currency: e.String,
7
+ status: e.NullOr(e.String)
8
+ }), a = e.Struct({
9
+ providerChargeId: r,
10
+ providerPaymentIntentId: e.NullOr(r),
11
+ providerCustomerId: r,
12
+ paymentIntentStatus: e.NullOr(e.String),
13
+ paymentIntentReceivedMinor: e.NullOr(t),
14
+ livemode: e.Boolean,
15
+ currency: e.String,
16
+ amountMinor: t,
17
+ capturedMinor: t,
18
+ refundedMinor: t,
19
+ paid: e.Boolean,
20
+ captured: e.Boolean,
21
+ disputed: e.Boolean,
22
+ refunds: e.Array(i)
23
+ }), o = e.Struct({
24
+ protocol: e.Literal("voltro.invoice-payments.v1"),
25
+ providerInvoiceId: r,
26
+ providerCustomerId: r,
27
+ livemode: e.Boolean,
28
+ currency: e.String,
29
+ prePaymentCreditNotesMinor: t,
30
+ postPaymentCreditNotesMinor: t,
31
+ invoiceTotalMinor: e.optionalKey(e.NullOr(n)),
32
+ startingBalanceMinor: e.optionalKey(e.NullOr(n)),
33
+ endingBalanceMinor: e.optionalKey(e.NullOr(n)),
34
+ observedAt: e.DateFromString,
35
+ payments: e.Array(e.Struct({
36
+ providerInvoicePaymentId: r,
37
+ sourceType: r,
38
+ sourceId: e.NullOr(r),
39
+ status: e.Literals([
40
+ "open",
41
+ "paid",
42
+ "canceled"
43
+ ]),
44
+ amountPaidMinor: e.NullOr(t),
45
+ paidAt: e.NullOr(e.DateFromString),
46
+ cash: e.NullOr(a)
47
+ }))
48
+ }), s = (t) => {
49
+ if (!e.is(o)(t) || t.payments.length > 1e4 || !/^[a-z]{3}$/.test(t.currency) || !Number.isSafeInteger(t.observedAt.getTime())) throw c();
50
+ let n = /* @__PURE__ */ new Set();
51
+ for (let e of t.payments) {
52
+ if (n.has(e.providerInvoicePaymentId) || e.status === "paid" && (e.amountPaidMinor === null || e.paidAt === null) || e.paidAt !== null && !Number.isSafeInteger(e.paidAt.getTime())) throw c();
53
+ n.add(e.providerInvoicePaymentId);
54
+ let r = e.cash;
55
+ if (r === null) continue;
56
+ if (r.providerCustomerId !== t.providerCustomerId || r.livemode !== t.livemode || r.currency !== t.currency || r.capturedMinor > r.amountMinor || r.refundedMinor > r.capturedMinor || r.refunds.length > 1e4 || e.sourceType === "payment_intent" && (r.providerPaymentIntentId !== e.sourceId || r.paymentIntentStatus === null || r.paymentIntentReceivedMinor === null) || e.sourceType === "charge" && (r.providerChargeId !== e.sourceId || r.providerPaymentIntentId !== null || r.paymentIntentStatus !== null || r.paymentIntentReceivedMinor !== null) || !["charge", "payment_intent"].includes(e.sourceType)) throw c();
57
+ let i = /* @__PURE__ */ new Set();
58
+ for (let e of r.refunds) {
59
+ if (i.has(e.providerRefundId) || e.currency !== t.currency) throw c();
60
+ i.add(e.providerRefundId);
61
+ }
62
+ }
63
+ }, c = () => /* @__PURE__ */ TypeError("Complete invoice payment observations require exact identities, amounts and source ownership.");
64
+ export { o as InvoicePaymentObservationSchema, s as assertInvoicePaymentObservation };
@@ -1,65 +1,75 @@
1
- import { BillingError as e } from "./types.js";
2
- import { Schema as t } from "effect";
1
+ import { InvoicePaymentObservationSchema as e, assertInvoicePaymentObservation as t } from "./invoicePaymentObservation.js";
2
+ import { BillingError as n } from "./types.js";
3
+ import { Schema as r } from "effect";
3
4
  // src/invoiceSnapshot.ts
4
- var n = (t, n = !1) => new e({
5
+ var i = (e, t = !1) => new n({
5
6
  source: "invoiceSnapshot",
6
- message: t,
7
- transient: n
8
- }), r = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, i = (e) => e === null || r(e), a = (e) => e instanceof Date && Number.isSafeInteger(e.getTime()), o = (e) => Number.isSafeInteger(e) && e >= 0, s = t.Struct({
9
- providerInvoiceId: t.String,
10
- providerCustomerId: t.String,
11
- providerSubscriptionId: t.NullOr(t.String),
12
- providerRevisionId: t.NullOr(t.String),
13
- status: t.Literals([
7
+ message: e,
8
+ transient: t
9
+ }), a = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, o = (e) => e === null || a(e), s = (e) => e instanceof Date && Number.isSafeInteger(e.getTime()), c = (e) => Number.isSafeInteger(e) && e >= 0, l = r.Struct({
10
+ paymentObservation: r.optionalKey(r.NullOr(e)),
11
+ providerInvoiceId: r.String,
12
+ providerCustomerId: r.String,
13
+ providerSubscriptionId: r.NullOr(r.String),
14
+ providerRevisionId: r.NullOr(r.String),
15
+ status: r.Literals([
14
16
  "open",
15
17
  "paid",
16
18
  "uncollectible",
17
19
  "void"
18
20
  ]),
19
- livemode: t.Boolean,
20
- currency: t.String,
21
- amountDueMinor: t.Number,
22
- amountPaidMinor: t.Number,
23
- amountRemainingMinor: t.Number,
24
- finalizedAt: t.DateFromString,
25
- paidAt: t.NullOr(t.DateFromString),
26
- observedAt: t.DateFromString,
27
- lines: t.Array(t.Struct({
28
- providerLineId: t.String,
29
- providerSubscriptionId: t.NullOr(t.String),
30
- providerSubscriptionItemId: t.NullOr(t.String),
31
- providerPriceId: t.NullOr(t.String),
32
- amountMinor: t.Number,
33
- currency: t.String,
34
- quantityDecimal: t.NullOr(t.String),
35
- periodStart: t.DateFromString,
36
- periodEnd: t.DateFromString,
37
- proration: t.NullOr(t.Boolean)
21
+ livemode: r.Boolean,
22
+ currency: r.String,
23
+ amountDueMinor: r.Number,
24
+ amountPaidMinor: r.Number,
25
+ amountRemainingMinor: r.Number,
26
+ finalizedAt: r.DateFromString,
27
+ paidAt: r.NullOr(r.DateFromString),
28
+ observedAt: r.DateFromString,
29
+ lines: r.Array(r.Struct({
30
+ providerLineId: r.String,
31
+ providerSubscriptionId: r.NullOr(r.String),
32
+ providerSubscriptionItemId: r.NullOr(r.String),
33
+ providerPriceId: r.NullOr(r.String),
34
+ amountMinor: r.Number,
35
+ currency: r.String,
36
+ quantityDecimal: r.NullOr(r.String),
37
+ periodStart: r.DateFromString,
38
+ periodEnd: r.DateFromString,
39
+ proration: r.NullOr(r.Boolean)
38
40
  }))
39
- }), c = t.Struct({
40
- protocol: t.Literal("voltro.invoice-observation.v1"),
41
- snapshot: s
42
- }), l = (e) => (d(e), t.encodeUnknownSync(c)({
41
+ }), u = r.Struct({
42
+ protocol: r.Literal("voltro.invoice-observation.v1"),
43
+ snapshot: l
44
+ }), d = (e) => (p(e), r.encodeUnknownSync(u)({
43
45
  protocol: "voltro.invoice-observation.v1",
44
46
  snapshot: e
45
- })), u = (e) => {
47
+ })), f = (e) => {
46
48
  try {
47
- let n = t.decodeUnknownSync(c)(e).snapshot;
48
- return d(n), n;
49
+ let t = r.decodeUnknownSync(u)(e).snapshot, n = {
50
+ ...t,
51
+ paymentObservation: t.paymentObservation ?? null
52
+ };
53
+ return p(n), n;
49
54
  } catch {
50
- throw n("The stored complete invoice observation could not be confirmed.");
55
+ throw i("The stored complete invoice observation could not be confirmed.");
51
56
  }
52
- }, d = (e) => {
53
- if (!r(e.providerInvoiceId) || !r(e.providerCustomerId) || !i(e.providerSubscriptionId) || !i(e.providerRevisionId) || ![
57
+ }, p = (e) => {
58
+ if (!a(e.providerInvoiceId) || !a(e.providerCustomerId) || !o(e.providerSubscriptionId) || !o(e.providerRevisionId) || ![
54
59
  "open",
55
60
  "paid",
56
61
  "uncollectible",
57
62
  "void"
58
- ].includes(e.status) || typeof e.livemode != "boolean" || !/^[a-z]{3}$/.test(e.currency) || !o(e.amountDueMinor) || !o(e.amountPaidMinor) || !o(e.amountRemainingMinor) || !a(e.finalizedAt) || !a(e.observedAt) || e.paidAt !== null && (!a(e.paidAt) || e.paidAt < e.finalizedAt) || e.status === "paid" && e.paidAt === null || !Array.isArray(e.lines) || e.lines.length > 1e4) throw n("A complete finalized invoice observation is required.");
59
- let t = /* @__PURE__ */ new Set();
60
- for (let o of e.lines) {
61
- if (!r(o.providerLineId) || t.has(o.providerLineId) || !i(o.providerSubscriptionId) || !i(o.providerSubscriptionItemId) || !i(o.providerPriceId) || !Number.isSafeInteger(o.amountMinor) || o.currency !== e.currency || o.quantityDecimal !== null && (typeof o.quantityDecimal != "string" || !/^\d+(?:\.\d{1,12})?$/.test(o.quantityDecimal)) || !a(o.periodStart) || !a(o.periodEnd) || o.periodEnd < o.periodStart || o.proration !== null && typeof o.proration != "boolean") throw n("Invoice lines must retain exact identities, money and periods.");
62
- t.add(o.providerLineId);
63
+ ].includes(e.status) || typeof e.livemode != "boolean" || !/^[a-z]{3}$/.test(e.currency) || !c(e.amountDueMinor) || !c(e.amountPaidMinor) || !c(e.amountRemainingMinor) || !s(e.finalizedAt) || !s(e.observedAt) || e.paidAt !== null && (!s(e.paidAt) || e.paidAt < e.finalizedAt) || e.status === "paid" && e.paidAt === null || !Array.isArray(e.lines) || e.lines.length > 1e4) throw i("A complete finalized invoice observation is required.");
64
+ if (e.paymentObservation !== null) try {
65
+ if (t(e.paymentObservation), e.paymentObservation.providerInvoiceId !== e.providerInvoiceId || e.paymentObservation.providerCustomerId !== e.providerCustomerId || e.paymentObservation.currency !== e.currency || e.paymentObservation.livemode !== e.livemode) throw TypeError("Invoice payment identity mismatch.");
66
+ } catch {
67
+ throw i("Invoice payment observations must match the complete invoice ownership.");
68
+ }
69
+ let n = /* @__PURE__ */ new Set();
70
+ for (let t of e.lines) {
71
+ if (!a(t.providerLineId) || n.has(t.providerLineId) || !o(t.providerSubscriptionId) || !o(t.providerSubscriptionItemId) || !o(t.providerPriceId) || !Number.isSafeInteger(t.amountMinor) || t.currency !== e.currency || t.quantityDecimal !== null && (typeof t.quantityDecimal != "string" || !/^\d+(?:\.\d{1,12})?$/.test(t.quantityDecimal)) || !s(t.periodStart) || !s(t.periodEnd) || t.periodEnd < t.periodStart || t.proration !== null && typeof t.proration != "boolean") throw i("Invoice lines must retain exact identities, money and periods.");
72
+ n.add(t.providerLineId);
63
73
  }
64
74
  };
65
- export { d as assertInvoiceSnapshot, u as decodeInvoiceSnapshot, l as encodeInvoiceSnapshot, n as invoiceSnapshotError };
75
+ export { p as assertInvoiceSnapshot, f as decodeInvoiceSnapshot, d as encodeInvoiceSnapshot, i as invoiceSnapshotError };
@@ -1,48 +1,58 @@
1
- import { BillingError as e } from "./types.js";
2
- import { decodeInvoiceSnapshot as t, encodeInvoiceSnapshot as n, invoiceSnapshotError as r } from "./invoiceSnapshot.js";
3
- import { Effect as i } from "effect";
4
- import { and as a, eq as o, id as s, integer as c, json as l, table as u, text as d, timestamp as f } from "@voltro/database";
1
+ import { captureInvoicePaymentEpoch as e, currentInvoicePaymentEpoch as t, invalidateInvoicePayments as n, withInvoicePaymentEpoch as r } from "./invoicePaymentEpoch.js";
2
+ import { decodeInvoiceSnapshot as i, encodeInvoiceSnapshot as a, invoiceSnapshotError as o } from "./invoiceSnapshot.js";
3
+ import { BillingError as s } from "./types.js";
4
+ import { Effect as c } from "effect";
5
+ import { and as l, eq as u, id as d, integer as f, json as p, table as m, text as h, timestamp as g } from "@voltro/database";
6
+ import "@voltro/runtime";
5
7
  // src/invoiceStore.ts
6
- var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_observations", {
7
- id: s({ prefix: "binvobs" }),
8
- tenantId: d(),
9
- provider: d(),
10
- providerInvoiceId: d(),
11
- providerCustomerId: d(),
12
- identityKey: d().maxLength(64),
13
- revision: c(),
14
- providerSnapshot: l().serverOnly(),
15
- createdAt: f()
16
- }).index("byBillingInvoiceObservationTenant", ["tenantId"]).unique("byBillingInvoiceObservationIdentity", ["identityKey"]), h = u(p, {
17
- id: s({ prefix: "binvobs" }),
18
- tenantId: d(),
19
- provider: d(),
20
- providerAccountId: d().maxLength(191),
21
- livemode: c(),
22
- providerInvoiceId: d(),
23
- providerCustomerId: d(),
24
- identityKey: d().maxLength(64),
25
- revision: c(),
26
- providerSnapshot: l().serverOnly(),
27
- createdAt: f()
28
- }).index("byBillingAccountInvoiceTenant", ["tenantId"]).unique("byBillingAccountInvoiceIdentity", ["identityKey"]), g = 2147483647, _ = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, v = (e, t) => ({
29
- table: p,
8
+ var _ = "_voltro_billing_account_invoices", v = m("_voltro_billing_invoice_observations", {
9
+ id: d({ prefix: "binvobs" }),
10
+ tenantId: h(),
11
+ provider: h(),
12
+ providerInvoiceId: h(),
13
+ providerCustomerId: h(),
14
+ identityKey: h().maxLength(64),
15
+ revision: f(),
16
+ providerSnapshot: p().serverOnly(),
17
+ createdAt: g()
18
+ }).index("byBillingInvoiceObservationTenant", ["tenantId"]).unique("byBillingInvoiceObservationIdentity", ["identityKey"]), y = m(_, {
19
+ id: d({ prefix: "binvobs" }),
20
+ tenantId: h(),
21
+ provider: h(),
22
+ providerAccountId: h().maxLength(191),
23
+ livemode: f(),
24
+ providerInvoiceId: h(),
25
+ providerCustomerId: h(),
26
+ identityKey: h().maxLength(64),
27
+ revision: f(),
28
+ providerSnapshot: p().serverOnly(),
29
+ paymentHeadId: h().nullable().serverOnly(),
30
+ paymentEpoch: f().nullable().serverOnly(),
31
+ createdAt: g()
32
+ }).index("byBillingAccountInvoiceTenant", ["tenantId"]).index("byBillingInvoicePaymentCustomer", [
33
+ "provider",
34
+ "providerAccountId",
35
+ "livemode",
36
+ "providerCustomerId",
37
+ "paymentEpoch"
38
+ ]).unique("byBillingAccountInvoiceIdentity", ["identityKey"]), b = 2147483647, x = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, S = (e, t) => ({
39
+ table: _,
30
40
  predicate: e,
31
41
  order: [],
32
42
  take: t,
33
43
  skip: void 0,
34
44
  projection: void 0
35
- }), y = (t) => i.tryPromise({
36
- try: t,
37
- catch: (t) => t instanceof e ? t : r("The native invoice observation could not be persisted or read.", !0)
38
- }), b = (e) => {
45
+ }), C = (e) => c.tryPromise({
46
+ try: e,
47
+ catch: (e) => e instanceof s ? e : o("The native invoice observation could not be persisted or read.", !0)
48
+ }), w = (e) => {
39
49
  if (![
40
50
  e.tenantId,
41
51
  e.provider,
42
52
  e.providerAccountId,
43
53
  e.providerCustomerId,
44
54
  e.providerInvoiceId
45
- ].every(_) || typeof e.livemode != "boolean") throw r("A valid customer-bound invoice identity is required.");
55
+ ].every(x) || typeof e.livemode != "boolean") throw o("A valid customer-bound invoice identity is required.");
46
56
  return Object.freeze({
47
57
  tenantId: e.tenantId,
48
58
  provider: e.provider,
@@ -51,7 +61,7 @@ var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_obser
51
61
  providerCustomerId: e.providerCustomerId,
52
62
  providerInvoiceId: e.providerInvoiceId
53
63
  });
54
- }, x = async (e) => {
64
+ }, T = async (e) => {
55
65
  let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
56
66
  "voltro.account-invoice-observation.v1",
57
67
  e.provider,
@@ -60,73 +70,97 @@ var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_obser
60
70
  e.providerInvoiceId
61
71
  ])));
62
72
  return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
63
- }, S = (e, t) => e.tenantId === t.tenantId && e.provider === t.provider && e.providerAccountId === t.providerAccountId && e.livemode === t.livemode && e.providerCustomerId === t.providerCustomerId && e.providerInvoiceId === t.providerInvoiceId, C = (e, t) => {
64
- if (!S(e, t)) throw r("The invoice is bound to a different tenant or billing customer.");
65
- }, w = (e) => {
66
- let n = e.tenantId, i = e.provider, a = e.providerInvoiceId, o = e.providerAccountId, s = e.livemode, c = e.providerCustomerId, l = e.identityKey, u = e.revision, d = e.id;
67
- if (!_(n) || !_(i) || !_(a) || !_(c) || !_(d) || !_(o) || s !== 0 && s !== 1 || typeof l != "string" || !/^[0-9a-f]{64}$/.test(l) || typeof u != "number" || !Number.isInteger(u) || u < 1 || u > g) throw r("The native invoice observation identity is invalid.");
68
- let f = t(e.providerSnapshot);
69
- if (f.providerCustomerId !== c || f.providerInvoiceId !== a || f.livemode !== (s === 1)) throw r("The stored observation has a different customer or invoice.");
73
+ }, E = (e, t) => e.tenantId === t.tenantId && e.provider === t.provider && e.providerAccountId === t.providerAccountId && e.livemode === t.livemode && e.providerCustomerId === t.providerCustomerId && e.providerInvoiceId === t.providerInvoiceId, D = (e, t) => {
74
+ if (!E(e, t)) throw o("The invoice is bound to a different tenant or billing customer.");
75
+ }, O = (t) => {
76
+ let n = t.tenantId, r = t.provider, a = t.providerInvoiceId, s = t.providerAccountId, c = t.livemode, l = t.providerCustomerId, u = t.identityKey, d = t.revision, f = t.id;
77
+ if (!x(n) || !x(r) || !x(a) || !x(l) || !x(f) || !x(s) || c !== 0 && c !== 1 || typeof u != "string" || !/^[0-9a-f]{64}$/.test(u) || typeof d != "number" || !Number.isInteger(d) || d < 1 || d > b) throw o("The native invoice observation identity is invalid.");
78
+ let p = i(t.providerSnapshot);
79
+ if (p.providerCustomerId !== l || p.providerInvoiceId !== a || p.livemode !== (c === 1)) throw o("The stored observation has a different customer or invoice.");
80
+ let m = t.paymentHeadId == null && t.paymentEpoch == null ? null : e({
81
+ headId: t.paymentHeadId,
82
+ epoch: t.paymentEpoch
83
+ });
70
84
  return {
71
- id: d,
85
+ id: f,
72
86
  tenantId: n,
73
- provider: i,
74
- providerAccountId: o,
75
- livemode: s === 1,
87
+ provider: r,
88
+ providerAccountId: s,
89
+ livemode: c === 1,
76
90
  providerInvoiceId: a,
77
- providerCustomerId: c,
78
- identityKey: l,
79
- revision: u,
80
- snapshot: f
91
+ providerCustomerId: l,
92
+ identityKey: u,
93
+ revision: d,
94
+ snapshot: p,
95
+ paymentEpoch: m
81
96
  };
82
- }, T = (e, t, i) => {
83
- let a = b(e), o = t === null ? null : Object.freeze({
97
+ }, k = (e, t, n) => {
98
+ let r = w(e), i = t === null ? null : Object.freeze({
84
99
  ...t,
85
- ...b(t)
100
+ ...w(t)
86
101
  });
87
- if (o !== null && (C(o, a), !_(o.id) || !/^[0-9a-f]{64}$/.test(o.identityKey) || !Number.isInteger(o.revision) || o.revision < 1 || o.revision >= g)) throw r("The expected native invoice revision is invalid or exhausted.");
88
- if (i.providerInvoiceId !== a.providerInvoiceId || i.providerCustomerId !== a.providerCustomerId || i.livemode !== a.livemode) throw r("The complete invoice must match the confirmed customer binding.");
102
+ if (i !== null && (D(i, r), !x(i.id) || !/^[0-9a-f]{64}$/.test(i.identityKey) || !Number.isInteger(i.revision) || i.revision < 1 || i.revision >= b)) throw o("The expected native invoice revision is invalid or exhausted.");
103
+ if (n.providerInvoiceId !== r.providerInvoiceId || n.providerCustomerId !== r.providerCustomerId || n.livemode !== r.livemode) throw o("The complete invoice must match the confirmed customer binding.");
89
104
  return {
90
- owner: a,
91
- previous: o,
92
- providerSnapshot: n(i)
105
+ owner: r,
106
+ previous: i,
107
+ providerSnapshot: structuredClone(a(n))
93
108
  };
94
- }, E = (e) => {
95
- let t = async (t) => {
96
- let n = await e.query(v(o("identityKey", t), 2));
97
- if (n.length > 1) throw r("The native invoice identity is not unique.");
98
- let i = n[0] ? w(n[0]) : null;
99
- if (i !== null && (i.identityKey !== t || await x(i) !== t)) throw r("The native invoice identity digest could not be confirmed.");
100
- return i;
109
+ }, A = (i) => {
110
+ let a = async (e, t = i, n = !1) => {
111
+ let r = S(u("identityKey", e), 2), a = await t.query(n ? {
112
+ ...r,
113
+ lock: "update"
114
+ } : r);
115
+ if (a.length > 1) throw o("The native invoice identity is not unique.");
116
+ let s = a[0] ? O(a[0]) : null;
117
+ if (s !== null && (s.identityKey !== e || await T(s) !== e)) throw o("The native invoice identity digest could not be confirmed.");
118
+ return s;
101
119
  };
102
120
  return {
103
- get: (e) => y(async () => {
104
- let n = b(e), r = await t(await x(n));
105
- return r !== null && C(r, n), r;
121
+ capturePaymentEpoch: (e) => C(() => r(i, e, !0, async (e, t) => t)),
122
+ currentPaymentEpoch: (e, n) => C(() => t(i, e, n?.forUpdate === !0)),
123
+ invalidatePayments: (e, t) => C(() => n(i, e, t)),
124
+ get: (e, t) => C(async () => {
125
+ let n = w(e), r = await a(await T(n), i, t?.forUpdate === !0);
126
+ return r !== null && D(r, n), r;
106
127
  }),
107
- complete: (n, i, s) => y(async () => {
108
- let { owner: c, previous: l, providerSnapshot: u } = T(n, i, s), d = await x(c);
109
- if (l === null) {
110
- let n = "binvobs_" + globalThis.crypto.randomUUID();
111
- await e.insertIgnore(p, {
112
- id: n,
113
- ...c,
114
- livemode: +!!c.livemode,
115
- identityKey: d,
116
- revision: 1,
117
- providerSnapshot: u,
118
- createdAt: /* @__PURE__ */ new Date()
119
- }, { conflictColumns: ["identityKey"] });
120
- let i = await t(d);
121
- if (i === null) throw r("The persisted invoice observation could not be confirmed.", !0);
122
- return C(i, c), i.id === n;
123
- }
124
- if (d !== l.identityKey) throw r("The expected invoice identity digest is invalid.");
125
- return await e.updateMany(p, {
126
- providerSnapshot: u,
127
- revision: l.revision + 1
128
- }, { where: a(o("id", l.id), o("identityKey", d), o("revision", l.revision), o("tenantId", c.tenantId), o("provider", c.provider), o("providerAccountId", c.providerAccountId), o("livemode", +!!c.livemode), o("providerCustomerId", c.providerCustomerId), o("providerInvoiceId", c.providerInvoiceId)) }) === 1;
128
+ complete: (t, n, s, c) => C(async () => {
129
+ let { owner: d, previous: f, providerSnapshot: p } = k(t, n, s), m = e(c), h = await T(d);
130
+ return r(i, d, !1, async (e, t) => {
131
+ if (t.headId !== m.headId || t.epoch !== m.epoch) return !1;
132
+ if (f === null) {
133
+ let t = "binvobs_" + globalThis.crypto.randomUUID();
134
+ await e.insertIgnore(_, {
135
+ id: t,
136
+ ...d,
137
+ livemode: +!!d.livemode,
138
+ identityKey: h,
139
+ revision: 1,
140
+ providerSnapshot: p,
141
+ paymentHeadId: m.headId,
142
+ paymentEpoch: m.epoch,
143
+ createdAt: /* @__PURE__ */ new Date()
144
+ }, { conflictColumns: ["identityKey"] });
145
+ let n = await a(h, e, !0);
146
+ if (n === null) throw o("The persisted invoice observation could not be confirmed.", !0);
147
+ return D(n, d), n.id === t && (j(n, m, p), !0);
148
+ }
149
+ if (h !== f.identityKey) throw o("The expected invoice identity digest is invalid.");
150
+ if (await e.updateMany("_voltro_billing_account_invoices", {
151
+ providerSnapshot: p,
152
+ revision: f.revision + 1,
153
+ paymentHeadId: m.headId,
154
+ paymentEpoch: m.epoch
155
+ }, { where: l(u("id", f.id), u("identityKey", h), u("revision", f.revision), u("tenantId", d.tenantId), u("provider", d.provider), u("providerAccountId", d.providerAccountId), u("livemode", +!!d.livemode), u("providerCustomerId", d.providerCustomerId), u("providerInvoiceId", d.providerInvoiceId)) }) !== 1) return !1;
156
+ let n = await a(h, e, !0);
157
+ if (!n || n.id !== f.id || n.revision !== f.revision + 1) throw o("The updated invoice revision could not be read back.", !0);
158
+ return D(n, d), j(n, m, p), !0;
159
+ });
129
160
  })
130
161
  };
162
+ }, j = (e, t, n) => {
163
+ let r = e.paymentEpoch;
164
+ if (r === null || r.headId !== t.headId || r.epoch !== t.epoch || JSON.stringify(a(e.snapshot)) !== JSON.stringify(n)) throw o("Invoice payment generation or exact observation could not be read back.", !0);
131
165
  };
132
- export { p as BILLING_INVOICE_OBSERVATIONS_TABLE, h as billingInvoiceObservationsTable, m as billingRetainedInvoiceObservationsTable, E as dataStoreInvoiceStore };
166
+ export { _ as BILLING_INVOICE_OBSERVATIONS_TABLE, y as billingInvoiceObservationsTable, v as billingRetainedInvoiceObservationsTable, A as dataStoreInvoiceStore };