@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
package/dist/types.js CHANGED
@@ -4,15 +4,32 @@ var n = class extends t.TaggedError()("BillingError", {
4
4
  source: t.String,
5
5
  message: t.String,
6
6
  transient: t.Boolean
7
- }) {}, r = class extends t.TaggedError()("SubscriptionLocked", {
7
+ }) {}, r = class extends t.TaggedError()("BillingRequestStale", {
8
+ requestId: t.String,
9
+ reason: t.Literals([
10
+ "superseded",
11
+ "withdrawn",
12
+ "rejected"
13
+ ]),
14
+ message: t.String
15
+ }) {}, i = class extends t.TaggedError()("BillingClosurePending", {
16
+ tenantId: t.String,
17
+ reason: t.Literals([
18
+ "cancellation-settling",
19
+ "final-invoice-draft",
20
+ "final-invoice-open"
21
+ ]),
22
+ providerInvoiceIds: t.Array(t.String),
23
+ message: t.String
24
+ }) {}, a = class extends t.TaggedError()("SubscriptionLocked", {
8
25
  tenantId: t.String,
9
26
  status: t.String,
10
27
  lockedSince: t.String,
11
28
  lockout: t.String
12
- }) {}, i = class extends t.TaggedError()("EntitlementExceeded", {
29
+ }) {}, o = class extends t.TaggedError()("EntitlementExceeded", {
13
30
  entitlement: t.String,
14
31
  limit: t.Number,
15
32
  used: t.Number,
16
33
  cost: t.Number
17
- }) {}, a = "free", o = class extends e.Service()("@voltro/plugin-billing/BillingService") {};
18
- export { n as BillingError, o as BillingService, a as DEFAULT_PLAN, i as EntitlementExceeded, r as SubscriptionLocked };
34
+ }) {}, s = "free", c = class extends e.Service()("@voltro/plugin-billing/BillingService") {};
35
+ export { i as BillingClosurePending, n as BillingError, r as BillingRequestStale, c as BillingService, s as DEFAULT_PLAN, o as EntitlementExceeded, a as SubscriptionLocked };
@@ -1,3 +1,34 @@
1
+ /** Adopt another tab's or device's outstanding request id in this tab. Sending
2
+ * the same intention again then resumes that write instead of starting one. */
3
+ export declare const adoptPendingBillingOperation: (scope: string, operation: PendingBillingOperation) => void;
4
+
5
+ /** The server's typed refusal of a spent request id (`BillingRequestStale`). */
6
+ export declare interface BillingRequestStaleError {
7
+ readonly _tag: 'BillingRequestStale';
8
+ readonly requestId: string;
9
+ readonly reason: 'superseded' | 'withdrawn' | 'rejected';
10
+ readonly message: string;
11
+ }
12
+
13
+ /** The intention a request id is saved for: action input values only. */
14
+ export declare type BillingWriteInput = Readonly<Record<string, string | number | boolean | null>>;
15
+
16
+ /** A confirmed billing intention's durable request identifier. */
17
+ export declare interface BillingWriteRequest {
18
+ readonly requestId: string;
19
+ /** The write answered: forget the id so a later intention gets a fresh one. */
20
+ readonly complete: () => void;
21
+ /** Forget the id once a status read shows a terminal phase
22
+ * (`completed`, `withdrawn` or `rejected`); other phases keep it for retry. */
23
+ readonly settle: (phase: string) => void;
24
+ /** Replace a spent id (`BillingRequestStale`) with a freshly minted one. */
25
+ readonly renew: () => BillingWriteRequest;
26
+ }
27
+
28
+ /** Keep a confirmed billing intention stable across transport loss and reload.
29
+ * This stores an opaque request identifier, never credentials or payment data. */
30
+ export declare const billingWriteRequest: (scope: string, action: string, input: BillingWriteInput) => BillingWriteRequest;
31
+
1
32
  /** The fields of `billing.subscription` the cancel flow reads. */
