@voltro/plugin-billing 0.89.2 → 0.90.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.
package/dist/providers.js CHANGED
@@ -1,29 +1,31 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { captureProviderAccount as t, captureProviderCustomer as n, providerIdentityError as r, sameProviderAccount as i } from "./providerIdentity.js";
3
- import { decodeInvoiceSnapshot as a, encodeInvoiceSnapshot as o, invoiceSnapshotError as s } from "./invoiceSnapshot.js";
2
+ import { decodeInvoiceSnapshot as t, encodeInvoiceSnapshot as n, invoiceSnapshotError as r } from "./invoiceSnapshot.js";
3
+ import { captureProviderAccount as i, captureProviderCustomer as a, providerIdentityError as o, sameProviderAccount as s } from "./providerIdentity.js";
4
4
  import { captureInvoiceHistoryInput as c, captureInvoiceHistoryPage as l, historyError as u, invoiceHistoryPreview as d } from "./invoiceHistory.js";
5
+ import "./subscriptionObservation.js";
5
6
  import { STRIPE_WEBHOOK_EVENTS as f, normalizeStripeEvent as p, stripeProvider as m } from "./stripeProvider.js";
6
7
  import { Effect as h } from "effect";
8
+ import { bootRefusal as g } from "@voltro/runtime/boot-refusal";
7
9
  // src/providers.ts
