@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/index.js CHANGED
@@ -1,35 +1,40 @@
1
- import { BillingError as e, BillingService as t, DEFAULT_PLAN as n, EntitlementExceeded as r, SubscriptionLocked as i } from "./types.js";
2
- import { makeBillingEventDelivery as a } from "./eventDelivery.js";
3
- import { BILLING_CUSTODY_INVENTORY_TABLES as o, inspectBillingCustody as s } from "./custodyInventory.js";
4
- import { BILLING_CUSTOMER_ACCOUNTS_TABLE as c, BILLING_CUSTOMER_CUSTODY_TABLE as l, billingCustomerAccountsTable as u, billingCustomerCustodyTable as ee } from "./customerStore.js";
5
- import { buildEnforceInterceptor as te, evaluateEntitlement as d, requireEntitled as f, requireEntitlement as ne } from "./entitlement.js";
6
- import { BILLING_INVOICE_HISTORY_PAGES_TABLE as p, BILLING_INVOICE_HISTORY_REFERENCES_TABLE as m, BILLING_INVOICE_HISTORY_WALKS_TABLE as h, billingInvoiceHistoryPagesTable as g, billingInvoiceHistoryReferencesTable as _, billingInvoiceHistoryWalksTable as v, dataStoreInvoiceHistoryJournal as y } from "./invoiceHistoryJournal.js";
7
- import { BILLING_INVOICE_OBSERVATIONS_TABLE as re, billingInvoiceObservationsTable as ie, billingRetainedInvoiceObservationsTable as ae } from "./invoiceStore.js";
8
- import { BILLING_INVOICE_HISTORY_WORK_TABLE as oe, billingInvoiceHistoryWorkTable as se, dataStoreInvoiceHistoryWorkStore as b } from "./invoiceHistoryWork.js";
9
- import { BILLING_INVOICE_HISTORY_DISPATCH_TABLE as ce, BILLING_INVOICE_HISTORY_SCAN_ACCOUNTS_TABLE as x, billingInvoiceHistoryDispatchTable as S, billingInvoiceHistoryScanAccountsTable as C, dataStoreInvoiceHistoryProgressStore as w } from "./invoiceHistoryProgress.js";
10
- import { BILLING_USAGE_EVENTS_TABLE as T, billingUsageEventsTable as E } from "./usageEvents.js";
11
- import { BILLING_CHECKOUT_OPERATIONS_TABLE as D, billingCheckoutOperationsTable as O, dataStoreCheckoutOperationStore as k, memoryCheckoutOperationStore as A } from "./checkoutStore.js";
12
- import { BILLING_CLOSE_OPERATIONS_TABLE as j, billingCloseOperationsTable as M, dataStoreBillingCloseStore as N, memoryBillingCloseStore as P } from "./closeStore.js";
13
- import { BILLING_DUNNING_NOTICES_TABLE as le, DEFAULT_DUNNING_STEPS as F, DEFAULT_GRACE_HOURS as I, DEFAULT_LOCKOUT as L, DUNNING_LOCK_STEP_ID as R, billingDunningNoticesTable as z, dataStoreDunningNoticeStore as B, defaultDunningEmail as ue, dueSteps as de, dunningMailNotifier as fe, episodeKeyOf as pe, evaluateBillingEntitlement as me, graceEndOf as he, memoryDunningNoticeStore as ge, resolveDunningConfig as V } from "./dunning.js";
14
- import { BILLING_CUSTOMERS_TABLE as _e, BILLING_INVOICES_TABLE as ve, BILLING_SUBSCRIPTIONS_TABLE as H, BILLING_USAGE_TABLE as U, billingCustomersTable as ye, billingInvoicesTable as be, billingSubscriptionsTable as xe, billingTables as W, billingUsageTable as Se } from "./table.js";
15
- import { dataStoreStores as G, isStaleStatusEvent as Ce, memoryStores as we, selectCurrentSubscription as Te } from "./stores.js";
16
- import { billingServiceLayer as K, buildBillingService as Ee, periodKey as De } from "./service.js";
17
- import { buildMeteringChangeTap as Oe, buildMeteringInterceptor as ke, hasCdcMeters as Ae, runAutopilotFlush as je, validateMeteringConfig as Me } from "./metering.js";
18
- import { buildPlanRegistry as Ne, emptyPlanRegistry as Pe } from "./plans.js";
19
- import { BILLING_FLUSH_CLAIMS_TABLE as Fe, billingFlushClaimsTable as Ie, claimFlushWindow as Le, flushWindowKey as Re } from "./flushClaim.js";
20
- import { STRIPE_API_VERSION as ze, STRIPE_DASHBOARD_REMINDERS as Be, diffMeter as Ve, diffPortal as He, diffPrice as Ue, diffProduct as We, diffTaxSettings as Ge, diffWebhook as Ke, portalParams as qe, sellingReadiness as Je } from "./catalog.js";
21
- import { StripeRestError as Ye, formEncode as Xe, redactStripeKeys as Ze, stripeRest as Qe } from "./stripeRest.js";
22
- import { STRIPE_WEBHOOK_EVENTS as $e, normalizeStripeEvent as et, stripeProvider as tt } from "./stripeProvider.js";
23
- import { assertBillingProductionReady as nt, billingEgressOf as rt, isProductionBoot as it, mockProvider as at, resolveProvider as ot } from "./providers.js";
24
- import { BILLING_WEBHOOK_ID as st, BILLING_WEBHOOK_PATH as q, billingWebhookDescriptor as ct, mountBillingWebhook as lt } from "./webhook.js";
25
- import { billingRpcClientImports as ut, cancelSubscriptionDescriptor as dt, changePlanDescriptor as ft, changeSeatsDescriptor as pt, entitlementStatusDescriptor as mt, invoicesDescriptor as ht, portalUrlDescriptor as gt, previewChangeDescriptor as _t, reportUsageDescriptor as vt, resumeSubscriptionDescriptor as yt, startCheckoutDescriptor as J, subscriptionDescriptor as bt, syncDescriptor as xt } from "./rpc.js";
26
- import { envOutRefusal as St, mergeEnvFile as Ct, openFindings as wt, parseProvisionArgs as Tt, provisionStripeCatalog as Et, resolveProvisionKey as Dt, runStripeProvision as Ot } from "./provision.js";
27
- import { Effect as Y } from "effect";
28
- import { pluginEnv as kt } from "@voltro/env";
29
- import { composeRpcInterceptors as At, definePlugin as jt, pluginInstanceName as Mt, recheckGuardsEffect as Nt } from "@voltro/protocol";
30
- import { and as Pt, eq as Ft, registerRetention as X, retentionTtlMsFromEnv as Z } from "@voltro/database";
31
- import { replicaId as It } from "@voltro/protocol/identity";
32
- import { dataStoreIdempotencyStore as Lt } from "@voltro/runtime";
1
+ import { paidInvoiceCoverageInTransaction as e } from "./paidInvoiceCoverage.js";
2
+ import { captureSubscriptionObservation as t } from "./subscriptionObservation.js";
3
+ import { billingInvoicePaymentCorrectionsTable as n, billingInvoicePaymentHeadsTable as r } from "./invoicePaymentEpoch.js";
4
+ import { InvoicePaymentObservationSchema as i, assertInvoicePaymentObservation as a } from "./invoicePaymentObservation.js";
5
+ import { makeBillingEventDelivery as o } from "./eventDelivery.js";
6
+ import { BILLING_CUSTOMER_ACCOUNTS_TABLE as s, BILLING_CUSTOMER_CUSTODY_TABLE as c, billingCustomerAccountsTable as ee, billingCustomerCustodyTable as l } from "./customerStore.js";
7
+ import { buildEnforceInterceptor as te, evaluateEntitlement as u, requireEntitled as ne, requireEntitlement as d } from "./entitlement.js";
8
+ import { buildMeteringChangeTap as re, buildMeteringInterceptor as ie, hasCdcMeters as ae, runAutopilotFlush as oe, validateMeteringConfig as se } from "./metering.js";
9
+ import { BILLING_INVOICE_OBSERVATIONS_TABLE as ce, billingInvoiceObservationsTable as f, billingRetainedInvoiceObservationsTable as le } from "./invoiceStore.js";
10
+ import { buildPlanRegistry as ue, emptyPlanRegistry as de } from "./plans.js";
11
+ import { billingServiceLayer as fe, buildBillingService as pe, periodKey as me } from "./service.js";
12
+ import { dataStoreStores as he, isStaleStatusEvent as ge, memoryStores as p, selectCurrentSubscription as m } from "./stores.js";
13
+ import { BILLING_CUSTOMERS_TABLE as _e, BILLING_INVOICES_TABLE as ve, BILLING_SUBSCRIPTIONS_TABLE as ye, BILLING_USAGE_TABLE as be, billingCustomersTable as xe, billingInvoicesTable as Se, billingSubscriptionsTable as h, billingTables as Ce, billingUsageTable as we } from "./table.js";
14
+ import { BILLING_DUNNING_NOTICES_TABLE as Te, DEFAULT_DUNNING_STEPS as g, DEFAULT_GRACE_HOURS as _, DEFAULT_LOCKOUT as v, DUNNING_LOCK_STEP_ID as y, billingDunningNoticesTable as Ee, dataStoreDunningNoticeStore as b, defaultDunningEmail as x, dueSteps as S, dunningMailNotifier as De, episodeKeyOf as Oe, evaluateBillingEntitlement as C, graceEndOf as w, memoryDunningNoticeStore as T, resolveDunningConfig as ke } from "./dunning.js";
15
+ import { BILLING_FLUSH_CLAIMS_TABLE as Ae, billingFlushClaimsTable as je, claimFlushWindow as Me, flushWindowKey as Ne } from "./flushClaim.js";
16
+ import { assertBillingProductionReady as Pe, billingEgressOf as Fe, isProductionBoot as E, mockProvider as Ie, resolveProvider as Le } from "./providers.js";
17
+ import { BILLING_WEBHOOK_ID as D, BILLING_WEBHOOK_PATH as O, billingWebhookDescriptor as k, mountBillingWebhook as Re } from "./webhook.js";
18
+ import { billingRpcClientImports as ze, cancelSubscriptionDescriptor as Be, changePlanDescriptor as Ve, changeSeatsDescriptor as He, entitlementStatusDescriptor as Ue, invoicesDescriptor as We, operationStatusDescriptor as Ge, pendingOperationDescriptor as Ke, portalUrlDescriptor as qe, previewChangeDescriptor as Je, reportUsageDescriptor as Ye, resumeSubscriptionDescriptor as Xe, startCheckoutDescriptor as A, subscriptionDescriptor as Ze, syncDescriptor as Qe } from "./rpc.js";
19
+ import { BILLING_SUBSCRIPTION_WRITES_TABLE as $e, BILLING_SUBSCRIPTION_WRITE_HEADS_TABLE as et, billingSubscriptionWriteHeadsTable as j, billingSubscriptionWritesTable as M, dataStoreSubscriptionWriteStore as tt, isTerminalSubscriptionWrite as N } from "./subscriptionWriteStore.js";
20
+ import { BillingClosurePending as P, BillingError as F, BillingRequestStale as nt, BillingService as I, DEFAULT_PLAN as L, EntitlementExceeded as rt, SubscriptionLocked as it } from "./types.js";
21
+ import { STRIPE_DASHBOARD_REMINDERS as R, diffMeter as at, diffPortal as z, diffPrice as ot, diffProduct as B, diffRetiredMeter as V, diffRetiredPrice as H, diffRetiredProduct as U, diffTaxSettings as W, diffWebhook as G, portalParams as K, sellingReadiness as q } from "./catalog.js";
22
+ import { envOutRefusal as J, mergeEnvFile as st, openFindings as Y, parseProvisionArgs as ct, provisionStripeCatalog as lt, resolveProvisionKey as ut, runStripeProvision as dt } from "./provision.js";
23
+ import { STRIPE_API_VERSION as ft, StripeRestError as pt, formEncode as mt, redactStripeKeys as ht, stripeRest as gt } from "./stripeRest.js";
24
+ import { BILLING_CHECKOUT_OPERATIONS_TABLE as _t, billingCheckoutOperationsTable as vt, dataStoreCheckoutOperationStore as yt, memoryCheckoutOperationStore as bt } from "./checkoutStore.js";
25
+ import { BILLING_CLOSE_OPERATIONS_TABLE as xt, billingCloseOperationsTable as St, dataStoreBillingCloseStore as Ct, memoryBillingCloseStore as wt } from "./closeStore.js";
26
+ import { STRIPE_WEBHOOK_EVENTS as Tt, normalizeStripeEvent as Et, stripeProvider as Dt } from "./stripeProvider.js";
27
+ import { BILLING_USAGE_EVENTS_TABLE as Ot, billingUsageEventsTable as kt } from "./usageEvents.js";
28
+ import { BILLING_ACCOUNT_CUSTODY_INVENTORY_TABLES as At, BILLING_CUSTODY_INVENTORY_TABLES as jt, inspectBillingAccountCustody as Mt, inspectBillingCustody as Nt } from "./custodyInventory.js";
29
+ import { BILLING_INVOICE_HISTORY_PAGES_TABLE as Pt, BILLING_INVOICE_HISTORY_REFERENCES_TABLE as Ft, BILLING_INVOICE_HISTORY_WALKS_TABLE as It, billingInvoiceHistoryPagesTable as Lt, billingInvoiceHistoryReferencesTable as Rt, billingInvoiceHistoryWalksTable as zt, dataStoreInvoiceHistoryJournal as Bt } from "./invoiceHistoryJournal.js";
30
+ import { BILLING_INVOICE_HISTORY_WORK_TABLE as Vt, billingInvoiceHistoryWorkTable as Ht, dataStoreInvoiceHistoryWorkStore as Ut } from "./invoiceHistoryWork.js";
31
+ import { BILLING_INVOICE_HISTORY_DISPATCH_TABLE as Wt, BILLING_INVOICE_HISTORY_SCAN_ACCOUNTS_TABLE as Gt, billingInvoiceHistoryDispatchTable as Kt, billingInvoiceHistoryScanAccountsTable as qt, dataStoreInvoiceHistoryProgressStore as Jt } from "./invoiceHistoryProgress.js";
32
+ import { Effect as X } from "effect";
33
+ import { and as Yt, eq as Xt, registerRetention as Zt, retentionTtlMsFromEnv as Qt } from "@voltro/database";
34
+ import { dataStoreIdempotencyStore as $t } from "@voltro/runtime";
35
+ import { composeRpcInterceptors as en, definePlugin as tn, pluginInstanceName as Z, recheckGuardsEffect as nn } from "@voltro/protocol";
36
+ import { pluginEnv as rn } from "@voltro/env";
37
+ import { replicaId as an } from "@voltro/protocol/identity";
33
38
  // src/index.ts