2
33
  export declare interface CancelableSubscription {
3
34
  readonly status: string;
@@ -7,6 +38,37 @@ export declare interface CancelableSubscription {
7
38
  readonly currentPeriodEnd: string | null;
8
39
  }
9
40
 
41
+ export declare const isBillingRequestStale: (error: unknown) => error is BillingRequestStaleError;
42
+
43
+ /** The tenant's outstanding write as `billing.pendingOperation` reports it. */
44
+ export declare interface PendingBillingOperation {
45
+ readonly requestId: string;
46
+ readonly kind: 'change' | 'cancel' | 'resume';
47
+ readonly plan: string | null;
48
+ readonly quantity: number | null;
49
+ readonly phase: 'prepared' | 'claimed' | 'dispatched' | 'acknowledged';
50
+ }
51
+
52
+ /** The action and input a pending operation was sent as, so its request id can
53
+ * be stored under the key the write hooks read. */
54
+ export declare const pendingBillingWriteTarget: (operation: PendingBillingOperation) => {
55
+ readonly action: "billing.cancel" | "billing.resume" | "billing.changePlan" | "billing.changeSeats";
56
+ readonly input: BillingWriteInput;
57
+ } | null;
58
+
59
+ /** The generated `billing.pendingOperation` query binding. */
60
+ export declare type PendingOperationRpc = (input: Record<string, never>) => Promise<{
61
+ readonly operation: PendingBillingOperation | null;
62
+ }>;
63
+
64
+ /**
65
+ * Send one journalled billing write under its durable id. A lost response is
66
+ * retried by sending again with the same saved id. When the server refuses the
67
+ * id as spent, the saved id is cleared; a `superseded` or `withdrawn` one is
68
+ * replaced by a fresh id and sent once more, a `rejected` one is not resent.
69
+ */
70
+ export declare const sendBillingWrite: <Result>(scope: string, action: string, input: BillingWriteInput, send: (requestId: string) => Promise<Result>) => Promise<Result>;
71
+
10
72
  /** The plan id + redirect URLs a checkout needs. */
11
73
  export declare interface StartCheckoutInput {
12
74
  readonly plan: string;
@@ -25,7 +87,34 @@ export declare type StartCheckoutRpc = (input: StartCheckoutInput) => Promise<{
25
87
  }>;
26
88
 
27
89
  /** The generated `billing.cancel` / `billing.resume` action bindings. */
28
- export declare type SubscriptionActionRpc = (input: Record<string, never>) => Promise<unknown>;
90
+ export declare type SubscriptionActionRpc = (input: {
91
+ readonly requestId: string;
92
+ }) => Promise<unknown>;
93
+
94
+ /**
95
+ * Find the tenant's outstanding subscription write — started in another tab,
96
+ * on another device, or before a reload — and adopt its request id here. The
97
+ * write hooks then RESUME it when the same intention is sent again, instead of
98
+ * being refused while it is open. `billing.sync` reconciles it instead.
99
+ *
100
+ * ```tsx
101
+ * const pending = usePendingBillingOperation({ scope: organizationId, read: rpc.billing.pendingOperation })
102
+ * pending.operation && <p>A {pending.operation.kind} is still being confirmed.</p>
103
+ * ```
104
+ */
105
+ export declare const usePendingBillingOperation: (input: {
106
+ readonly scope: string;
107
+ readonly read: PendingOperationRpc;
108
+ }) => UsePendingBillingOperationResult;
109
+
110
+ export declare interface UsePendingBillingOperationResult {
111
+ /** The tenant's outstanding write, or null when none is open. */
112
+ readonly operation: PendingBillingOperation | null;
113
+ readonly loading: boolean;
114
+ readonly error: Error | null;
115
+ /** Read it again (after a `billing.sync`, or when another tab finished). */
116
+ readonly refresh: () => Promise<void>;
117
+ }
29
118
 
30
119
  /**
31
120
  * React hook that drives provider-hosted checkout. Pass the generated
@@ -60,13 +149,14 @@ export declare interface UseStartCheckoutResult {
60
149
  * cancellation made in the provider's portal shows here too.
61
150
  *
62
151
  * ```tsx
63
- * const flow = useSubscriptionCancel({ subscription, cancel: rpc.billing.cancel, resume: rpc.billing.resume })
152
+ * const flow = useSubscriptionCancel({ scope: organizationId, subscription, cancel: rpc.billing.cancel, resume: rpc.billing.resume })
64
153
  * flow.stage === 'active' && <button onClick={flow.begin}>Cancel your subscription here</button>
65
154
  * flow.stage === 'confirming' && <><p>Ends on {flow.endsOn}</p><button onClick={flow.confirm}>Cancel now</button><button onClick={flow.keep}>Keep</button></>
66
155
  * flow.stage === 'scheduled' && <button onClick={flow.resume}>Take the cancellation back</button>
67
156
  * ```
68
157
  */
69
158
  export declare const useSubscriptionCancel: (input: {
159
+ readonly scope: string;
70
160
  readonly subscription: CancelableSubscription;
71
161
  readonly cancel: SubscriptionActionRpc;
72
162
  readonly resume: SubscriptionActionRpc;
@@ -91,7 +181,7 @@ export declare interface UseSubscriptionCancelResult {
91
181
  /** Take a scheduled cancellation back. */
92
182
  readonly resume: () => Promise<void>;
93
183
  readonly pending: boolean;
94
- /** The last failure, or null. The subscription is unchanged when set. */
184
+ /** Last failure. A missing receipt does not prove the subscription stayed unchanged. */
95
185
  readonly error: Error | null;
96
186
  }
97
187
 
package/dist/web/index.js CHANGED
@@ -1,46 +1,89 @@
1
- import { useCallback as e, useState as t } from "react";
1
+ import { adoptPendingBillingOperation as e, billingWriteRequest as t, isBillingRequestStale as n, pendingBillingWriteTarget as r, sendBillingWrite as i } from "./writeRequest.js";
2
+ import { useCallback as a, useEffect as o, useRef as s, useState as c } from "react";
2
3
  // src/web/index.ts
3
- var n = () => globalThis.window, r = (r) => {
4
- let [i, a] = t(!1), [o, s] = t(null);
4
+ var l = () => globalThis.window, u = (e) => {
5
+ let [t, n] = c(!1), [r, i] = c(null);
5
6
  return {
6
- startCheckout: e(async (e) => {
7
- a(!0), s(null);
7
+ startCheckout: a(async (t) => {
8
+ n(!0), i(null);
8
9
  try {
9
- let { url: t } = await r(e);
10
- n()?.location.assign(t);
10
+ let { url: n } = await e(t);
11
+ l()?.location.assign(n);
11
12
  } catch (e) {
12
- throw s(e instanceof Error ? e : Error(String(e))), e;
13
+ throw i(e instanceof Error ? e : Error(String(e))), e;
13
14
  } finally {
14
- a(!1);
15
+ n(!1);
15
16
  }
16
- }, [r]),
17
- pending: i,
18
- error: o
17
+ }, [e]),
18
+ pending: t,
19
+ error: r
19
20
  };
20
- }, i = (n) => {
21
- let [r, i] = t(!1), [a, o] = t(!1), [s, c] = t(null), { subscription: l, cancel: u, resume: d } = n, f = e(async (e) => {
22
- o(!0), c(null);
21
+ }, d = (e) => {
22
+ let [t, n] = c(!1), [r, l] = c(!1), [u, d] = c(null), { subscription: f, cancel: p, resume: m } = e, h = s({
23
+ scope: e.scope,
24
+ pending: !1
25
+ });
26
+ h.current.scope !== e.scope && (h.current = {
27
+ scope: e.scope,
28
+ pending: !1
29
+ }), o(() => {
30
+ n(!1), l(h.current.pending), d(null);
31
+ }, [e.scope]);
32
+ let g = a(async (e) => {
33
+ let t = h.current;
34
+ if (!t.pending) {
35
+ t.pending = !0, l(!0), d(null);
36
+ try {
37
+ await e(), h.current === t && n(!1);
38
+ } catch (e) {
39
+ h.current === t && d(e instanceof Error ? e : Error(String(e)));
40
+ } finally {
41
+ t.pending = !1, h.current === t && l(!1);
42
+ }
43
+ }
44
+ }, []), _ = a(() => g(() => i(e.scope, "billing.cancel", {}, (e) => p({ requestId: e }))), [
45
+ g,
46
+ p,
47
+ e.scope
48
+ ]), v = a(() => g(() => i(e.scope, "billing.resume", {}, (e) => m({ requestId: e }))), [
49
+ g,
50
+ m,
51
+ e.scope
52
+ ]), y = a(() => {
53
+ d(null), n(!0);
54
+ }, []), b = a(() => {
55
+ n(!1);
56
+ }, []);
57
+ return {
58
+ stage: f.status === "canceled" ? "ended" : f.cancelAt === null ? t ? "confirming" : "active" : "scheduled",
59
+ endsOn: f.cancelAt ?? f.currentPeriodEnd,
60
+ begin: y,
61
+ keep: b,
62
+ confirm: _,
63
+ resume: v,
64
+ pending: r,
65
+ error: u
66
+ };
67
+ }, f = (t) => {
68
+ let { scope: n, read: r } = t, [i, l] = c(null), [u, d] = c(!0), [f, p] = c(null), m = s(0), h = a(async () => {
69
+ let t = ++m.current;
70
+ d(!0), p(null);
23
71
  try {
24
- await e(), i(!1);
72
+ let { operation: i } = await r({});
73
+ i !== null && e(n, i), m.current === t && l(i);
25
74
  } catch (e) {
26
- c(e instanceof Error ? e : Error(String(e)));
75
+ m.current === t && p(e instanceof Error ? e : Error(String(e)));
27
76
  } finally {
28
- o(!1);
77
+ m.current === t && d(!1);
29
78
  }
30
- }, []), p = e(() => f(() => u({})), [f, u]), m = e(() => f(() => d({})), [f, d]), h = e(() => {
31
- c(null), i(!0);
32
- }, []), g = e(() => {
33
- i(!1);
34
- }, []);
35
- return {
36
- stage: l.status === "canceled" ? "ended" : l.cancelAt === null ? r ? "confirming" : "active" : "scheduled",
37
- endsOn: l.cancelAt ?? l.currentPeriodEnd,
38
- begin: h,
39
- keep: g,
40
- confirm: p,
41
- resume: m,
42
- pending: a,
43
- error: s
79
+ }, [r, n]);
80
+ return o(() => {
81
+ h();
82
+ }, [h]), {
83
+ operation: i,
84
+ loading: u,
85
+ error: f,
86
+ refresh: h
44
87
  };
45
88
  };
46
- export { r as useStartCheckout, i as useSubscriptionCancel };
89
+ export { e as adoptPendingBillingOperation, t as billingWriteRequest, n as isBillingRequestStale, r as pendingBillingWriteTarget, i as sendBillingWrite, f as usePendingBillingOperation, u as useStartCheckout, d as useSubscriptionCancel };
@@ -0,0 +1,65 @@
1
+ // src/web/writeRequest.ts
2
+ var e = /^[A-Za-z0-9_-]{8,128}$/, t = [
3
+ "completed",
4
+ "withdrawn",
5
+ "rejected"
6
+ ], n = () => {
7
+ let e = globalThis.window?.sessionStorage;
8
+ if (e === void 0) throw Error("Durable billing request storage is unavailable.");
9
+ return e;
10
+ }, r = (e, t, n) => {
11
+ if (!e || !t) throw Error("Durable billing request storage is unavailable.");
12
+ return "voltro.billing.write.v1." + encodeURIComponent(JSON.stringify([
13
+ e,
14
+ t,
15
+ Object.keys(n).sort().map((e) => [e, n[e]])
16
+ ]));
17
+ }, i = (e, t, n) => {
18
+ if (e.setItem(t, n), e.getItem(t) !== n) throw Error("Durable billing request storage could not be confirmed.");
19
+ }, a = (o, s, c) => {
20
+ let l = n(), u = r(o, s, c), d = l.getItem(u);
21
+ if (d === null && (d = globalThis.crypto.randomUUID(), i(l, u, d)), !e.test(d)) throw Error("The saved billing request requires reconciliation.");
22
+ let f = d, p = () => {
23
+ l.getItem(u) === f && l.removeItem(u);
24
+ };
25
+ return {
26
+ requestId: f,
27
+ complete: p,
28
+ settle: (e) => {
29
+ t.includes(e) && p();
30
+ },
31
+ renew: () => (p(), a(o, s, c))
32
+ };
33
+ }, o = (e) => {
34
+ let t = e;
35
+ return typeof t == "object" && !!t && t._tag === "BillingRequestStale" && (t.reason === "superseded" || t.reason === "withdrawn" || t.reason === "rejected");
36
+ }, s = async (e, t, n, r) => {
37
+ let i = async (e, t) => {
38
+ try {
39
+ let t = await r(e.requestId);
40
+ return e.complete(), t;
41
+ } catch (n) {
42
+ if (!o(n) || n.requestId !== e.requestId) throw n;
43
+ if (t || n.reason === "rejected") throw e.complete(), n;
44
+ return i(e.renew(), !0);
45
+ }
46
+ };
47
+ return i(a(e, t, n), !1);
48
+ }, c = (e) => e.kind === "cancel" ? {
49
+ action: "billing.cancel",
50
+ input: {}
51
+ } : e.kind === "resume" ? {
52
+ action: "billing.resume",
53
+ input: {}
54
+ } : e.plan !== null && e.quantity === null ? {
55
+ action: "billing.changePlan",
56
+ input: { plan: e.plan }
57
+ } : e.quantity !== null && e.plan === null ? {
58
+ action: "billing.changeSeats",
59
+ input: { quantity: e.quantity }
60
+ } : null, l = (t, a) => {
61
+ let o = c(a);
62
+ if (o === null || !e.test(a.requestId)) throw Error("The pending billing request requires reconciliation.");
63
+ i(n(), r(t, o.action, o.input), a.requestId);
64
+ };
65
+ export { l as adoptPendingBillingOperation, a as billingWriteRequest, o as isBillingRequestStale, c as pendingBillingWriteTarget, s as sendBillingWrite };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/plugin-billing",
3
- "version": "0.89.2",
3
+ "version": "0.91.0",
4
4
  "description": "Billing on the official Stripe SDK — subscriptions, plans, entitlements and usage metering. Proration, failed-payment retries, tax, promotion codes, trials and the checkout seat stepper are Stripe's own; the plugin adds the entitlement engine, the enforce interceptor, typed BillingError/EntitlementExceeded, the /billing/webhook mount with Stripe's signature verification, the BillingService Tag, requireEntitlement(), and a browser-safe useStartCheckout() hook. Money is integer minor units end-to-end.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -53,18 +53,18 @@
53
53
  "node": ">=24.0.0"
54
54
  },
55
55
  "dependencies": {
56
- "@voltro/database": "0.89.2",
57
- "@voltro/env": "0.89.2",
58
- "@voltro/logger": "0.89.2",
59
- "@voltro/plugin-webhooks": "0.89.2",
60
- "@voltro/protocol": "0.89.2",
61
- "@voltro/runtime": "0.89.2"
56
+ "@voltro/database": "0.91.0",
57
+ "@voltro/env": "0.91.0",
58
+ "@voltro/logger": "0.91.0",
59
+ "@voltro/plugin-webhooks": "0.91.0",
60
+ "@voltro/protocol": "0.91.0",
61
+ "@voltro/runtime": "0.91.0"
62
62
  },
63
63
  "peerDependencies": {
64
- "effect": "4.1.2",
64
+ "effect": "4.1.4",
65
65
  "react": "^19.0.0",
66
66
  "stripe": "^22.6.1 || ^23.0.1",
67
- "@voltro/plugin-economy": "0.89.2"
67
+ "@voltro/plugin-economy": "0.91.0"
68
68
  },
69
69
  "peerDependenciesMeta": {
70
70
  "react": {