8
- var g = (f) => {
9
- let p = t({
10
+ var _ = (f) => {
11
+ let p = i({
10
12
  providerAccountId: f?.accountId ?? "mock_" + globalThis.crypto.randomUUID(),
11
13
  livemode: !1
12
14
  }), m = /* @__PURE__ */ new Map(), g = 0, _ = f?.baseUrl ?? "https://mock.billing.local", v = [], y = [], b = [], x = /* @__PURE__ */ new Map(), S = /* @__PURE__ */ new Map(), C = /* @__PURE__ */ new Map(), w = /* @__PURE__ */ new Map(), T = [], E = (t) => h.try({
13
15
  try: () => {
14
16
  let e = c(t);
15
- if (!i(e.account, p)) throw u("The mock invoice history account differs.");
17
+ if (!s(e.account, p)) throw u("The mock invoice history account differs.");
16
18
  let n = T.filter((t) => t.providerCustomerId === e.providerCustomerId).slice().sort((e, t) => t.createdAt.getTime() - e.createdAt.getTime() || (e.providerInvoiceId < t.providerInvoiceId ? 1 : e.providerInvoiceId > t.providerInvoiceId ? -1 : 0)), r = e.cursor === void 0 ? -1 : n.findIndex((t) => t.providerInvoiceId === e.cursor?.afterInvoiceId);
17
19
  if (e.cursor !== void 0 && r < 0) throw u("The mock invoice cursor does not belong to this customer.");
18
- let a = n.slice(r + 1, r + 1 + e.limit), o = a[a.length - 1];
20
+ let i = n.slice(r + 1, r + 1 + e.limit), a = i[i.length - 1];
19
21
  return l(e, {
20
22
  account: p,
21
23
  providerCustomerId: e.providerCustomerId,
22
- invoices: a,
23
- nextCursor: r + 1 + a.length < n.length && o !== void 0 ? {
24
+ invoices: i,
25
+ nextCursor: r + 1 + i.length < n.length && a !== void 0 ? {
24
26
  ...p,
25
27
  providerCustomerId: e.providerCustomerId,
26
- afterInvoiceId: o.providerInvoiceId
28
+ afterInvoiceId: a.providerInvoiceId
27
29
  } : null,
28
30
  observedAt: j()
29
31
  });
@@ -51,26 +53,73 @@ var g = (f) => {
51
53
  ...r,
52
54
  ...t
53
55
  }), n;
54
- }, B = (e) => typeof e == "object" && !!e && typeof e._tag == "string";
56
+ }, B = (e) => typeof e == "object" && !!e && typeof e._tag == "string", V = /* @__PURE__ */ new Map(), H = null, U = (e) => {
57
+ let t = S.get(e), n = x.get(e);
58
+ return t === void 0 || n === void 0 ? null : {
59
+ ...t,
60
+ ...n,
61
+ writeOperationId: V.get(e) ?? null,
62
+ providerObservedAt: new Date(j().getTime()),
63
+ providerPlanItemId: t.providerPlanItemId ?? "mock-item:" + e
64
+ };
65
+ }, W = (t, n, r) => h.gen(function* () {
66
+ if (n === void 0) return yield* r;
67
+ let i = U(t);
68
+ if (i === null || n.itemId !== null && n.itemId !== i.providerPlanItemId || n.expectedPriceId !== null && !i.priceIds.includes(n.expectedPriceId)) return yield* n.notDispatched(), yield* h.fail(new e({
69
+ source: "mock",
70
+ message: "Original provider subscription/item is missing.",
71
+ transient: !1
72
+ }));
73
+ if (i.writeOperationId === n.id) return yield* n.applied(i), yield* h.fail(new e({
74
+ source: "mock",
75
+ message: "Execution already observed; read current subscription.",
76
+ transient: !0
77
+ }));
78
+ let a = H;
79
+ if (H = null, a === "notDispatched") return yield* n.notDispatched(), yield* h.fail(new e({
80
+ source: "mock",
81
+ message: "The write was refused before dispatch.",
82
+ transient: !1
83
+ }));
84
+ if (yield* n.beforeDispatch().pipe(h.catch((e) => n.notDispatched().pipe(h.andThen(h.fail(e))))), a === "rejected") return yield* n.rejected("StripeInvalidRequestError (resource_missing)"), yield* h.fail(new e({
85
+ source: "mock",
86
+ message: "StripeInvalidRequestError (resource_missing)",
87
+ transient: !1
88
+ }));
89
+ if (a === "unknown") return yield* h.fail(new e({
90
+ source: "mock",
91
+ message: "The provider did not answer.",
92
+ transient: !0
93
+ }));
94
+ let o = yield* r;
95
+ V.set(t, n.id);
96
+ let s = U(t);
97
+ return s === null ? yield* h.fail(new e({
98
+ source: "mock",
99
+ message: "Provider result is unconfirmed.",
100
+ transient: !0
101
+ })) : (yield* n.applied(s), o);
102
+ });
55
103
  return {
56
104
  name: "mock",
57
- fetchAccountIdentity: () => h.succeed(t(p)),
105
+ supportsNativeSubscriptionWrites: !0,
106
+ fetchAccountIdentity: () => h.succeed(i(p)),
58
107
  fetchCustomerSnapshot: (e) => h.try({
59
108
  try: () => {
60
- let a = t(e.account);
61
- if (!i(a, p)) throw r();
62
- let o = m.get(e.providerCustomerId);
63
- if (o === void 0) throw r();
64
- return n({
65
- ...o,
109
+ let t = i(e.account);
110
+ if (!s(t, p)) throw o();
111
+ let n = m.get(e.providerCustomerId);
112
+ if (n === void 0) throw o();
113
+ return a({
114
+ ...n,
66
115
  observedAt: j()
67
116
  });
68
117
  },
69
- catch: () => r()
118
+ catch: () => o()
70
119
  }),
71
120
  setCustomerSnapshot: (e) => {
72
- let t = n(e);
73
- if (!i(t.account, p)) throw r();
121
+ let t = a(e);
122
+ if (!s(t.account, p)) throw o();
74
123
  m.set(t.providerCustomerId, t);
75
124
  },
76
125
  setInvoiceHistory: (e) => {
@@ -95,20 +144,20 @@ var g = (f) => {
95
144
  T = Object.freeze(n);
96
145
  },
97
146
  setInvoiceSnapshot: (e) => {
98
- let t = o(e);
147
+ let t = n(e);
99
148
  w.set(e.providerInvoiceId, {
100
149
  customerId: e.providerCustomerId,
101
150
  encoded: t
102
151
  });
103
152
  },
104
- fetchInvoiceSnapshot: (t) => h.try({
153
+ fetchInvoiceSnapshot: (n) => h.try({
105
154
  try: () => {
106
- let e = w.get(t.providerInvoiceId);
107
- if (e === void 0) throw s("The mock provider has no detailed invoice evidence.");
108
- if (e.customerId !== t.providerCustomerId) throw s("The invoice belongs to a different mock billing customer.");
109
- return a(e.encoded);
155
+ let e = w.get(n.providerInvoiceId);
156
+ if (e === void 0) throw r("The mock provider has no detailed invoice evidence.");
157
+ if (e.customerId !== n.providerCustomerId) throw r("The invoice belongs to a different mock billing customer.");
158
+ return t(e.encoded);
110
159
  },
111
- catch: (t) => t instanceof e ? t : s("The mock invoice observation is invalid.")
160
+ catch: (t) => t instanceof e ? t : r("The mock invoice observation is invalid.")
112
161
  }),
113
162
  supportsMeteredUsage: f?.supportsMeteredUsage ?? !0,
114
163
  pushed: v,
@@ -124,6 +173,9 @@ var g = (f) => {
124
173
  L = structuredClone(e);
125
174
  },
126
175
  undeliveredReads: () => R,
176
+ failNextWrite: (e) => {
177
+ H = e;
178
+ },
127
179
  listUndeliveredEvents: (t) => h.try({
128
180
  try: () => {
129
181
  if (R += 1, !Number.isInteger(t.limit) || t.limit < 1 || t.limit > 100) throw Error("Invalid event page size.");
@@ -144,13 +196,13 @@ var g = (f) => {
144
196
  ensureCustomer: (e) => h.sync(() => {
145
197
  let t = I.get(e.tenantId);
146
198
  if (t !== void 0 && m.get(t)?.deleted === !1) return t;
147
- let r = `mock_cus_${e.tenantId}`, i = t === void 0 ? r : `${r}_${++g}`, a = n({
199
+ let n = `mock_cus_${e.tenantId}`, r = t === void 0 ? n : `${n}_${++g}`, i = a({
148
200
  account: p,
149
- providerCustomerId: i,
201
+ providerCustomerId: r,
150
202
  deleted: !1,
151
203
  observedAt: j()
152
204
  });
153
- return I.set(e.tenantId, i), m.set(i, a), P.push(e.tenantId), i;
205
+ return I.set(e.tenantId, r), m.set(r, i), P.push(e.tenantId), r;
154
206
  }),
155
207
  expireOpenCheckouts: (e) => h.sync(() => {
156
208
  F.push(e.providerCustomerId);
@@ -171,18 +223,11 @@ var g = (f) => {
171
223
  setCustomerEmail: (e, t) => {
172
224
  t === null ? C.delete(e) : C.set(e, t);
173
225
  },
174
- fetchSubscriptionSnapshot: (e) => h.sync(() => {
175
- b.push(e);
176
- let t = S.get(e), n = x.get(e);
177
- return t === void 0 || n === void 0 ? null : {
178
- ...t,
179
- ...n
180
- };
181
- }),
226
+ fetchSubscriptionSnapshot: (e) => h.sync(() => (b.push(e), U(e))),
182
227
  fetchSubscription: (e) => h.sync(() => (b.push(e), x.get(e) ?? null)),
183
228
  listSubscriptions: (e) => h.sync(() => [...S.values()].filter((t) => t.status !== "canceled" && (e.providerCustomerId === void 0 || t.providerCustomerId === e.providerCustomerId))),
184
229
  prepareSubscriptionClose: () => h.sync(() => ({ cancelAt: /* @__PURE__ */ new Date(Math.ceil(j().getTime() / 1e3) * 1e3 + 6e5) })),
185
- cancelSubscription: (t) => h.try({
230
+ cancelSubscription: (t) => W(t.providerSubscriptionId, t.operation, h.try({
186
231
  try: () => {
187
232
  D.push({
188
233
  providerSubscriptionId: t.providerSubscriptionId,
@@ -203,15 +248,15 @@ var g = (f) => {
203
248
  message: "A valid retained billing close operation is required.",
204
249
  transient: !1
205
250
  })
206
- }),
207
- resumeSubscription: (e) => h.sync(() => (O.push(e), z(e, { cancelAt: null }))),
251
+ })),
252
+ resumeSubscription: (e, t) => W(e, t, h.sync(() => (O.push(e), z(e, { cancelAt: null })))),
208
253
  addSubscriptionPrices: (e) => h.sync(() => {
209
254
  k.push({
210
255
  providerSubscriptionId: e.providerSubscriptionId,
211
256
  priceIds: e.priceIds
212
257
  });
213
258
  let t = S.get(e.providerSubscriptionId);
214
- t !== void 0 && z(e.providerSubscriptionId, { priceIds: [...t.priceIds, ...e.priceIds] });
259
+ t !== void 0 && z(e.providerSubscriptionId, { priceIds: [.../* @__PURE__ */ new Set([...t.priceIds, ...e.priceIds])] });
215
260
  }),
216
261
  customerEmail: (e) => h.sync(() => C.get(e) ?? null),
217
262
  createCheckoutSession: (t) => h.try({
@@ -279,21 +324,32 @@ var g = (f) => {
279
324
  reportUsage: (e) => h.sync(() => {
280
325
  v.push(e);
281
326
  }),
282
- updateSubscription: (e) => h.sync(() => (y.push(e), {
283
- plan: e.priceId ?? "mock-plan",
284
- quantity: e.quantity ?? 1,
285
- prorationMinor: 0,
286
- currency: "usd",
287
- currentPeriodStart: null,
288
- currentPeriodEnd: null
327
+ updateSubscription: (e) => W(e.providerSubscriptionId, e.operation, h.sync(() => {
328
+ y.push(e);
329
+ let t = S.get(e.providerSubscriptionId), n = e.operation?.plan ?? e.priceId ?? x.get(e.providerSubscriptionId)?.plan ?? "mock-plan", r = e.priceId !== void 0 && t !== void 0 ? [e.priceId, ...t.priceIds.slice(1)] : t?.priceIds, i = e.meteredPriceIds === void 0 || r === void 0 ? r : [.../* @__PURE__ */ new Set([...r.filter((t) => !(e.replacesMeteredPriceIds ?? []).includes(t)), ...e.meteredPriceIds])], a = z(e.providerSubscriptionId, {
330
+ plan: n,
331
+ ...e.quantity === void 0 ? {} : { quantity: e.quantity },
332
+ ...i !== void 0 && t !== void 0 && i !== t.priceIds ? { priceIds: i } : {}
333
+ });
334
+ return {
335
+ plan: a.plan ?? n,
336
+ quantity: a.quantity,
337
+ prorationMinor: null,
338
+ currency: "usd",
339
+ currentPeriodStart: a.currentPeriodStart,
340
+ currentPeriodEnd: a.currentPeriodEnd
341
+ };
289
342
  })),
290
- previewSubscriptionChange: (e) => h.succeed({
291
- plan: e.priceId ?? "mock-plan",
292
- quantity: e.quantity ?? 1,
293
- prorationMinor: 0,
294
- currency: "usd",
295
- currentPeriodStart: null,
296
- currentPeriodEnd: null
343
+ previewSubscriptionChange: (e) => h.sync(() => {
344
+ let t = x.get(e.providerSubscriptionId);
345
+ return {
346
+ plan: e.priceId === void 0 ? t?.plan ?? "mock-plan" : f?.planForPriceId?.(e.priceId) ?? e.priceId,
347
+ quantity: e.quantity ?? t?.quantity ?? 1,
348
+ prorationMinor: 0,
349
+ currency: "usd",
350
+ currentPeriodStart: t?.currentPeriodStart ?? null,
351
+ currentPeriodEnd: t?.currentPeriodEnd ?? null
352
+ };
297
353
  }),
298
354
  listInvoiceHistory: E,
299
355
  listInvoices: (e) => E({
@@ -303,20 +359,20 @@ var g = (f) => {
303
359
  }).pipe(h.map((e) => e.invoices.map(d))),
304
360
  normalizeEvent: (e) => h.succeed(B(e) ? e : null)
305
361
  };
306
- }, _ = /* @__PURE__ */ new Set([
362
+ }, v = /* @__PURE__ */ new Set([
307
363
  "",
308
364
  "development",
309
365
  "dev",
310
366
  "test"
311
- ]), v = (e) => !_.has((e ?? "").trim().toLowerCase()), y = (e) => {
312
- if (v(e.env.NODE_ENV)) {
313
- if (e.resolvedName === "mock" && e.providerOption === void 0) throw Error("billingPlugin: no STRIPE_SECRET_KEY in a production boot — refusing to run the MOCK billing provider, which answers every charge and subscription call successfully and reaches nobody. Set STRIPE_SECRET_KEY, or declare `billingPlugin({ provider: 'mock' })` if this deployment does not sell.");
367
+ ]), y = (e) => !v.has((e ?? "").trim().toLowerCase()), b = (e) => {
368
+ if (y(e.env.NODE_ENV)) {
369
+ if (e.resolvedName === "mock" && e.providerOption === void 0) throw g("billingPlugin: no STRIPE_SECRET_KEY in a production boot — refusing to run the MOCK billing provider, which answers every charge and subscription call successfully and reaches nobody. Set STRIPE_SECRET_KEY, or declare `billingPlugin({ provider: 'mock' })` if this deployment does not sell.");
314
370
  if (e.resolvedName === "stripe") {
315
- if (e.webhookSecret === null || e.webhookSecret.trim() === "") throw Error("billingPlugin: Stripe in a production boot needs STRIPE_WEBHOOK_SECRET — without it no provider event can be verified, so subscriptions, cancellations and payments would never reach this app.");
316
- if (e.redirectOrigins === void 0 || e.redirectOrigins.length === 0) throw Error("billingPlugin: Stripe in a production boot needs `redirectOrigins` — the origins checkout and the customer portal may send a customer back to. Without it any URL a caller names is accepted.");
371
+ if (e.webhookSecret === null || e.webhookSecret.trim() === "") throw g("billingPlugin: Stripe in a production boot needs STRIPE_WEBHOOK_SECRET — without it no provider event can be verified, so subscriptions, cancellations and payments would never reach this app.");
372
+ if (e.redirectOrigins === void 0 || e.redirectOrigins.length === 0) throw g("billingPlugin: Stripe in a production boot needs `redirectOrigins` — the origins checkout and the customer portal may send a customer back to. Without it any URL a caller names is accepted.");
317
373
  }
318
374
  }
319
- }, b = (e) => {
375
+ }, x = (e) => {
320
376
  let { provider: t, env: n } = e;
321
377
  if (t !== void 0 && typeof t == "object") return t;
322
378
  if ((t ?? (n.STRIPE_SECRET_KEY ? "stripe" : "mock")) === "stripe") {
@@ -324,14 +380,15 @@ var g = (f) => {
324
380
  if (!t) throw Error("billingPlugin: provider 'stripe' needs an apiKey (option or STRIPE_SECRET_KEY env)");
325
381
  return m({
326
382
  apiKey: t,
327
- ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {}
383
+ ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {},
384
+ ...e.seatPricingForPriceId ? { seatPricingForPriceId: e.seatPricingForPriceId } : {}
328
385
  });
329
386
  }
330
- return g();
331
- }, x = (e) => e.name === "mock" ? [] : [{
387
+ return _({ ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {} });
388
+ }, S = (e) => e.name === "mock" ? [] : [{
332
389
  destination: e.name === "stripe" ? "api.stripe.com" : `runtime:the '${e.name}' billing provider`,
333
390
  purpose: "customers, subscriptions, checkout and metered usage",
334
391
  data: ["personal", "metadata"],
335
392
  disable: "without STRIPE_SECRET_KEY the mock provider answers, and nothing leaves (production refuses to boot on it)"
336
393
  }];
337
- export { f as STRIPE_WEBHOOK_EVENTS, y as assertBillingProductionReady, x as billingEgressOf, v as isProductionBoot, g as mockProvider, p as normalizeStripeEvent, b as resolveProvider, m as stripeProvider };
394
+ export { f as STRIPE_WEBHOOK_EVENTS, b as assertBillingProductionReady, S as billingEgressOf, y as isProductionBoot, _ as mockProvider, p as normalizeStripeEvent, x as resolveProvider, m as stripeProvider };
package/dist/provision.js CHANGED
@@ -1,81 +1,92 @@
1
- import { diffMeter as e, diffPortal as t, diffPrice as n, diffProduct as r, diffTaxSettings as i, diffWebhook as a, sellingReadiness as o } from "./catalog.js";
2
- import { redactStripeKeys as s, stripeRest as c } from "./stripeRest.js";
3
- import { execFileSync as l } from "node:child_process";
4
- import { chmodSync as u, existsSync as d, readFileSync as f, realpathSync as p, writeFileSync as m } from "node:fs";
5
- import { dirname as h, resolve as g } from "node:path";
1
+ import { diffMeter as e, diffPortal as t, diffPrice as n, diffProduct as r, diffRetiredMeter as i, diffRetiredPrice as a, diffRetiredProduct as o, diffTaxSettings as s, diffWebhook as c, retiredConflicts as l, sellingReadiness as u } from "./catalog.js";
2
+ import { redactStripeKeys as d, stripeRest as f } from "./stripeRest.js";
3
+ import { execFileSync as p } from "node:child_process";
4
+ import { chmodSync as m, existsSync as h, readFileSync as g, realpathSync as _, writeFileSync as v } from "node:fs";
5
+ import { dirname as y, resolve as b } from "node:path";
6
6
  // src/provision.ts
7
- var _ = (e) => e.filter((e) => e.applied !== !0 && (e.kind === "create" || e.kind === "update" || e.kind === "adopt" || e.kind === "drift")), v = async (s, c, l) => {
8
- let u = c.environments[l.env], d = await s.get("/v1/tax/settings"), f = l.env === "live";
9
- if (d.livemode !== f) throw Error(`the key reaches a ${d.livemode ? "LIVE" : "test"} account, not ${l.env}`);
10
- let p = [], m = {}, h = async (e, t) => {
7
+ var x = (e) => e.filter((e) => e.applied !== !0 && (e.kind === "create" || e.kind === "update" || e.kind === "adopt" || e.kind === "drift")), S = async (d, f, p) => {
8
+ let m = f.environments[p.env], h = l(f);
9
+ if (h.length > 0) throw Error(`the catalog both sells and retires: ${h.join(", ")}`);
10
+ let g = await d.get("/v1/tax/settings"), _ = p.env === "live";
11
+ if (g.livemode !== _) throw Error(`the key reaches a ${g.livemode ? "LIVE" : "test"} account, not ${p.env}`);
12
+ let v = [], y = {}, b = async (e, t) => {
11
13
  let n = "apply" in e ? e.apply : void 0;
12
- if (l.apply && n !== void 0) {
13
- let r = await s.post(n.path, n.params);
14
- t?.(r), p.push({
14
+ if (p.apply && n !== void 0) {
15
+ let r = await d.post(n.path, n.params);
16
+ t?.(r), v.push({
15
17
  ...e,
16
18
  applied: !0
17
19
  });
18
- } else p.push(e);
19
- }, g = await s.list("/v1/billing/meters"), _ = /* @__PURE__ */ new Map();
20
- for (let t of c.meters) {
21
- let n = e(t, g);
22
- _.set(t.eventName, n.id), await h(n.finding, (e) => {
23
- _.set(t.eventName, e.id);
20
+ } else v.push(e);
21
+ }, x = await d.list("/v1/billing/meters"), S = /* @__PURE__ */ new Map();
22
+ for (let t of f.meters) {
23
+ let n = e(t, x);
24
+ S.set(t.eventName, n.id), await b(n.finding, (e) => {
25
+ S.set(t.eventName, e.id);
24
26
  });
25
27
  }
26
- let v = await s.list("/v1/products"), y = [];
27
- for (let e of c.products) {
28
- let t = r(e, v), n = {
29
- inPortal: e.inPortal,
28
+ let C = await d.list("/v1/products"), w = [];
29
+ for (let e of f.products) {
30
+ let t = r(e, C), n = {
30
31
  productId: t.id,
31
32
  priceId: null
32
33
  };
33
- await h(t.finding, (e) => {
34
+ await b(t.finding, (e) => {
34
35
  n.productId = e.id;
35
- }), y.push(n);
36
+ }), w.push(n);
36
37
  }
37
- for (let [e, t] of c.products.entries()) {
38
- let r = y[e], i = t.price.meter;
39
- if (t.price.usageType === "metered" && (i === void 0 || !_.has(i))) {
40
- p.push({
38
+ for (let [e, t] of f.products.entries()) {
39
+ let r = w[e], i = t.price.meter;
40
+ if (t.price.usageType === "metered" && (i === void 0 || !S.has(i))) {
41
+ v.push({
41
42
  kind: "manual",
42
43
  object: `price ${t.price.lookupKey}`,
43
44
  detail: `metered, but names no catalog meter (${i ?? "none"})`
44
45
  });
45
46
  continue;
46
47
  }
47
- let a = i === void 0 ? null : _.get(i) ?? null, o = r.productId ?? (l.apply ? null : `pending:${t.key}`), c = a ?? (l.apply || t.price.usageType !== "metered" ? a : `pending:${i}`), u = (await s.list("/v1/prices", { lookup_keys: [t.price.lookupKey] }))[0] ?? null, d = r.productId === null ? [] : await s.list("/v1/prices", { product: r.productId }), f = n(t.price, o, c, u, d, l.allowPriceChange);
48
- r.priceId = f.id, await h(f.finding, (e) => {
48
+ let a = i === void 0 ? null : S.get(i) ?? null, o = r.productId ?? (p.apply ? null : `pending:${t.key}`), s = a ?? (p.apply || t.price.usageType !== "metered" ? a : `pending:${i}`), c = (await d.list("/v1/prices", {
49
+ lookup_keys: [t.price.lookupKey],
50
+ expand: ["data.tiers"]
51
+ }))[0] ?? null, l = r.productId === null ? [] : await d.list("/v1/prices", {
52
+ product: r.productId,
53
+ expand: ["data.tiers"]
54
+ }), u = n(t.price, o, s, c, l, p.allowPriceChange);
55
+ r.priceId = u.id, await b(u.finding, (e) => {
49
56
  r.priceId = e.id;
50
- }), r.priceId !== null && (m[t.price.envName] = r.priceId);
57
+ }), r.priceId !== null && (y[t.price.envName] = r.priceId);
51
58
  }
52
- await h(i(c.tax, d));
53
- let b = y.filter((e) => e.inPortal), x = b.every((e) => e.productId !== null && e.priceId !== null) ? b.map((e) => ({
54
- productId: e.productId,
55
- priceId: e.priceId
56
- })) : null, S = await s.list("/v1/billing_portal/configurations", { expand: ["data.features.subscription_update.products"] });
57
- for (let e of t(c.portal, u, x, S)) await h(e);
58
- let C = a(u, await s.list("/v1/webhook_endpoints"));
59
- C.kind === "create" && l.apply && l.envOut === null ? p.push({
59
+ let T = f.retired ?? {}, E = T.prices ?? [];
60
+ for (let e = 0; e < E.length; e += 10) {
61
+ let t = E.slice(e, e + 10), n = await d.list("/v1/prices", { lookup_keys: t });
62
+ for (let e of t) await b(a(e, n));
63
+ }
64
+ for (let e of T.products ?? []) await b(o(e, C));
65
+ for (let e of T.meters ?? []) await b(i(e, x));
66
+ await b(s(f.tax, g));
67
+ let D = await d.list("/v1/billing_portal/configurations");
68
+ for (let e of t(f.portal, m, D)) await b(e);
69
+ let O = c(m, await d.list("/v1/webhook_endpoints"));
70
+ O.kind === "create" && p.apply && p.envOut === null ? v.push({
60
71
  kind: "manual",
61
- object: C.object,
72
+ object: O.object,
62
73
  detail: "not created: pass --env-out so its signing secret is captured (Stripe shows it once)"
63
- }) : await h(C, (e) => {
64
- typeof e.secret == "string" && (m.STRIPE_WEBHOOK_SECRET = e.secret);
74
+ }) : await b(O, (e) => {
75
+ typeof e.secret == "string" && (y.STRIPE_WEBHOOK_SECRET = e.secret);
65
76
  });
66
- let w = await s.get("/v1/account").catch(() => null), T = await s.list("/v1/tax_ids", { owner: { type: "account" } }).catch(() => null), E = await s.list("/v1/tax/registrations", { status: "active" }).catch(() => []);
67
- return p.push(...o({
68
- catalog: c,
69
- env: u,
70
- chargesEnabled: w === null ? null : w.charges_enabled === !0,
71
- accountTaxIds: T === null ? null : T.length,
72
- activeRegistrations: E.map((e) => e.country)
77
+ let k = await d.get("/v1/account").catch(() => null), A = await d.list("/v1/tax_ids", { owner: { type: "account" } }).catch(() => null), j = await d.list("/v1/tax/registrations", { status: "active" }).catch(() => []);
78
+ return v.push(...u({
79
+ catalog: f,
80
+ env: m,
81
+ chargesEnabled: k === null ? null : k.charges_enabled === !0,
82
+ accountTaxIds: A === null ? null : A.length,
83
+ activeRegistrations: j.map((e) => e.country)
73
84
  })), {
74
- livemode: d.livemode,
75
- findings: p,
76
- envOut: m
85
+ livemode: g.livemode,
86
+ findings: v,
87
+ envOut: y
77
88
  };
78
- }, y = (e, t) => {
89
+ }, C = (e, t) => {
79
90
  let n = new Set(Object.keys(t)), r = e.split("\n").filter((e) => !n.has(e.split("=")[0] ?? ""));
80
91
  for (; r.length > 0 && r[r.length - 1] === "";) r.pop();
81
92
  return [
@@ -83,18 +94,18 @@ var _ = (e) => e.filter((e) => e.applied !== !0 && (e.kind === "create" || e.kin
83
94
  ...Object.entries(t).map(([e, t]) => `${e}=${t}`),
84
95
  ""
85
96
  ].join("\n");
86
- }, b = (e, t) => {
97
+ }, w = (e, t) => {
87
98
  try {
88
- return l("git", [...e], {
99
+ return p("git", [...e], {
89
100
  cwd: t,
90
101
  stdio: "ignore"
91
102
  }), !0;
92
103
  } catch {
93
104
  return !1;
94
105
  }
95
- }, x = (e, t = b, n = (e) => d(e) ? p(e) : e) => {
96
- for (let r of /* @__PURE__ */ new Set([g(e), g(n(g(e)))])) {
97
- let n = h(r);
106
+ }, T = (e, t = w, n = (e) => h(e) ? _(e) : e) => {
107
+ for (let r of /* @__PURE__ */ new Set([b(e), b(n(b(e)))])) {
108
+ let n = y(r);
98
109
  if (t(["rev-parse", "--is-inside-work-tree"], n) && !t([
99
110
  "check-ignore",
100
111
  "-q",
@@ -102,7 +113,7 @@ var _ = (e) => e.filter((e) => e.applied !== !0 && (e.kind === "create" || e.kin
102
113
  ], n)) return `${e} is inside a git work tree and not ignored — write it to a gitignored file or outside the repo`;
103
114
  }
104
115
  return null;
105
- }, S = (e) => {
116
+ }, E = (e) => {
106
117
  let t = (t) => {
107
118
  let n = e.indexOf(t);
108
119
  return n < 0 ? null : e[n + 1];
@@ -119,34 +130,34 @@ var _ = (e) => e.filter((e) => e.applied !== !0 && (e.kind === "create" || e.kin
119
130
  envOut: r
120
131
  };
121
132
  return i.env === "live" && i.apply && !i.confirmLive ? "writing to LIVE needs --confirm-live (run without --apply first to see the plan)" : i;
122
- }, C = (e, t, n) => {
133
+ }, D = (e, t, n) => {
123
134
  let r = t.STRIPE_PROVISION_KEY?.trim() || (e === "sandbox" ? n?.trim() : void 0);
124
135
  return r === void 0 || r.length === 0 ? { refusal: "set STRIPE_PROVISION_KEY (a sandbox run also reads STRIPE_SECRET_KEY from the dotenv file)" } : e === "live" && !/^(sk|rk)_live_/.test(r) ? { refusal: "--env live needs a live key (sk_live_/rk_live_)" } : e === "sandbox" && !/^(sk|rk)_test_/.test(r) ? { refusal: "--env sandbox needs a test key (sk_test_/rk_test_)" } : { key: r };
125
- }, w = (e, t) => d(e) ? f(e, "utf8").split("\n").find((e) => e.startsWith(`${t}=`))?.slice(t.length + 1).trim() : void 0, T = async (e, t, n = {}) => {
126
- let r = n.vars ?? process.env, i = (e) => (console.error(`stripe provision: ${e}`), 2), a = S(t);
136
+ }, O = (e, t) => h(e) ? g(e, "utf8").split("\n").find((e) => e.startsWith(`${t}=`))?.slice(t.length + 1).trim() : void 0, k = async (e, t, n = {}) => {
137
+ let r = n.vars ?? process.env, i = (e) => (console.error(`stripe provision: ${e}`), 2), a = E(t);
127
138
  if (typeof a == "string") return i(a);
128
139
  if (a.envOut !== null) {
129
- let e = x(a.envOut);
140
+ let e = T(a.envOut);
130
141
  if (e !== null) return i(e);
131
142
  }
132
- let o = C(a.env, r, n.dotenv === void 0 ? void 0 : w(n.dotenv, "STRIPE_SECRET_KEY"));
143
+ let o = D(a.env, r, n.dotenv === void 0 ? void 0 : O(n.dotenv, "STRIPE_SECRET_KEY"));
133
144
  if ("refusal" in o) return i(o.refusal);
134
- let l;
145
+ let s;
135
146
  try {
136
- l = await v((n.rest ?? c)(o.key), e, a);
147
+ s = await S((n.rest ?? f)(o.key), e, a);
137
148
  } catch (e) {
138
- return console.error(`stripe provision: ${s(e instanceof Error ? e.message : String(e))}`), 1;
149
+ return console.error(`stripe provision: ${d(e instanceof Error ? e.message : String(e))}`), 1;
139
150
  }
140
- console.log(`Stripe ${a.env} (${l.livemode ? "LIVE" : "test mode"}) — ${a.apply ? "apply" : "check"}`);
141
- for (let e of l.findings) {
151
+ console.log(`Stripe ${a.env} (${s.livemode ? "LIVE" : "test mode"}) — ${a.apply ? "apply" : "check"}`);
152
+ for (let e of s.findings) {
142
153
  let t = e.applied === !0 ? `${e.kind} ✓` : e.kind;
143
154
  console.log(` ${t.padEnd(10)} ${e.object}${"detail" in e ? ` — ${e.detail}` : ""}`);
144
155
  }
145
156
  if (a.envOut !== null) {
146
157
  let e = a.envOut;
147
- m(e, y(d(e) ? f(e, "utf8") : "", l.envOut), { mode: 384 }), u(e, 384), console.log(` wrote ${Object.keys(l.envOut).sort().join(", ")} to ${e}`);
158
+ v(e, C(h(e) ? g(e, "utf8") : "", s.envOut), { mode: 384 }), m(e, 384), console.log(` wrote ${Object.keys(s.envOut).sort().join(", ")} to ${e}`);
148
159
  }
149
- let p = _(l.findings), h = l.findings.filter((e) => e.kind === "manual");
150
- return console.log(` ${p.length} open, ${h.length} manual`), p.length > 0 || a.strict && h.length > 0 ? 1 : 0;
160
+ let c = x(s.findings), l = s.findings.filter((e) => e.kind === "manual");
161
+ return console.log(` ${c.length} open, ${l.length} manual`), c.length > 0 || a.strict && l.length > 0 ? 1 : 0;
151
162
  };
152
- export { x as envOutRefusal, y as mergeEnvFile, _ as openFindings, S as parseProvisionArgs, v as provisionStripeCatalog, C as resolveProvisionKey, T as runStripeProvision };
163
+ export { T as envOutRefusal, C as mergeEnvFile, x as openFindings, E as parseProvisionArgs, S as provisionStripeCatalog, D as resolveProvisionKey, k as runStripeProvision };