34
39
  var Q = (e) => e === null ? null : {
35
40
  plan: e.plan,
@@ -37,7 +42,7 @@ var Q = (e) => e === null ? null : {
37
42
  quantity: e.quantity,
38
43
  currentPeriodEnd: e.currentPeriodEnd ? e.currentPeriodEnd.toISOString() : null,
39
44
  cancelAt: e.cancelAt ? e.cancelAt.toISOString() : null
40
- }, Rt = kt([{
45
+ }, on = rn([{
41
46
  name: "STRIPE_SECRET_KEY",
42
47
  required: !1,
43
48
  secret: !0,
@@ -47,82 +52,82 @@ var Q = (e) => e === null ? null : {
47
52
  required: !1,
48
53
  secret: !0,
49
54
  description: "Stripe webhook signing secret (whsec_…) for verifying webhook payloads."
50
- }]), $ = "@voltro/plugin-billing", zt = (t = {}) => {
51
- let n = process.env, o = Ne(t.plans ?? {}), s = ot({
52
- ...t.provider === void 0 ? {} : { provider: t.provider },
53
- ...t.apiKey === void 0 ? {} : { apiKey: t.apiKey },
54
- planForPriceId: o.planForPriceId,
55
- env: n
56
- }), u = t.webhookSecret ?? Rt.read("STRIPE_WEBHOOK_SECRET") ?? null;
57
- nt({
58
- env: n,
59
- providerOption: t.provider,
60
- resolvedName: s.name,
61
- webhookSecret: u,
62
- redirectOrigins: t.redirectOrigins
63
- });
64
- let ee = V(t.dunning, n);
65
- X({
55
+ }]), $ = "@voltro/plugin-billing", sn = (e = {}) => {
56
+ let t = process.env, n = ue(e.plans ?? {}), r = Le({
57
+ ...e.provider === void 0 ? {} : { provider: e.provider },
58
+ ...e.apiKey === void 0 ? {} : { apiKey: e.apiKey },
59
+ planForPriceId: n.planForPriceId,
60
+ seatPricingForPriceId: n.seatPricingForPriceId,
61
+ env: t
62
+ }), i = e.webhookSecret ?? on.read("STRIPE_WEBHOOK_SECRET") ?? null, a = {
63
+ env: t,
64
+ providerOption: e.provider,
65
+ resolvedName: r.name,
66
+ webhookSecret: i,
67
+ redirectOrigins: e.redirectOrigins
68
+ }, ee = ke(e.dunning, t);
69
+ Zt({
66
70
  source: "plugin",
67
- table: U,
71
+ table: be,
68
72
  timeColumn: "updatedAt",
69
- where: Pt(Ft("used", 0), Ft("reportedToProvider", 0)),
70
- ttlMs: Z(process.env.VOLTRO_BILLING_USAGE_TTL_HOURS, 9600),
73
+ where: Yt(Xt("used", 0), Xt("reportedToProvider", 0)),
74
+ ttlMs: Qt(process.env.VOLTRO_BILLING_USAGE_TTL_HOURS, 9600),
71
75
  label: "unused billing usage counters"
72
- }), X({
76
+ }), Zt({
73
77
  source: "plugin",
74
- table: Fe,
78
+ table: Ae,
75
79
  timeColumn: "claimedAt",
76
- ttlMs: Z(process.env.VOLTRO_BILLING_FLUSH_CLAIM_TTL_HOURS, 1),
80
+ ttlMs: Qt(process.env.VOLTRO_BILLING_FLUSH_CLAIM_TTL_HOURS, 1),
77
81
  label: "billing flush claims"
78
- }), X({
82
+ }), Zt({
79
83
  source: "plugin",
80
- table: le,
84
+ table: Te,
81
85
  timeColumn: "sentAt",
82
- ttlMs: Z(process.env.VOLTRO_BILLING_DUNNING_TTL_HOURS, 9600),
86
+ ttlMs: Qt(process.env.VOLTRO_BILLING_DUNNING_TTL_HOURS, 9600),
83
87
  label: "billing dunning notices"
84
88
  });
85
- let { service: d, holder: f } = Ee({
86
- provider: s,
87
- plans: o,
88
- ...t.attempts === void 0 ? {} : { attempts: t.attempts },
89
- ...t.checkout === void 0 ? {} : { checkout: t.checkout },
90
- ...t.admit === void 0 ? {} : { admit: t.admit },
91
- ...t.redirectOrigins === void 0 ? {} : { redirectOrigins: t.redirectOrigins },
92
- ...t.isTenantClosed === void 0 ? {} : { isTenantClosed: t.isTenantClosed },
93
- ...t.onEvent === void 0 ? {} : { onEvent: t.onEvent },
94
- ...t.resolveEntitlementLimit === void 0 ? {} : { resolveEntitlementLimit: t.resolveEntitlementLimit },
89
+ let { service: l, holder: u } = pe({
90
+ provider: r,
91
+ plans: n,
92
+ ...e.attempts === void 0 ? {} : { attempts: e.attempts },
93
+ ...e.checkout === void 0 ? {} : { checkout: e.checkout },
94
+ ...e.admit === void 0 ? {} : { admit: e.admit },
95
+ ...e.redirectOrigins === void 0 ? {} : { redirectOrigins: e.redirectOrigins },
96
+ ...e.isTenantClosed === void 0 ? {} : { isTenantClosed: e.isTenantClosed },
97
+ ...e.onEvent === void 0 ? {} : { onEvent: e.onEvent },
98
+ ...e.resolveEntitlementLimit === void 0 ? {} : { resolveEntitlementLimit: e.resolveEntitlementLimit },
99
+ ...e.invoiceHistoryHeadRescanMs === void 0 ? {} : { invoiceHistoryHeadRescanMs: e.invoiceHistoryHeadRescanMs },
95
100
  dunning: ee
96
- }), ne = K(d), p, m = {
97
- scope: Mt({
101
+ }), ne = fe(l), d, f = {
102
+ scope: Z({
98
103
  base: $,
99
- alias: t.alias,
100
- instance: t.name
104
+ alias: e.alias,
105
+ instance: e.name
101
106
  }),
102
107
  store: () => {
103
- if (p === void 0) throw Error("Billing delivery requires the bound native store.");
104
- return p;
108
+ if (d === void 0) throw Error("Billing delivery requires the bound native store.");
109
+ return d;
105
110
  }
106
- }, h = a({
107
- provider: s,
108
- service: d,
109
- receipts: m,
110
- ...t.onEvent === void 0 ? {} : { onEvent: t.onEvent }
111
- }), g = lt({
112
- provider: s,
113
- service: d,
114
- receipts: m,
115
- webhookSecret: u,
116
- ...t.onEvent === void 0 ? {} : { onEvent: t.onEvent },
111
+ }, le = o({
112
+ provider: r,
113
+ service: l,
114
+ receipts: f,
115
+ ...e.onEvent === void 0 ? {} : { onEvent: e.onEvent }
116
+ }), de = Re({
117
+ provider: r,
118
+ service: l,
119
+ receipts: f,
120
+ webhookSecret: i,
121
+ ...e.onEvent === void 0 ? {} : { onEvent: e.onEvent },
117
122
  onLateDelivery: () => {
118
- R();
123
+ Y();
119
124
  }
120
- }), _ = {
125
+ }), me = {
121
126
  method: "POST",
122
- path: q,
127
+ path: O,
123
128
  originGuard: "exempt",
124
129
  handle: async (e) => {
125
- let t = await g({
130
+ let t = await de({
126
131
  method: e.method,
127
132
  path: e.path,
128
133
  headers: e.headers,
@@ -135,59 +140,63 @@ var Q = (e) => e === null ? null : {
135
140
  ...t.headers === void 0 ? {} : { headers: { ...t.headers } }
136
141
  };
137
142
  }
138
- }, v = (t) => ({
139
- ...t,
140
- execute: (n, r) => {
141
- let i = r.request.subject;
142
- return i.type === "anonymous" || typeof i.tenantId != "string" || i.tenantId === "" ? Y.fail(new e({
143
+ }, ge = (e) => ({
144
+ ...e,
145
+ execute: (t, n) => {
146
+ let r = n.request.subject;
147
+ return r.type === "anonymous" || typeof r.tenantId != "string" || r.tenantId === "" ? X.fail(new F({
143
148
  source: "billing",
144
149
  message: "billing routes answer only a signed-in caller that belongs to a tenant",
145
150
  transient: !1
146
- })) : t.execute(n, r);
151
+ })) : e.execute(t, n);
147
152
  }
148
- }), y = (e, t, n, r) => e.pipe(Y.flatMap((e) => Nt(r.request.subject, t.guards, n).pipe(Y.flatMap((t) => t === null ? Y.succeed(e) : Y.fail(t))))), ie = [
153
+ }), p = (e, t, n, r) => e.pipe(X.flatMap((e) => nn(r.request.subject, t.guards, n).pipe(X.flatMap((t) => t === null ? X.succeed(e) : X.fail(t))))), m = (e, t, n) => () => nn(n.request.subject, e.guards, t).pipe(X.flatMap((e) => e === null ? X.void : X.fail(new F({
154
+ source: "billing",
155
+ message: "Current billing authority is required.",
156
+ transient: !1
157
+ })))), _e = [
149
158
  {
150
- ...J,
151
- execute: (t, n) => {
152
- let r = t;
153
- return y(d.startCheckout({
154
- tenantId: n.request.subject.tenantId ?? "",
155
- plan: r.plan,
156
- successUrl: r.successUrl,
157
- cancelUrl: r.cancelUrl,
158
- ...r.quantity === void 0 ? {} : { quantity: r.quantity },
159
- authorize: () => Nt(n.request.subject, J.guards, t).pipe(Y.flatMap((t) => t === null ? Y.void : Y.fail(new e({
159
+ ...A,
160
+ execute: (e, t) => {
161
+ let n = e;
162
+ return p(l.startCheckout({
163
+ tenantId: t.request.subject.tenantId ?? "",
164
+ plan: n.plan,
165
+ successUrl: n.successUrl,
166
+ cancelUrl: n.cancelUrl,
167
+ ...n.quantity === void 0 ? {} : { quantity: n.quantity },
168
+ authorize: () => nn(t.request.subject, A.guards, e).pipe(X.flatMap((e) => e === null ? X.void : X.fail(new F({
160
169
  source: "billing",
161
170
  message: "Current checkout authority could not be confirmed.",
162
171
  transient: !1
163
172
  }))))
164
- }), J, t, n);
173
+ }), A, e, t);
165
174
  }
166
175
  },
167
176
  {
168
- ...gt,
177
+ ...qe,
169
178
  execute: (e, t) => {
170
179
  let n = e;
171
- return y(d.portalUrl(t.request.subject.tenantId ?? "", n.returnUrl), gt, e, t);
180
+ return p(l.portalUrl(t.request.subject.tenantId ?? "", n.returnUrl), qe, e, t);
172
181
  }
173
182
  },
174
183
  {
175
- ...bt,
184
+ ...Ze,
176
185
  source: [
177
- H,
178
- c,
179
- l
186
+ ye,
187
+ s,
188
+ c
180
189
  ],
181
- execute: (e, t) => d.subscription(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({ subscription: Q(e) })))
190
+ execute: (e, t) => l.subscription(t.request.subject.tenantId ?? "").pipe(X.map((e) => ({ subscription: Q(e) })))
182
191
  },
183
192
  {
184
- ...mt,
193
+ ...Ue,
185
194
  source: [
186
- H,
187
- c,
188
- l
195
+ ye,
196
+ s,
197
+ c
189
198
  ],
190
- execute: (e, t) => d.entitlementStatus(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({
199
+ execute: (e, t) => l.entitlementStatus(t.request.subject.tenantId ?? "").pipe(X.map((e) => ({
191
200
  plan: e.plan,
192
201
  billedPlan: e.billedPlan,
193
202
  status: e.status,
@@ -199,13 +208,13 @@ var Q = (e) => e === null ? null : {
199
208
  })))
200
209
  },
201
210
  {
202
- ..._t,
211
+ ...Je,
203
212
  execute: (e, t) => {
204
213
  let n = e;
205
- return d.previewChange(t.request.subject.tenantId ?? "", {
214
+ return l.previewChange(t.request.subject.tenantId ?? "", {
206
215
  ...n.plan === void 0 ? {} : { plan: n.plan },
207
216
  ...n.quantity === void 0 ? {} : { quantity: n.quantity }
208
- }).pipe(Y.map((e) => ({
217
+ }).pipe(X.map((e) => ({
209
218
  plan: e.plan,
210
219
  quantity: e.quantity,
211
220
  prorationMinor: e.prorationMinor,
@@ -214,77 +223,86 @@ var Q = (e) => e === null ? null : {
214
223
  }
215
224
  },
216
225
  {
217
- ...ht,
226
+ ...We,
218
227
  source: [
219
- re,
220
- l,
221
- c
228
+ ce,
229
+ c,
230
+ s
222
231
  ],
223
- execute: (e, t) => d.invoices(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({ invoices: e.map((e) => ({
232
+ execute: (e, t) => l.invoices(t.request.subject.tenantId ?? "").pipe(X.map((e) => ({ invoices: e.map((e) => ({
224
233
  ...e,
225
234
  createdAt: e.createdAt?.toISOString() ?? null
226
235
  })) })))
227
236
  },
228
237
  {
229
- ...vt,
238
+ ...Ye,
230
239
  execute: (e, t) => {
231
240
  let n = e;
232
- return d.reportUsage(t.request.subject.tenantId ?? "", n.key, n.quantity).pipe(Y.map(() => ({ ok: !0 })));
241
+ return l.reportUsage(t.request.subject.tenantId ?? "", n.key, n.quantity).pipe(X.map(() => ({ ok: !0 })));
233
242
  }
234
243
  },
235
244
  {
236
- ...ft,
245
+ ...Ve,
237
246
  execute: (e, t) => {
238
247
  let n = e;
239
- return d.changePlan(t.request.subject.tenantId ?? "", n.plan).pipe(Y.map((e) => ({
248
+ return p(l.changePlan(t.request.subject.tenantId ?? "", n.plan, void 0, m(Ve, e, t), n.requestId).pipe(X.map((e) => ({
240
249
  plan: e.plan,
241
250
  quantity: e.quantity,
242
251
  prorationMinor: e.prorationMinor,
243
252
  currency: e.currency
244
- })));
253
+ }))), Ve, e, t);
245
254
  }
246
255
  },
247
256
  {
248
- ...pt,
257
+ ...He,
249
258
  execute: (e, t) => {
250
259
  let n = e;
251
- return d.changeSeats(t.request.subject.tenantId ?? "", n.quantity).pipe(Y.map((e) => ({
260
+ return p(l.changeSeats(t.request.subject.tenantId ?? "", n.quantity, void 0, m(He, e, t), n.requestId).pipe(X.map((e) => ({
252
261
  plan: e.plan,
253
262
  quantity: e.quantity,
254
263
  prorationMinor: e.prorationMinor,
255
264
  currency: e.currency
256
- })));
265
+ }))), He, e, t);
257
266
  }
258
267
  },
259
268
  {
260
- ...dt,
261
- execute: (e, t) => d.cancelSubscription(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({ subscription: Q(e) })))
269
+ ...Be,
270
+ execute: (e, t) => p(l.cancelSubscription(t.request.subject.tenantId ?? "", m(Be, e, t), e.requestId).pipe(X.map((e) => ({ subscription: Q(e) }))), Be, e, t)
271
+ },
272
+ {
273
+ ...Ge,
274
+ execute: (e, t) => p(l.subscriptionWriteStatus(t.request.subject.tenantId ?? "", e.requestId), Ge, e, t)
275
+ },
276
+ {
277
+ ...Ke,
278
+ source: [et, $e],
279
+ execute: (e, t) => p(l.pendingSubscriptionWrite(t.request.subject.tenantId ?? "").pipe(X.map((e) => ({ operation: e }))), Ke, e, t)
262
280
  },
263
281
  {
264
- ...xt,
265
- execute: (e, t) => d.syncTenant(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({ subscription: e === null ? null : Q(e) })))
282
+ ...Qe,
283
+ execute: (e, t) => l.syncTenant(t.request.subject.tenantId ?? "").pipe(X.map((e) => ({ subscription: e === null ? null : Q(e) })))
266
284
  },
267
285
  {
268
- ...yt,
269
- execute: (e, t) => d.resumeSubscription(t.request.subject.tenantId ?? "").pipe(Y.map((e) => ({ subscription: Q(e) })))
286
+ ...Xe,
287
+ execute: (e, t) => p(l.resumeSubscription(t.request.subject.tenantId ?? "", m(Xe, e, t), e.requestId).pipe(X.map((e) => ({ subscription: Q(e) }))), Xe, e, t)
270
288
  }
271
- ].map(v), ae = (e, t) => ({
289
+ ].map(ge), ve = (e, t) => ({
272
290
  kind: "json",
273
291
  status: e,
274
292
  data: { error: t }
275
- }), oe = [{
293
+ }), xe = [{
276
294
  method: "GET",
277
295
  path: "/stats",
278
296
  scope: "declaration",
279
297
  description: "Billing config: provider, declared plans, enforced tags",
280
- handler: () => Y.succeed({
298
+ handler: () => X.succeed({
281
299
  kind: "json",
282
300
  data: {
283
- provider: s.name,
284
- supportsMeteredUsage: s.supportsMeteredUsage,
285
- plans: o.planIds(),
286
- enforce: t.enforce ? Object.keys(t.enforce) : [],
287
- webhookPath: q
301
+ provider: r.name,
302
+ supportsMeteredUsage: r.supportsMeteredUsage,
303
+ plans: n.planIds(),
304
+ enforce: e.enforce ? Object.keys(e.enforce) : [],
305
+ webhookPath: O
288
306
  }
289
307
  })
290
308
  }, {
@@ -292,164 +310,267 @@ var Q = (e) => e === null ? null : {
292
310
  path: "/usage",
293
311
  scope: "process",
294
312
  description: "Pending (un-flushed) metered usage counters",
295
- handler: () => f.stores.usage.pending().pipe(Y.map((e) => ({
313
+ handler: () => u.stores.usage.pending().pipe(X.map((e) => ({
296
314
  kind: "json",
297
315
  data: { usage: e }
298
- })), Y.catch((e) => Y.succeed(ae(500, `${e.source} failed`))))
299
- }], se = [
316
+ })), X.catch((e) => X.succeed(ve(500, `${e.source} failed`))))
317
+ }], Se = [
300
318
  {
301
- schema: e,
319
+ schema: F,
302
320
  import: {
303
321
  module: "@voltro/plugin-billing/errors",
304
322
  name: "BillingError"
305
323
  }
306
324
  },
307
325
  {
308
- schema: r,
326
+ schema: rt,
309
327
  import: {
310
328
  module: "@voltro/plugin-billing/errors",
311
329
  name: "EntitlementExceeded"
312
330
  }
313
331
  },
314
332
  {
315
- schema: i,
333
+ schema: it,
316
334
  import: {
317
335
  module: "@voltro/plugin-billing/errors",
318
336
  name: "SubscriptionLocked"
319
337
  }
338
+ },
339
+ {
340
+ schema: nt,
341
+ import: {
342
+ module: "@voltro/plugin-billing/errors",
343
+ name: "BillingRequestStale"
344
+ }
320
345
  }
321
- ], b = t.enforce, ce = b !== void 0 && Object.keys(b).length > 0 ? te(b, d) : void 0, x = t.metering;
322
- x !== void 0 && Me(x);
323
- let S = x !== void 0 && Object.keys(x).length > 0 ? ke(d, x) : void 0, C = x !== void 0 && Ae(x), w = { claim: void 0 }, T = x === void 0 ? void 0 : Oe(d, x, {
324
- claimChange: () => w.claim,
346
+ ], h = e.enforce, we = h !== void 0 && Object.keys(h).length > 0 ? te(h, l) : void 0, g = e.metering;
347
+ g !== void 0 && se(g);
348
+ let _ = g !== void 0 && Object.keys(g).length > 0 ? ie(l, g) : void 0, v = g !== void 0 && ae(g), y = { claim: void 0 }, Ee = g === void 0 ? void 0 : re(l, g, {
349
+ claimChange: () => y.claim,
325
350
  onUngated: () => {
326
- Y.runSync(Y.logWarning("metering: CDC meters are accruing PER PROCESS — with N replicas a tenant is billed N times. The framework did not hand this plugin a change claimer (expected on the memory store; on a SQL store this is a bug worth reporting).").pipe(Y.annotateLogs({ scope: "voltro:billing" })));
351
+ X.runSync(X.logWarning("metering: CDC meters are accruing PER PROCESS — with N replicas a tenant is billed N times. The framework did not hand this plugin a change claimer (expected on the memory store; on a SQL store this is a bug worth reporting).").pipe(X.annotateLogs({ scope: "voltro:billing" })));
327
352
  }
328
- }), E = At([S, ce].filter((e) => e !== void 0)), D, O, k = !1, A = !1, j, M, N = null, P = !1, F, I = {
353
+ }), b = en([_, we].filter((e) => e !== void 0)), x, S = e.invoiceHistoryRecoveryIntervalMs ?? 6e4;
354
+ if (!Number.isSafeInteger(S) || S < 0 || S !== 0 && (S < 1e3 || S > 864e5)) throw TypeError("Invoice-history recovery requires 0 or a whole interval from one second through one day");
355
+ let De = r.listInvoiceHistory !== void 0 && r.fetchInvoiceSnapshot !== void 0, Oe = Z({
356
+ base: $,
357
+ alias: e.alias,
358
+ instance: e.name
359
+ }) + ".invoiceHistoryRecovery", C, w, T, E = 0, Ie = () => {
360
+ if (!V || x === void 0 || !De) return Promise.resolve();
361
+ if (T !== void 0) return T;
362
+ let e = u.stores, t = E, n = Promise.resolve().then(async () => {
363
+ let n = performance.now() + 3e4, r = {
364
+ passes: 0,
365
+ admittedPages: 0,
366
+ observed: 0,
367
+ deferred: 0,
368
+ busy: 0,
369
+ unconfirmed: 0
370
+ };
371
+ try {
372
+ for (let i = 0; i < 8 && performance.now() < n; i++) {
373
+ if (!V || E !== t || u.stores !== e) return;
374
+ let n = await X.runPromise(l.reconcileInvoiceHistory());
375
+ if (r.passes++, r.admittedPages += n.admittedPages, r.observed += n.observed, r.deferred += n.deferred, r.busy += n.busy, r.unconfirmed += n.unconfirmed, n.kind === "idle" || n.kind === "contended") break;
376
+ }
377
+ if (r.unconfirmed > 0) throw Error("Original invoice observations remain unconfirmed");
378
+ V && E === t && (r.admittedPages > 0 || r.observed > 0 || r.deferred > 0) && J.info("billing invoice-history recovery", r);
379
+ } catch {
380
+ throw J.error("Billing invoice-history recovery remains retryable; native custody is retained.", r), new F({
381
+ source: "invoiceHistoryRecovery",
382
+ transient: !0,
383
+ message: "The bounded invoice-history recovery pass remains unconfirmed."
384
+ });
385
+ }
386
+ });
387
+ return T = n, n.then(() => {
388
+ T === n && (T = void 0);
389
+ }, () => {
390
+ T === n && (T = void 0);
391
+ }), n;
392
+ }, D = async () => {
393
+ let e = w;
394
+ w = void 0, C = void 0, E++;
395
+ let t = (await Promise.allSettled([Promise.resolve().then(() => e?.stop()), T ?? Promise.resolve()])).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
396
+ if (t.length > 0) throw AggregateError(t, "Billing invoice-history work did not drain cleanly");
397
+ }, k = () => {
398
+ if (!V || x === void 0 || w !== void 0 || S === 0 || !De) return;
399
+ let e = C;
400
+ if (e?.workloads === void 0 || e.workloads.includes("schedules")) {
401
+ if (e?.scheduleCoordinated === void 0) throw Error("Automatic invoice-history recovery requires native coordinated schedule binding; configure 0 only with an explicit recovery driver");
402
+ w = e.scheduleCoordinated(Oe, S, Ie);
403
+ }
404
+ }, j = e.subscriptionWriteRecoveryIntervalMs ?? 6e4;
405
+ if (!Number.isSafeInteger(j) || j < 0 || j !== 0 && (j < 1e3 || j > 864e5)) throw TypeError("Subscription-write recovery requires 0 or a whole interval from one second through one day");
406
+ let M = r.supportsNativeSubscriptionWrites === !0, tt = Z({
407
+ base: $,
408
+ alias: e.alias,
409
+ instance: e.name
410
+ }) + ".subscriptionWriteRecovery", N, P, I, L = 0, R = null, at = () => {
411
+ if (!V || x === void 0 || !M) return Promise.resolve();
412
+ if (I !== void 0) return I;
413
+ let e = u.stores, t = L, n = Promise.resolve().then(async () => {
414
+ let n = await X.runPromise(l.recoverSubscriptionWrites({
415
+ limit: 25,
416
+ afterTenantId: R
417
+ }));
418
+ L === t && u.stores === e && (R = n.nextAfter, (n.completed > 0 || n.withdrawn > 0 || n.pending > 0) && J.info("billing subscription-write recovery", { ...n }));
419
+ }).catch(() => {
420
+ throw J.error("Billing subscription-write recovery remains retryable; native intents are retained.", {}), new F({
421
+ source: "subscriptionWriteRecovery",
422
+ transient: !0,
423
+ message: "The bounded subscription-write recovery pass remains unconfirmed."
424
+ });
425
+ });
426
+ return I = n, n.then(() => {
427
+ I === n && (I = void 0);
428
+ }, () => {
429
+ I === n && (I = void 0);
430
+ }), n;
431
+ }, z = async () => {
432
+ let e = P;
433
+ P = void 0, N = void 0, L++, R = null;
434
+ let t = (await Promise.allSettled([Promise.resolve().then(() => e?.stop()), I ?? Promise.resolve()])).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
435
+ if (t.length > 0) throw AggregateError(t, "Billing subscription-write recovery did not drain cleanly");
436
+ }, ot = () => {
437
+ if (!V || x === void 0 || P !== void 0 || j === 0 || !M) return;
438
+ let e = N;
439
+ if (e?.workloads === void 0 || e.workloads.includes("schedules")) {
440
+ if (e?.scheduleCoordinated === void 0) throw Error("Automatic subscription-write recovery requires native coordinated schedule binding; configure 0 only with an explicit recovery driver");
441
+ P = e.scheduleCoordinated(tt, j, at);
442
+ }
443
+ }, B, V = !1, H = !1, U, W, G = null, K = !1, q, J = {
329
444
  info: (e, t) => {
330
445
  console.info(e, t ?? {});
331
446
  },
332
447
  error: (e, t) => {
333
448
  console.error(e, t ?? {});
334
449
  }
335
- }, L = (e) => {
336
- k && M === void 0 && (M = setTimeout(() => {
337
- M = void 0, R();
338
- }, e), M.unref?.());
339
- }, R = () => {
340
- let e = s.listUndeliveredEvents;
341
- if (!k || D === void 0 || e === void 0) return Promise.resolve();
342
- if (j !== void 0) return j;
343
- let t = F === void 0 ? 0 : 6e4 - (performance.now() - F);
344
- return t > 0 ? (L(t), Promise.resolve()) : (j = Promise.resolve().then(async () => {
450
+ }, st = (e) => {
451
+ V && W === void 0 && (W = setTimeout(() => {
452
+ W = void 0, Y();
453
+ }, e), W.unref?.());
454
+ }, Y = () => {
455
+ let e = r.listUndeliveredEvents;
456
+ if (!V || x === void 0 || e === void 0) return Promise.resolve();
457
+ if (U !== void 0) return U;
458
+ let t = q === void 0 ? 0 : 6e4 - (performance.now() - q);
459
+ return t > 0 ? (st(t), Promise.resolve()) : (U = Promise.resolve().then(async () => {
345
460
  let t = !1, n = 0, r = 0, i = 0, a = /* @__PURE__ */ new Set();
346
461
  try {
347
- for (let o = 0; o < 10 && k; o++) {
348
- let o = N;
462
+ for (let o = 0; o < 10 && V; o++) {
463
+ let o = G;
349
464
  if (o !== null) {
350
465
  if (a.has(o)) throw Error("The provider event cursor repeated.");
351
466
  a.add(o);
352
467
  }
353
- let s = await Y.runPromise(e({
468
+ let s = await X.runPromise(e({
354
469
  cursor: o,
355
470
  limit: 100
356
471
  }));
357
472
  if (!Array.isArray(s.events) || s.events.length > 100 || s.nextCursor !== null && (typeof s.nextCursor != "string" || !s.nextCursor || s.nextCursor !== s.events.at(-1)?.id || s.nextCursor === o)) throw Error("The provider event page did not supply a bounded advancing cursor.");
358
473
  for (let e of s.events) {
359
- if (!k) return;
474
+ if (!V) return;
360
475
  try {
361
- await Y.runPromise(h(e)) === "processed" ? n++ : r++;
476
+ await X.runPromise(le(e)) === "processed" ? n++ : r++;
362
477
  } catch {
363
- i++, P = !0, I.error("billing catch-up: delivery remains retryable", { eventId: e.id });
478
+ i++, K = !0, J.error("billing catch-up: delivery remains retryable", { eventId: e.id });
364
479
  }
365
480
  }
366
- if (N = s.nextCursor, N === null) {
367
- t = P, P = !1;
481
+ if (G = s.nextCursor, G === null) {
482
+ t = K, K = !1;
368
483
  break;
369
484
  }
370
485
  t = !0;
371
486
  }
372
- I.info("billing catch-up", {
487
+ J.info("billing catch-up", {
373
488
  processed: n,
374
489
  replayed: r,
375
490
  failed: i,
376
- continuation: N !== null
491
+ continuation: G !== null
377
492
  });
378
493
  } catch {
379
- t = !0, I.error("billing catch-up failed; the current page will be retried");
494
+ t = !0, J.error("billing catch-up failed; the current page will be retried");
380
495
  } finally {
381
- F = performance.now(), j = void 0, t && L(6e4);
496
+ q = performance.now(), U = void 0, t && st(6e4);
382
497
  }
383
- }), j);
384
- }, z = (e) => {
385
- e !== void 0 && (I = e), !A && k && D !== void 0 && (A = !0, R());
386
- }, B = [
498
+ }), U);
499
+ }, ct = (e) => {
500
+ e !== void 0 && (J = e), !H && V && x !== void 0 && (H = !0, Y());
501
+ }, lt = [
387
502
  "store:write",
388
503
  "inspect:read",
389
504
  "inspect:write",
390
505
  "network:outbound:*",
391
- ...E === void 0 ? [] : [
506
+ ...b === void 0 ? [] : [
392
507
  "rpc:intercept:mutation",
393
508
  "rpc:intercept:action",
394
509
  "rpc:intercept:workflow"
395
510
  ],
396
- ...S === void 0 ? [] : ["rpc:intercept:query"],
397
- ...C ? ["store:changes:read"] : []
511
+ ..._ === void 0 ? [] : ["rpc:intercept:query"],
512
+ ...v ? ["store:changes:read"] : []
398
513
  ];
399
- return jt({
400
- name: Mt({
514
+ return tn({
515
+ name: Z({
401
516
  base: $,
402
- alias: t.alias,
403
- instance: t.name
517
+ alias: e.alias,
518
+ instance: e.name
404
519
  }),
405
520
  baseName: $,
406
521
  description: "Billing — subscriptions, plans, entitlements + usage metering over a pluggable BillingProvider (Stripe + mock). Ships the BillingService, the requireEntitlement() in-handler guard + the enforce-map interceptor, the /billing/webhook receiver (riding @voltro/plugin-webhooks for signature + idempotency), and the _voltro_billing_* tables. Money is integer minor units.",
407
- permissions: B,
408
- declaredEnv: Rt.declared,
409
- egress: rt(s),
522
+ permissions: lt,
523
+ declaredEnv: on.declared,
524
+ egress: Fe(r),
410
525
  services: ne,
411
- routes: ie,
412
- rpcClientDescriptors: ut,
413
- httpRoutes: [_],
414
- inspectEndpoints: oe,
415
- extendSchema: { tables: [...W(), Ie] },
416
- errorSchemas: se,
417
- ...E === void 0 ? {} : {
418
- interceptMutation: E,
419
- interceptAction: E,
420
- interceptWorkflow: E
526
+ routes: _e,
527
+ rpcClientDescriptors: ze,
528
+ httpRoutes: [me],
529
+ inspectEndpoints: xe,
530
+ extendSchema: { tables: [...Ce(), je] },
531
+ errorSchemas: Se,
532
+ ...b === void 0 ? {} : {
533
+ interceptMutation: b,
534
+ interceptAction: b,
535
+ interceptWorkflow: b
421
536
  },
422
- ...S === void 0 ? {} : { interceptQuery: S },
423
- ...C ? { onChangeEvent: T } : {},
424
- bindDataStore: (e, t) => {
425
- f.stores = G(e), D = e, p = Lt(e), z(), w.claim = t?.claimChange;
537
+ ..._ === void 0 ? {} : { interceptQuery: _ },
538
+ ...v ? { onChangeEvent: Ee } : {},
539
+ bindDataStore: async (e, t) => {
540
+ await Promise.all([D(), z()]), C = t, N = t, u.stores = he(e), x = e, d = $t(e), ct(), y.claim = t?.claimChange, k(), ot();
426
541
  },
427
- onActivate: (e) => Y.sync(() => {
428
- e.logger.info("billing active", {
429
- provider: s.name,
430
- plans: o.planIds().length,
431
- enforce: b ? Object.keys(b).length : 0,
432
- metering: x ? Object.keys(x).length : 0,
433
- webhook: q,
434
- redirectOrigins: t.redirectOrigins?.length ?? "any"
435
- }), s.name === "stripe" && t.redirectOrigins === void 0 && e.logger.warn("billing: no redirectOrigins — checkout and portal accept any return URL; set billingPlugin({ redirectOrigins })", {});
436
- let n = t.flushIntervalMs ?? 6e4, r = x, i = r !== void 0 && Object.keys(r).length > 0;
437
- if (n > 0) {
438
- let e = It();
439
- O = setInterval(() => {
440
- let t = D;
542
+ onActivate: (t) => (Pe(a), X.sync(() => {
543
+ t.logger.info("billing active", {
544
+ provider: r.name,
545
+ plans: n.planIds().length,
546
+ enforce: h ? Object.keys(h).length : 0,
547
+ metering: g ? Object.keys(g).length : 0,
548
+ webhook: O,
549
+ redirectOrigins: e.redirectOrigins?.length ?? "any"
550
+ }), r.name === "stripe" && e.redirectOrigins === void 0 && t.logger.warn("billing: no redirectOrigins — checkout and portal accept any return URL; set billingPlugin({ redirectOrigins })", {});
551
+ let i = e.flushIntervalMs ?? 6e4, a = g, o = a !== void 0 && Object.keys(a).length > 0;
552
+ if (i > 0) {
553
+ let e = an();
554
+ B = setInterval(() => {
555
+ let t = x;
441
556
  if (t === void 0) return;
442
- let a = Date.now();
557
+ let n = Date.now();
443
558
  (async () => {
444
- await Le(t, Re(a, n), e, a) && await Y.runPromise((i ? je(d, t, r) : d.flushUsage()).pipe(Y.catch(() => Y.void)));
559
+ await Me(t, Ne(n, i), e, n) && await X.runPromise((o ? oe(l, t, a) : l.flushUsage()).pipe(X.catch(() => X.void)));
445
560
  })();
446
- }, n), O.unref?.();
561
+ }, i), B.unref?.();
447
562
  }
448
- k = !0, z(e.logger);
449
- }),
450
- onDeactivate: () => Y.promise(async () => {
451
- k = !1, A = !1, M !== void 0 && (clearTimeout(M), M = void 0), O !== void 0 && (clearInterval(O), O = void 0), await j;
563
+ V = !0, ct(t.logger), k(), ot();
564
+ })),
565
+ onDeactivate: () => X.promise(async () => {
566
+ V = !1, H = !1, W !== void 0 && (clearTimeout(W), W = void 0), B !== void 0 && (clearInterval(B), B = void 0);
567
+ let e = (await Promise.allSettled([
568
+ D(),
569
+ z(),
570
+ U ?? Promise.resolve()
571
+ ])).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
572
+ if (e.length > 0) throw AggregateError(e, "Billing recovery shutdown requires reconciliation");
452
573
  })
453
574
  });
454
575
  };
455
- export { D as BILLING_CHECKOUT_OPERATIONS_TABLE, j as BILLING_CLOSE_OPERATIONS_TABLE, o as BILLING_CUSTODY_INVENTORY_TABLES, _e as BILLING_CUSTOMERS_TABLE, c as BILLING_CUSTOMER_ACCOUNTS_TABLE, l as BILLING_CUSTOMER_CUSTODY_TABLE, le as BILLING_DUNNING_NOTICES_TABLE, Fe as BILLING_FLUSH_CLAIMS_TABLE, ve as BILLING_INVOICES_TABLE, ce as BILLING_INVOICE_HISTORY_DISPATCH_TABLE, p as BILLING_INVOICE_HISTORY_PAGES_TABLE, m as BILLING_INVOICE_HISTORY_REFERENCES_TABLE, x as BILLING_INVOICE_HISTORY_SCAN_ACCOUNTS_TABLE, h as BILLING_INVOICE_HISTORY_WALKS_TABLE, oe as BILLING_INVOICE_HISTORY_WORK_TABLE, re as BILLING_INVOICE_OBSERVATIONS_TABLE, H as BILLING_SUBSCRIPTIONS_TABLE, T as BILLING_USAGE_EVENTS_TABLE, U as BILLING_USAGE_TABLE, st as BILLING_WEBHOOK_ID, q as BILLING_WEBHOOK_PATH, e as BillingError, t as BillingService, F as DEFAULT_DUNNING_STEPS, I as DEFAULT_GRACE_HOURS, L as DEFAULT_LOCKOUT, n as DEFAULT_PLAN, R as DUNNING_LOCK_STEP_ID, r as EntitlementExceeded, ze as STRIPE_API_VERSION, Be as STRIPE_DASHBOARD_REMINDERS, $e as STRIPE_WEBHOOK_EVENTS, Ye as StripeRestError, i as SubscriptionLocked, nt as assertBillingProductionReady, O as billingCheckoutOperationsTable, M as billingCloseOperationsTable, u as billingCustomerAccountsTable, ee as billingCustomerCustodyTable, ye as billingCustomersTable, z as billingDunningNoticesTable, rt as billingEgressOf, Ie as billingFlushClaimsTable, S as billingInvoiceHistoryDispatchTable, g as billingInvoiceHistoryPagesTable, _ as billingInvoiceHistoryReferencesTable, C as billingInvoiceHistoryScanAccountsTable, v as billingInvoiceHistoryWalksTable, se as billingInvoiceHistoryWorkTable, ie as billingInvoiceObservationsTable, be as billingInvoicesTable, zt as billingPlugin, ae as billingRetainedInvoiceObservationsTable, K as billingServiceLayer, xe as billingSubscriptionsTable, W as billingTables, E as billingUsageEventsTable, Se as billingUsageTable, ct as billingWebhookDescriptor, Ee as buildBillingService, te as buildEnforceInterceptor, Ne as buildPlanRegistry, Le as claimFlushWindow, N as dataStoreBillingCloseStore, k as dataStoreCheckoutOperationStore, B as dataStoreDunningNoticeStore, y as dataStoreInvoiceHistoryJournal, w as dataStoreInvoiceHistoryProgressStore, b as dataStoreInvoiceHistoryWorkStore, G as dataStoreStores, ue as defaultDunningEmail, Ve as diffMeter, He as diffPortal, Ue as diffPrice, We as diffProduct, Ge as diffTaxSettings, Ke as diffWebhook, de as dueSteps, fe as dunningMailNotifier, Pe as emptyPlanRegistry, St as envOutRefusal, pe as episodeKeyOf, me as evaluateBillingEntitlement, d as evaluateEntitlement, Re as flushWindowKey, Xe as formEncode, he as graceEndOf, s as inspectBillingCustody, it as isProductionBoot, Ce as isStaleStatusEvent, P as memoryBillingCloseStore, A as memoryCheckoutOperationStore, ge as memoryDunningNoticeStore, we as memoryStores, Ct as mergeEnvFile, at as mockProvider, lt as mountBillingWebhook, et as normalizeStripeEvent, wt as openFindings, Tt as parseProvisionArgs, De as periodKey, qe as portalParams, Et as provisionStripeCatalog, Ze as redactStripeKeys, f as requireEntitled, ne as requireEntitlement, V as resolveDunningConfig, ot as resolveProvider, Dt as resolveProvisionKey, Ot as runStripeProvision, Te as selectCurrentSubscription, Je as sellingReadiness, tt as stripeProvider, Qe as stripeRest };
576
+ export { At as BILLING_ACCOUNT_CUSTODY_INVENTORY_TABLES, _t as BILLING_CHECKOUT_OPERATIONS_TABLE, xt as BILLING_CLOSE_OPERATIONS_TABLE, jt as BILLING_CUSTODY_INVENTORY_TABLES, _e as BILLING_CUSTOMERS_TABLE, s as BILLING_CUSTOMER_ACCOUNTS_TABLE, c as BILLING_CUSTOMER_CUSTODY_TABLE, Te as BILLING_DUNNING_NOTICES_TABLE, Ae as BILLING_FLUSH_CLAIMS_TABLE, ve as BILLING_INVOICES_TABLE, Wt as BILLING_INVOICE_HISTORY_DISPATCH_TABLE, Pt as BILLING_INVOICE_HISTORY_PAGES_TABLE, Ft as BILLING_INVOICE_HISTORY_REFERENCES_TABLE, Gt as BILLING_INVOICE_HISTORY_SCAN_ACCOUNTS_TABLE, It as BILLING_INVOICE_HISTORY_WALKS_TABLE, Vt as BILLING_INVOICE_HISTORY_WORK_TABLE, ce as BILLING_INVOICE_OBSERVATIONS_TABLE, ye as BILLING_SUBSCRIPTIONS_TABLE, $e as BILLING_SUBSCRIPTION_WRITES_TABLE, et as BILLING_SUBSCRIPTION_WRITE_HEADS_TABLE, Ot as BILLING_USAGE_EVENTS_TABLE, be as BILLING_USAGE_TABLE, D as BILLING_WEBHOOK_ID, O as BILLING_WEBHOOK_PATH, P as BillingClosurePending, F as BillingError, nt as BillingRequestStale, I as BillingService, g as DEFAULT_DUNNING_STEPS, _ as DEFAULT_GRACE_HOURS, v as DEFAULT_LOCKOUT, L as DEFAULT_PLAN, y as DUNNING_LOCK_STEP_ID, rt as EntitlementExceeded, i as InvoicePaymentObservationSchema, ft as STRIPE_API_VERSION, R as STRIPE_DASHBOARD_REMINDERS, Tt as STRIPE_WEBHOOK_EVENTS, pt as StripeRestError, it as SubscriptionLocked, Pe as assertBillingProductionReady, a as assertInvoicePaymentObservation, vt as billingCheckoutOperationsTable, St as billingCloseOperationsTable, ee as billingCustomerAccountsTable, l as billingCustomerCustodyTable, xe as billingCustomersTable, Ee as billingDunningNoticesTable, Fe as billingEgressOf, je as billingFlushClaimsTable, Kt as billingInvoiceHistoryDispatchTable, Lt as billingInvoiceHistoryPagesTable, Rt as billingInvoiceHistoryReferencesTable, qt as billingInvoiceHistoryScanAccountsTable, zt as billingInvoiceHistoryWalksTable, Ht as billingInvoiceHistoryWorkTable, f as billingInvoiceObservationsTable, n as billingInvoicePaymentCorrectionsTable, r as billingInvoicePaymentHeadsTable, Se as billingInvoicesTable, sn as billingPlugin, le as billingRetainedInvoiceObservationsTable, fe as billingServiceLayer, j as billingSubscriptionWriteHeadsTable, M as billingSubscriptionWritesTable, h as billingSubscriptionsTable, Ce as billingTables, kt as billingUsageEventsTable, we as billingUsageTable, k as billingWebhookDescriptor, pe as buildBillingService, te as buildEnforceInterceptor, ue as buildPlanRegistry, t as captureSubscriptionObservation, Me as claimFlushWindow, Ct as dataStoreBillingCloseStore, yt as dataStoreCheckoutOperationStore, b as dataStoreDunningNoticeStore, Bt as dataStoreInvoiceHistoryJournal, Jt as dataStoreInvoiceHistoryProgressStore, Ut as dataStoreInvoiceHistoryWorkStore, he as dataStoreStores, tt as dataStoreSubscriptionWriteStore, x as defaultDunningEmail, at as diffMeter, z as diffPortal, ot as diffPrice, B as diffProduct, V as diffRetiredMeter, H as diffRetiredPrice, U as diffRetiredProduct, W as diffTaxSettings, G as diffWebhook, S as dueSteps, De as dunningMailNotifier, de as emptyPlanRegistry, J as envOutRefusal, Oe as episodeKeyOf, C as evaluateBillingEntitlement, u as evaluateEntitlement, Ne as flushWindowKey, mt as formEncode, w as graceEndOf, Mt as inspectBillingAccountCustody, Nt as inspectBillingCustody, E as isProductionBoot, ge as isStaleStatusEvent, N as isTerminalSubscriptionWrite, wt as memoryBillingCloseStore, bt as memoryCheckoutOperationStore, T as memoryDunningNoticeStore, p as memoryStores, st as mergeEnvFile, Ie as mockProvider, Re as mountBillingWebhook, Et as normalizeStripeEvent, Y as openFindings, e as paidInvoiceCoverageInTransaction, ct as parseProvisionArgs, me as periodKey, K as portalParams, lt as provisionStripeCatalog, ht as redactStripeKeys, ne as requireEntitled, d as requireEntitlement, ke as resolveDunningConfig, Le as resolveProvider, ut as resolveProvisionKey, dt as runStripeProvision, m as selectCurrentSubscription, q as sellingReadiness, Dt as stripeProvider, gt as stripeRest };