@tofound/billing 0.1.0 → 0.2.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 (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +58 -13
  3. package/dist/catalog/catalog.d.ts +115 -0
  4. package/dist/catalog/catalog.js +201 -0
  5. package/dist/domain/types.d.ts +3 -1
  6. package/dist/drizzle/index.d.ts +2 -0
  7. package/dist/drizzle/index.js +2 -0
  8. package/dist/entitlement/resolve.d.ts +76 -0
  9. package/dist/entitlement/resolve.js +122 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +9 -0
  12. package/dist/providers/polar/events.d.ts +17 -0
  13. package/dist/providers/polar/events.js +213 -0
  14. package/dist/providers/polar/index.d.ts +50 -0
  15. package/dist/providers/polar/index.js +271 -0
  16. package/dist/providers/polar/signature.d.ts +23 -0
  17. package/dist/providers/polar/signature.js +52 -0
  18. package/dist/providers/port.d.ts +6 -0
  19. package/dist/renewal/renewal.d.ts +69 -0
  20. package/dist/renewal/renewal.js +198 -0
  21. package/dist/stores/testing.d.ts +4 -2
  22. package/dist/stores/testing.js +4 -2
  23. package/dist/terms/conformance.d.ts +17 -0
  24. package/dist/terms/conformance.js +198 -0
  25. package/dist/terms/decide.d.ts +97 -0
  26. package/dist/terms/decide.js +176 -0
  27. package/dist/terms/drizzle.d.ts +12 -0
  28. package/dist/terms/drizzle.js +131 -0
  29. package/dist/terms/memory.d.ts +23 -0
  30. package/dist/terms/memory.js +126 -0
  31. package/dist/terms/plans.d.ts +85 -0
  32. package/dist/terms/plans.js +331 -0
  33. package/dist/terms/ports.d.ts +55 -0
  34. package/dist/terms/ports.js +1 -0
  35. package/dist/terms/rules.d.ts +11 -0
  36. package/dist/terms/rules.js +36 -0
  37. package/dist/terms/schema.d.ts +711 -0
  38. package/dist/terms/schema.js +70 -0
  39. package/dist/terms/snapshot.d.ts +20 -0
  40. package/dist/terms/snapshot.js +134 -0
  41. package/dist/terms/types.d.ts +85 -0
  42. package/dist/terms/types.js +4 -0
  43. package/docs/API.md +223 -4
  44. package/docs/SCHEMA.md +57 -2
  45. package/package.json +6 -1
@@ -0,0 +1,122 @@
1
+ import { addDays } from '../terms/rules.js';
2
+ /**
3
+ * Until when a term entitles its account, or `null` when it does not at `now`.
4
+ *
5
+ * - `active` before its period end. An auto-renewing term past its end is
6
+ * still entitled for `graceDays` while the renewal (job or provider
7
+ * webhook) catches up — the renewal itself decides past_due.
8
+ * - `grace` until `graceUntil` (the period end when the provider sent none).
9
+ * - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
10
+ * AC15); a provider `past_due` without one is not entitled (§4.6).
11
+ * - `scheduled` once `startsAt` passed and before its period end, in case
12
+ * activation has not run yet.
13
+ */
14
+ export function entitledUntil(term, now, graceDays) {
15
+ const at = now.getTime();
16
+ const before = (d) => (d !== null && at < d.getTime() ? d : null);
17
+ switch (term.status) {
18
+ case 'active': {
19
+ if (at < term.startsAt.getTime())
20
+ return null;
21
+ if (at < term.currentPeriodEnd.getTime())
22
+ return term.currentPeriodEnd;
23
+ return term.autoRenew && !term.cancelAtPeriodEnd ? before(addDays(term.currentPeriodEnd, graceDays)) : null;
24
+ }
25
+ case 'grace':
26
+ return before(term.graceUntil ?? term.currentPeriodEnd);
27
+ case 'past_due':
28
+ return before(term.graceUntil);
29
+ case 'scheduled':
30
+ return at >= term.startsAt.getTime() ? before(term.currentPeriodEnd) : null;
31
+ default:
32
+ return null;
33
+ }
34
+ }
35
+ export function isEntitled(term, now, graceDays) {
36
+ return entitledUntil(term, now, graceDays) !== null;
37
+ }
38
+ const renews = (t) => t.autoRenew && !t.cancelAtPeriodEnd;
39
+ /**
40
+ * Resolve the account's entitlement (S1: highest rank wins, then the later
41
+ * end, then the older term; quotas and permissions never sum). Terms naming a
42
+ * plan the catalog no longer has are ignored. No entitled term → the free plan.
43
+ */
44
+ export function resolveEntitlement(terms, now, catalog, options = {}) {
45
+ const graceDays = catalog.policies.graceDays;
46
+ const entitled = terms
47
+ .map((term) => ({ term, plan: catalog.findPlan(term.planKey), until: entitledUntil(term, now, graceDays) }))
48
+ .filter((c) => c.plan !== undefined && c.until !== null)
49
+ .sort((a, b) => b.plan.rank - a.plan.rank ||
50
+ b.term.currentPeriodEnd.getTime() - a.term.currentPeriodEnd.getTime() ||
51
+ a.term.createdAt.getTime() - b.term.createdAt.getTime() ||
52
+ (a.term.id < b.term.id ? -1 : 1));
53
+ const warnings = [];
54
+ const billing = entitled.filter((c) => c.term.source !== 'credit' && renews(c.term));
55
+ if (billing.length > 1)
56
+ warnings.push({ code: 'two_subscriptions', termIds: billing.map((c) => c.term.id) });
57
+ const winner = entitled[0];
58
+ if (!winner) {
59
+ const free = catalog.freePlan;
60
+ return {
61
+ plan: free.key,
62
+ rank: free.rank,
63
+ permissions: free.permissions,
64
+ quotas: free.quotas,
65
+ includedCredits: null,
66
+ term: null,
67
+ source: null,
68
+ status: 'free',
69
+ endsAt: null,
70
+ graceUntil: null,
71
+ renewal: null,
72
+ warnings,
73
+ };
74
+ }
75
+ const { term, plan } = winner;
76
+ const inGrace = term.status === 'grace' || term.status === 'past_due';
77
+ if (term.status === 'past_due')
78
+ warnings.push({ code: 'past_due', termIds: [term.id] });
79
+ const scheduled = terms.find((t) => t.status === 'scheduled' && t.accountId === term.accountId && t.id !== term.id);
80
+ const downgradeTo = term.nextPlanKey ?? scheduled?.planKey ?? null;
81
+ const downgradeRank = downgradeTo ? catalog.findPlan(downgradeTo)?.rank : undefined;
82
+ if (downgradeRank !== undefined && downgradeRank < plan.rank) {
83
+ warnings.push({ code: 'scheduled_downgrade', termIds: [term.nextPlanKey ? term.id : scheduled.id] });
84
+ }
85
+ const renewal = renewalOf(term, catalog, options);
86
+ if (term.source === 'credit' &&
87
+ renewal?.auto &&
88
+ renewal.price &&
89
+ options.balance !== undefined &&
90
+ options.balance < renewal.price.amountMinor) {
91
+ warnings.push({ code: 'renewal_shortfall', termIds: [term.id] });
92
+ }
93
+ return {
94
+ plan: plan.key,
95
+ rank: plan.rank,
96
+ permissions: plan.permissions,
97
+ quotas: plan.quotas,
98
+ includedCredits: term.source === 'credit' ? null : plan.includedCredits,
99
+ term,
100
+ source: term.source,
101
+ status: inGrace ? 'grace' : 'active',
102
+ endsAt: term.currentPeriodEnd,
103
+ graceUntil: inGrace ? (term.graceUntil ?? null) : null,
104
+ renewal,
105
+ warnings,
106
+ };
107
+ }
108
+ function renewalOf(term, catalog, options) {
109
+ const plan = term.nextPlanKey ?? term.planKey;
110
+ if (term.source !== 'credit') {
111
+ const price = term.priceMinor !== null && term.priceUnit ? { amountMinor: term.priceMinor, unit: term.priceUnit } : null;
112
+ return { auto: renews(term), at: term.currentPeriodEnd, plan, price };
113
+ }
114
+ const market = options.market ?? term.market;
115
+ const offer = market ? catalog.creditOffer(plan, market, term.intervalMonths) : undefined;
116
+ return {
117
+ auto: renews(term),
118
+ at: term.currentPeriodEnd,
119
+ plan,
120
+ price: offer ? { amountMinor: offer.credits, unit: catalog.creditUnit.code } : null,
121
+ };
122
+ }
package/dist/index.d.ts CHANGED
@@ -18,3 +18,13 @@ export { FINAL_INBOX_STATUSES, type CheckoutSession, type CheckoutSessionPatch,
18
18
  export { createMemoryIngestStore, type MemoryIngestStore } from './inbox/memory.js';
19
19
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
20
20
  export { isNewer, type Watermark } from './inbox/watermark.js';
21
+ export { DEFAULT_POLICIES, defineCatalog, type Catalog, type CatalogPolicies, type CatalogSpec, type CreditOffer, type CreditPack, type CreditPackSpec, type MarketSpec, type PackProvider, type Plan, type PlanOffer, type PlanSpec, type ProductMatch, type ProviderOffer, type ReversalShortfallPolicy, type UpgradeProration, } from './catalog/catalog.js';
22
+ export * from './terms/types.js';
23
+ export type { TermListOptions, TermReader, TermStore, TermTx } from './terms/ports.js';
24
+ export { addDays, addTermMonths, isRenewalDue, renewalDueAt, renews } from './terms/rules.js';
25
+ export { createMemoryTermStore, type MemoryTermStore, type MemoryTransactor } from './terms/memory.js';
26
+ export { decidePlanPurchase, itemsOf, supersedeRefund, type PlanDecision, type PlanQuoteKind, type PlanRequest, type TermEffect, } from './terms/decide.js';
27
+ export { createPlans, type PlanOps, type PlanPurchaseInput, type PlanPurchaseResult, type PlanQuote, type Plans, type PlansEvent, type PlansEventSink, type PlansOptions, type TermUpdateResult, } from './terms/plans.js';
28
+ export { createSnapshotHandler, type SnapshotHandlerOptions } from './terms/snapshot.js';
29
+ export { entitledUntil, isEntitled, resolveEntitlement, type Entitlement, type EntitlementRenewal, type EntitlementStatus, type EntitlementWarning, type EntitlementWarningCode, type ResolveOptions, } from './entitlement/resolve.js';
30
+ export { createRenewal, type RenewalEvent, type RenewalOps, type RenewalOptions, type RenewalOutcome, type RenewalResult, type RenewalRun, type RenewalService, } from './renewal/renewal.js';
package/dist/index.js CHANGED
@@ -16,3 +16,12 @@ export { FINAL_INBOX_STATUSES, } from './inbox/ports.js';
16
16
  export { createMemoryIngestStore } from './inbox/memory.js';
17
17
  export { isSensitiveKey, redactPayload } from './inbox/redact.js';
18
18
  export { isNewer } from './inbox/watermark.js';
19
+ export { DEFAULT_POLICIES, defineCatalog, } from './catalog/catalog.js';
20
+ export * from './terms/types.js';
21
+ export { addDays, addTermMonths, isRenewalDue, renewalDueAt, renews } from './terms/rules.js';
22
+ export { createMemoryTermStore } from './terms/memory.js';
23
+ export { decidePlanPurchase, itemsOf, supersedeRefund, } from './terms/decide.js';
24
+ export { createPlans, } from './terms/plans.js';
25
+ export { createSnapshotHandler } from './terms/snapshot.js';
26
+ export { entitledUntil, isEntitled, resolveEntitlement, } from './entitlement/resolve.js';
27
+ export { createRenewal, } from './renewal/renewal.js';
@@ -0,0 +1,17 @@
1
+ import type { NormalizedEvent } from '../port.js';
2
+ export interface PolarEnvelope {
3
+ type: string;
4
+ timestamp?: unknown;
5
+ data: Record<string, unknown>;
6
+ }
7
+ export interface NormalizeOptions {
8
+ /** Polar product id → catalog productRef. */
9
+ products: Readonly<Record<string, string>>;
10
+ /** Our checkout session ids, as carried in `metadata.checkout_id`. */
11
+ checkoutPattern: RegExp;
12
+ }
13
+ /** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
14
+ export declare function occurredAtOf(envelope: PolarEnvelope, fallback: Date): Date;
15
+ /** The server-issued external customer id (design §4.1). */
16
+ export declare function externalCustomerOf(data: Record<string, unknown>): string | null;
17
+ export declare function normalizePolarEvent(envelope: PolarEnvelope, occurredAt: Date, options: NormalizeOptions): NormalizedEvent;
@@ -0,0 +1,213 @@
1
+ const rec = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : null;
2
+ const str = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
3
+ /** A non-negative safe-integer minor amount from a number or digit string. */
4
+ function minor(value) {
5
+ const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN;
6
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
7
+ }
8
+ function date(value) {
9
+ const raw = str(value);
10
+ if (!raw)
11
+ return null;
12
+ const parsed = new Date(raw);
13
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
14
+ }
15
+ /** Payload values are keys here: never let `constructor` or `__proto__` resolve an inherited member. */
16
+ const own = (map, key) => (Object.hasOwn(map, key) ? map[key] : undefined);
17
+ const CURRENCIES = { USD: 'USD', VND: 'VND' };
18
+ /** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
19
+ export function occurredAtOf(envelope, fallback) {
20
+ const { data } = envelope;
21
+ return date(data['modified_at']) ?? date(data['created_at']) ?? date(envelope.timestamp) ?? fallback;
22
+ }
23
+ /** The server-issued external customer id (design §4.1). */
24
+ export function externalCustomerOf(data) {
25
+ return str(rec(data['customer'])?.['external_id']) ?? str(data['external_customer_id']);
26
+ }
27
+ const productIdOf = (data) => str(rec(data['product'])?.['id']) ?? str(data['product_id']);
28
+ function checkoutRefOf(data, options) {
29
+ const ref = str(rec(data['metadata'])?.['checkout_id']);
30
+ return ref && options.checkoutPattern.test(ref) ? ref : null;
31
+ }
32
+ function moneyOf(currencyRaw, amountMinor, rawAmount) {
33
+ const currency = own(CURRENCIES, (str(currencyRaw) ?? '').toUpperCase());
34
+ if (!currency)
35
+ return { ok: false, event: { kind: 'needs_review', reason: 'invalid_currency', detail: { currency: currencyRaw ?? null } } };
36
+ if (amountMinor === null)
37
+ return { ok: false, event: { kind: 'needs_review', reason: 'invalid_amount', detail: { amount: rawAmount ?? null } } };
38
+ return { ok: true, money: { currency, amountMinor } };
39
+ }
40
+ /**
41
+ * What the merchant charged for the product: the price the catalog defines,
42
+ * after discounts, before tax — `subtotal_amount − discount_amount`, the one
43
+ * basis that reads the same whatever the tax behaviour. `net_amount` and
44
+ * `total_amount` move with it: a tax-inclusive order of a 500 pack has
45
+ * `net_amount` 420 and `tax_amount` 80, a tax-exclusive one `total_amount`
46
+ * 540. A discounted or re-priced order still fails the inbox's exact-amount
47
+ * guard instead of crediting a full pack.
48
+ */
49
+ function orderAmount(data) {
50
+ const subtotal = minor(data['subtotal_amount']);
51
+ const discount = data['discount_amount'] == null ? 0 : minor(data['discount_amount']);
52
+ // An unreadable discount must not fall through to the gross amount.
53
+ const amount = subtotal !== null && discount !== null && subtotal >= discount ? subtotal - discount : null;
54
+ return moneyOf(data['currency'], amount, data['subtotal_amount']);
55
+ }
56
+ const isSubscriptionOrder = (data) => {
57
+ const reason = str(data['billing_reason']);
58
+ return str(data['subscription_id']) !== null || (reason !== null && reason !== 'purchase');
59
+ };
60
+ function orderEvent(envelope, occurredAt, options) {
61
+ const { type, data } = envelope;
62
+ if (type === 'order.created' || type === 'order.updated')
63
+ return { kind: 'ignored', reason: 'no_money_moved' };
64
+ if (type !== 'order.paid' && type !== 'order.refunded')
65
+ return { kind: 'ignored', reason: `unhandled_type:${type}` };
66
+ if (isSubscriptionOrder(data)) {
67
+ // Receipts of a subscription; access comes and goes with `subscription.*`.
68
+ return { kind: 'ignored', reason: type === 'order.paid' ? 'subscription_order' : 'subscription_order_refund' };
69
+ }
70
+ const orderId = str(data['id']);
71
+ if (!orderId)
72
+ return { kind: 'needs_review', reason: 'missing_order_id' };
73
+ const amount = orderAmount(data);
74
+ if (!amount.ok)
75
+ return amount.event;
76
+ const checkoutRef = checkoutRefOf(data, options);
77
+ if (type === 'order.refunded') {
78
+ const status = str(data['status']);
79
+ if (status !== 'refunded') {
80
+ // `refunded_amount` is a running total; a partial refund against a pack
81
+ // has no agreed credit amount to take back.
82
+ return {
83
+ kind: 'needs_review',
84
+ reason: status === 'partially_refunded' ? 'partial_refund' : `refund_status:${status ?? 'none'}`,
85
+ detail: { refundedAmount: data['refunded_amount'] ?? null },
86
+ };
87
+ }
88
+ return {
89
+ kind: 'purchase.reversed',
90
+ externalId: orderId,
91
+ reason: 'refund',
92
+ ...(checkoutRef ? { checkoutRef } : {}),
93
+ amount: amount.money,
94
+ occurredAt,
95
+ };
96
+ }
97
+ const customer = externalCustomerOf(data);
98
+ const account = customer
99
+ ? { kind: 'polar_customer_external_id', value: customer }
100
+ : checkoutRef
101
+ ? { kind: 'checkout', value: checkoutRef }
102
+ : null;
103
+ if (!account)
104
+ return { kind: 'needs_review', reason: 'unbound_order' };
105
+ const productId = productIdOf(data);
106
+ return {
107
+ kind: 'purchase.completed',
108
+ account,
109
+ externalId: orderId,
110
+ productRef: (productId && own(options.products, productId)) ?? null,
111
+ quantity: 1,
112
+ amount: amount.money,
113
+ ...(checkoutRef ? { checkoutRef } : {}),
114
+ occurredAt,
115
+ };
116
+ }
117
+ /**
118
+ * Same-instant precedence, lowest first: the later a type stands here, the
119
+ * more it says about the one change they share (a revoke outranks the
120
+ * `updated` that carries the same state). Unknown types rank lowest.
121
+ */
122
+ const TIE_ORDER = [
123
+ 'subscription.created',
124
+ 'subscription.updated',
125
+ 'subscription.active',
126
+ 'subscription.past_due',
127
+ 'subscription.uncanceled',
128
+ 'subscription.canceled',
129
+ 'subscription.paused',
130
+ 'subscription.revoked',
131
+ ];
132
+ const GRANTING = new Set(['active', 'trialing']);
133
+ const DUNNING = new Set(['past_due', 'unpaid']);
134
+ function subscriptionEvent(envelope, occurredAt, options) {
135
+ const { type, data } = envelope;
136
+ const customer = externalCustomerOf(data);
137
+ if (!customer)
138
+ return { kind: 'ignored', reason: 'no_external_customer' };
139
+ const externalId = str(data['id']);
140
+ if (!externalId)
141
+ return { kind: 'needs_review', reason: 'missing_subscription_id' };
142
+ const productId = productIdOf(data);
143
+ const planRef = productId ? own(options.products, productId) : undefined;
144
+ if (!planRef)
145
+ return { kind: 'ignored', reason: 'unknown_product' };
146
+ const providerStatus = str(data['status'])?.toLowerCase() ?? null;
147
+ const endedAt = date(data['ended_at']);
148
+ let status;
149
+ if (type === 'subscription.revoked' || type === 'subscription.paused' || providerStatus === 'paused')
150
+ status = 'revoked';
151
+ else if (!providerStatus)
152
+ return { kind: 'ignored', reason: 'missing_status' };
153
+ else if (GRANTING.has(providerStatus))
154
+ status = 'active';
155
+ else if (DUNNING.has(providerStatus))
156
+ status = 'past_due';
157
+ else if (providerStatus === 'canceled')
158
+ status = endedAt && endedAt.getTime() <= occurredAt.getTime() ? 'expired' : 'active';
159
+ else
160
+ return { kind: 'ignored', reason: `unhandled_status:${providerStatus}` };
161
+ // A revocation ends access whatever the payload says about periods.
162
+ const revokedAt = status === 'revoked' ? occurredAt : null;
163
+ const periodStart = date(data['current_period_start']) ?? date(data['started_at']) ?? revokedAt;
164
+ const currentEnd = date(data['current_period_end']);
165
+ // An ended subscription's period stops when it ended, not when it would have renewed.
166
+ const periodEnd = currentEnd && endedAt ? (endedAt < currentEnd ? endedAt : currentEnd) : (currentEnd ?? endedAt ?? revokedAt);
167
+ if (!periodStart || !periodEnd)
168
+ return { kind: 'needs_review', reason: 'missing_period' };
169
+ const cancelAtPeriodEnd = type !== 'subscription.uncanceled' &&
170
+ (type === 'subscription.canceled' || providerStatus === 'canceled' || data['cancel_at_period_end'] === true);
171
+ const live = status === 'active' || status === 'past_due';
172
+ let price;
173
+ if (data['amount'] != null || data['currency'] != null) {
174
+ const amount = moneyOf(data['currency'], minor(data['amount']), data['amount']);
175
+ if (!amount.ok)
176
+ return amount.event;
177
+ price = amount.money;
178
+ }
179
+ return {
180
+ kind: 'subscription.snapshot',
181
+ account: { kind: 'polar_customer_external_id', value: customer },
182
+ externalId,
183
+ planRef,
184
+ status,
185
+ periodStart,
186
+ periodEnd,
187
+ autoRenew: live && !cancelAtPeriodEnd,
188
+ cancelAtPeriodEnd: live && cancelAtPeriodEnd,
189
+ ...(price ? { price } : {}),
190
+ occurredAt,
191
+ tieBreak: String(TIE_ORDER.indexOf(type) + 1),
192
+ };
193
+ }
194
+ function checkoutEvent(envelope, options) {
195
+ // Only sessions we created carry our id; anything else is not ours to track.
196
+ const checkoutRef = checkoutRefOf(envelope.data, options);
197
+ if (!checkoutRef)
198
+ return { kind: 'ignored', reason: 'foreign_checkout' };
199
+ const status = str(envelope.data['status']);
200
+ if (!status)
201
+ return { kind: 'ignored', reason: 'missing_status' };
202
+ return { kind: 'checkout.status', checkoutRef, status };
203
+ }
204
+ export function normalizePolarEvent(envelope, occurredAt, options) {
205
+ const { type } = envelope;
206
+ if (type.startsWith('subscription.'))
207
+ return subscriptionEvent(envelope, occurredAt, options);
208
+ if (type.startsWith('order.'))
209
+ return orderEvent(envelope, occurredAt, options);
210
+ if (type.startsWith('checkout.'))
211
+ return checkoutEvent(envelope, options);
212
+ return { kind: 'ignored', reason: `unhandled_type:${type}` };
213
+ }
@@ -0,0 +1,50 @@
1
+ import { type CheckoutCapable, type CheckoutRedirect, type CheckoutRequest, type IngestOutcome, type PortalCapable, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse } from '../port.js';
2
+ export { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, signPolarWebhook, type PolarKeyDerivation, } from './signature.js';
3
+ /**
4
+ * 2Novel's two-switch arming, made explicit: production needs both the
5
+ * requested environment and the arming flag. Unlike the host copy, an unset
6
+ * or unknown environment is refused rather than defaulted to sandbox, and an
7
+ * unarmed production refuses here instead of on the first charge.
8
+ */
9
+ export declare function resolvePolarEnvironment(input: {
10
+ environment: string | null | undefined;
11
+ productionEnabled: boolean;
12
+ }): ProviderEnvironment;
13
+ export interface PolarAdapterOptions {
14
+ /** Required. Resolve the host's switches with `resolvePolarEnvironment`. */
15
+ environment: ProviderEnvironment;
16
+ /** Accepted webhook secrets (`whsec_…`); more than one only while rotating. */
17
+ webhookSecrets: readonly string[];
18
+ /** Polar product id → catalog productRef, for this environment's products. */
19
+ products: Readonly<Record<string, string>>;
20
+ /** Organization access token; needed for checkout and portal, not for webhooks. */
21
+ accessToken?: string;
22
+ /** Our checkout session ids as carried in `metadata.checkout_id`. Default: UUID. */
23
+ checkoutPattern?: RegExp;
24
+ /** Replay window in seconds. Default 300. */
25
+ toleranceSec?: number;
26
+ /** Wall clock for the replay window. Default `new Date()`. */
27
+ clock?: () => Date;
28
+ fetch?: typeof fetch;
29
+ /** API timeout. Default 10 s. */
30
+ timeoutMs?: number;
31
+ }
32
+ /** A checkout request; Polar uses the buyer's IP for tax country when the host has it. */
33
+ export interface PolarCheckoutRequest extends CheckoutRequest {
34
+ customerIpAddress?: string | null;
35
+ }
36
+ export interface PolarAdapter extends ProviderAdapter, CheckoutCapable, PortalCapable {
37
+ readonly id: 'polar';
38
+ createCheckout(req: PolarCheckoutRequest): Promise<CheckoutRedirect>;
39
+ }
40
+ /** A Polar API call failed. Never carries the token or the response body. */
41
+ export declare class PolarApiError extends Error {
42
+ readonly name = "PolarApiError";
43
+ readonly code: 'polar_unreachable' | 'polar_error' | 'polar_bad_response' | 'polar_price_mismatch';
44
+ readonly status: number | null;
45
+ constructor(code: PolarApiError['code'], message: string, status?: number | null);
46
+ }
47
+ export declare function redactPolarPayload(payload: unknown): unknown;
48
+ export declare function createPolarAdapter(options: PolarAdapterOptions): PolarAdapter;
49
+ /** Polar retries any non-2xx; acknowledge everything a retry cannot change. */
50
+ export declare function respondPolar(outcome: IngestOutcome): ProviderResponse;