@tofound/billing 0.0.0-stage → 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 (100) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/LICENSE +3 -0
  3. package/README.md +79 -2
  4. package/dist/catalog/catalog.d.ts +115 -0
  5. package/dist/catalog/catalog.js +201 -0
  6. package/dist/domain/errors.d.ts +14 -0
  7. package/dist/domain/errors.js +21 -0
  8. package/dist/domain/money.d.ts +21 -0
  9. package/dist/domain/money.js +77 -0
  10. package/dist/domain/types.d.ts +167 -0
  11. package/dist/domain/types.js +18 -0
  12. package/dist/drizzle/index.d.ts +5 -0
  13. package/dist/drizzle/index.js +5 -0
  14. package/dist/drizzle/schema-factory.d.ts +586 -0
  15. package/dist/drizzle/schema-factory.js +206 -0
  16. package/dist/drizzle/store.d.ts +20 -0
  17. package/dist/drizzle/store.js +124 -0
  18. package/dist/entitlement/resolve.d.ts +76 -0
  19. package/dist/entitlement/resolve.js +122 -0
  20. package/dist/inbox/apply.d.ts +48 -0
  21. package/dist/inbox/apply.js +299 -0
  22. package/dist/inbox/conformance.d.ts +20 -0
  23. package/dist/inbox/conformance.js +254 -0
  24. package/dist/inbox/drizzle.d.ts +14 -0
  25. package/dist/inbox/drizzle.js +203 -0
  26. package/dist/inbox/ingest.d.ts +108 -0
  27. package/dist/inbox/ingest.js +404 -0
  28. package/dist/inbox/memory.d.ts +13 -0
  29. package/dist/inbox/memory.js +172 -0
  30. package/dist/inbox/ports.d.ts +150 -0
  31. package/dist/inbox/ports.js +1 -0
  32. package/dist/inbox/redact.d.ts +2 -0
  33. package/dist/inbox/redact.js +47 -0
  34. package/dist/inbox/schema.d.ts +1158 -0
  35. package/dist/inbox/schema.js +90 -0
  36. package/dist/inbox/watermark.d.ts +13 -0
  37. package/dist/inbox/watermark.js +6 -0
  38. package/dist/index.d.ts +30 -0
  39. package/dist/index.js +27 -0
  40. package/dist/ledger/ledger.d.ts +47 -0
  41. package/dist/ledger/ledger.js +224 -0
  42. package/dist/ports/index.d.ts +2 -0
  43. package/dist/ports/index.js +1 -0
  44. package/dist/ports/ledger-store.d.ts +53 -0
  45. package/dist/ports/ledger-store.js +1 -0
  46. package/dist/ports/runtime.d.ts +9 -0
  47. package/dist/ports/runtime.js +1 -0
  48. package/dist/providers/polar/events.d.ts +17 -0
  49. package/dist/providers/polar/events.js +213 -0
  50. package/dist/providers/polar/index.d.ts +50 -0
  51. package/dist/providers/polar/index.js +271 -0
  52. package/dist/providers/polar/signature.d.ts +23 -0
  53. package/dist/providers/polar/signature.js +52 -0
  54. package/dist/providers/port.d.ts +207 -0
  55. package/dist/providers/port.js +30 -0
  56. package/dist/providers/sepay/index.d.ts +34 -0
  57. package/dist/providers/sepay/index.js +241 -0
  58. package/dist/providers/sepay/order.d.ts +32 -0
  59. package/dist/providers/sepay/order.js +69 -0
  60. package/dist/providers/sepay/signature.d.ts +8 -0
  61. package/dist/providers/sepay/signature.js +51 -0
  62. package/dist/quote/conformance.d.ts +16 -0
  63. package/dist/quote/conformance.js +39 -0
  64. package/dist/quote/index.d.ts +3 -0
  65. package/dist/quote/index.js +3 -0
  66. package/dist/quote/steps.d.ts +54 -0
  67. package/dist/quote/steps.js +103 -0
  68. package/dist/quote/waterfall.d.ts +98 -0
  69. package/dist/quote/waterfall.js +82 -0
  70. package/dist/renewal/renewal.d.ts +69 -0
  71. package/dist/renewal/renewal.js +198 -0
  72. package/dist/stores/conformance.d.ts +22 -0
  73. package/dist/stores/conformance.js +269 -0
  74. package/dist/stores/memory.d.ts +19 -0
  75. package/dist/stores/memory.js +137 -0
  76. package/dist/stores/testing.d.ts +13 -0
  77. package/dist/stores/testing.js +13 -0
  78. package/dist/terms/conformance.d.ts +17 -0
  79. package/dist/terms/conformance.js +198 -0
  80. package/dist/terms/decide.d.ts +97 -0
  81. package/dist/terms/decide.js +176 -0
  82. package/dist/terms/drizzle.d.ts +12 -0
  83. package/dist/terms/drizzle.js +131 -0
  84. package/dist/terms/memory.d.ts +23 -0
  85. package/dist/terms/memory.js +126 -0
  86. package/dist/terms/plans.d.ts +85 -0
  87. package/dist/terms/plans.js +331 -0
  88. package/dist/terms/ports.d.ts +55 -0
  89. package/dist/terms/ports.js +1 -0
  90. package/dist/terms/rules.d.ts +11 -0
  91. package/dist/terms/rules.js +36 -0
  92. package/dist/terms/schema.d.ts +711 -0
  93. package/dist/terms/schema.js +70 -0
  94. package/dist/terms/snapshot.d.ts +20 -0
  95. package/dist/terms/snapshot.js +134 -0
  96. package/dist/terms/types.d.ts +85 -0
  97. package/dist/terms/types.js +4 -0
  98. package/docs/API.md +417 -0
  99. package/docs/SCHEMA.md +163 -0
  100. package/package.json +80 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,122 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
+ are additive.
5
+
6
+ ## 0.2.0 — 2026-10-18
7
+
8
+ Additive to 0.1: every 0.1 export is unchanged (public-api declaration
9
+ snapshot only grows). One type widens: `BillingErrorCode` gains five members
10
+ (below), so an exhaustive `switch` over it in a consumer needs the new cases
11
+ (or a `default`) to typecheck.
12
+
13
+ To adopt: pin `@tofound/billing@0.2.0`. If you use terms, export the tables
14
+ `createTermTables` returns from your drizzle schema and run `db:generate`.
15
+
16
+ - Catalog as config (`defineCatalog`): plans with strict ranks and one free
17
+ plan, N-month credit offers per market, provider offers by `productRef`,
18
+ credit packs and policies (`termDays`, `upgradeProration`, `graceDays`,
19
+ `renewalLeadSec`). Validated and frozen at boot (`invalid_catalog`).
20
+ - Terms (`Term`, `TermStore`): one shape for credit, Polar, Apple and Google
21
+ subscriptions; memory store and Drizzle tables/store (`createTermTables`,
22
+ `createDrizzleTermStore`, `termTableNames` in `/drizzle`); term store
23
+ conformance cases in `/testing`. **Schema:** two new tables,
24
+ `<prefix>terms` and the per-account lock row `<prefix>term_accounts` —
25
+ add `createTermTables(...)` to your drizzle schema and run `db:generate`
26
+ (additive: new tables and indexes only).
27
+ - Entitlement (`resolveEntitlement`): stacking S1–S5 across sources —
28
+ highest rank wins, then the later end; credit terms carry no included pool;
29
+ warnings `two_subscriptions`, `past_due`, `renewal_shortfall`,
30
+ `scheduled_downgrade`; nothing entitled → the free plan.
31
+ - Plans (`createPlans`): quote and buy N months with credits through one
32
+ waterfall — new, extend (S2), upgrade with host-policy proration
33
+ (`remaining_time`: ceil(remaining/total × (offerNew − paid)), end date kept;
34
+ or `none`), renew a past_due term, downgrade scheduled with no money moved
35
+ (S3b), blocked when a renewing subscription of ≥ rank covers it (S3,
36
+ `plan_blocked`); idempotent purchase keys; auto-renew on/off, cancel,
37
+ cancel now.
38
+ - Renewal (`createRenewal`): charges the live catalog price at period end
39
+ (`renew:<termId>:<periodEnd>`, a double run debits once); a short balance →
40
+ `past_due` with `graceDays` of entitlement; `retryPastDue` after a top-up
41
+ renews from the old end; grace passed → expired → free; scheduled terms
42
+ activate when they start; a failed early attempt (`renewalLeadSec`) keeps
43
+ the paid period active and is retried by the next run.
44
+ - Provider subscriptions (`createSnapshotHandler` for the ingest
45
+ `subscription.snapshot` slot): upserts the provider term under a watermark;
46
+ an entitled subscription of ≥ rank supersedes the credit term and refunds
47
+ its unused share pro rata (`plan_refund`, `supersede:<termId>`, rounded up);
48
+ an account `resolveAccount` does not know is ignored as unmatched and
49
+ relayed through `onUnmatched`.
50
+ - Polar adapter (`@tofound/billing/providers/polar`, new entry point):
51
+ `createPolarAdapter` for the ingest inbox, with Standard Webhooks
52
+ verification before any parse (both secret derivations, a rotation list,
53
+ a 300 s replay window). It normalizes three kinds of event:
54
+ - subscriptions → `subscription.snapshot`, for `createSnapshotHandler`;
55
+ - one-time **credit-pack orders** bound to a checkout session →
56
+ `purchase.completed`, credited once;
57
+ - **full refunds** → `purchase.reversed` (a ledger reversal). A partial
58
+ refund goes to `needs_review`.
59
+
60
+ An order's amount is the catalog price, `subtotal_amount −
61
+ discount_amount`, so tax-inclusive (EU buyers under tax behaviour
62
+ `location`), tax-exclusive and untaxed orders all credit the full pack;
63
+ refunds use the same basis. Polar's same-instant subscription events (one
64
+ revoke as `updated`, `canceled`, `revoked`) are ordered by type through the
65
+ new optional `SubscriptionSnapshotEvent.tieBreak`, which the snapshot handler
66
+ compares before the event id, and the period ends at `ended_at`.
67
+ `redactPolarPayload` also scrubs Polar secrets inside values, such as the
68
+ checkout client secret in a checkout `url`.
69
+
70
+ `createCheckout` opens one-time checkouts and `createPortalSession` opens
71
+ customer portal sessions. `resolvePolarEnvironment` makes the environment
72
+ explicit and refuses an unarmed production. Also exported:
73
+ `respondPolar`, `redactPolarPayload`, `signPolarWebhook` (test
74
+ deliveries), `PolarApiError` and the webhook header constants.
75
+ - Error codes: `invalid_catalog`, `plan_not_found`, `offer_not_found`,
76
+ `term_not_found`, `plan_blocked`. They widen the `BillingErrorCode` union,
77
+ so check exhaustive switches.
78
+ - Docs: the README describes 0.2 and links only to files shipped in the
79
+ package (no private-repo links). `docs/SCHEMA.md` names the tables each
80
+ factory returns. `docs/API.md` documents the `walletDelta` sign.
81
+
82
+ ## 0.1.0 — 2026-10-17
83
+
84
+ First release (baseline: repository start).
85
+
86
+ - Domain: `CreditUnit`, `Money`, safe-integer amounts, explicit rounding
87
+ (`divRound`, `mulDivRound`), `BillingError` codes.
88
+ - Ledger: single-entry, append-only, per-account `seq` + `balanceAfter`,
89
+ global idempotency keys (replay / `idempotency_mismatch`), no overdraft,
90
+ `debitUpTo` with recorded shortfall, one partial-or-full reversal per entry,
91
+ `ledger.in(tx)` for host transactions, `findByKey`, post-commit domain
92
+ events delivered at most once (sink errors go to `onEventError`).
93
+ - Ports: `LedgerStore` / `LedgerTx` / `LedgerReader`, `Clock`, `IdGenerator`,
94
+ `BillingEventSink`.
95
+ - Stores: memory store; Drizzle Postgres store (`@tofound/billing/drizzle`).
96
+ - Schema factory: `createBillingTables` (accounts, entries) with `schema` /
97
+ `prefix` / host-typed `accountId`, `billingTableBuilder`, and
98
+ `checkAdditiveDdl` for the additive-migration rules (statement-split,
99
+ multi-action aware, fails closed). Hosts run their own
100
+ `db:generate`. Entries resolve under `require` too (drizzle-kit loads schema
101
+ files that way; Node ≥ 22.12).
102
+ - Quote/charge: `createWaterfall` with `freeStep`, `quotaStep`, `creditsStep`;
103
+ one walk for the quote and the settlement; a retried charge replays its
104
+ credits posting (`Settled.replayed`) and settlement returns its ledger
105
+ events for the host's outbox.
106
+ - Provider port: `ProviderAdapter`, `CheckoutCapable`, `PurchaseVerifier`,
107
+ normalized events and an explicit `ProviderEnvironment` (never inferred).
108
+ - Payment inbox (`createIngest`): verify a webhook, persist it, apply each
109
+ event exactly once into the ledger — replays and concurrent redeliveries
110
+ are duplicates, late payments after checkout expiry still credit, unmatched
111
+ deliveries are kept for manual replay, plus retry sweep, dead-letter and
112
+ per-purchase watermarks. Memory store and Drizzle store/tables
113
+ (`createIngestTables`, `createDrizzleIngestStore` in `/drizzle`); payloads
114
+ are redacted before storage.
115
+ - SePay adapter (`@tofound/billing/providers/sepay`): `createSepayAdapter`
116
+ with secret-header webhook verification, signed checkout fields
117
+ (byte-compatible with `sepay-pg-node@1.0.0`, no SDK), order lookup that never
118
+ turns a lookup failure into a cancellation, `TRANSACTION_VOID` precedence,
119
+ VND-only settlement, and `respondSepay` for the host route. The environment
120
+ is required and production with test credentials is refused.
121
+ - Testing kit (`@tofound/billing/testing`): store conformance cases, ledger
122
+ invariant check, `assertQuoteMatchesSettlement`, ingest conformance cases.
package/LICENSE ADDED
@@ -0,0 +1,3 @@
1
+ Copyright (c) 2026 2found. All rights reserved.
2
+
3
+ This package is UNLICENSED. Publication on npm does not grant a license.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # 2billing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@tofound/billing` — the shared subscription & credit library for 2found
4
+ products (2Novel first, the Lohi reader api last). Each host API embeds it on
5
+ its own database; there is no billing service.
6
+
7
+ 0.2 ships:
8
+
9
+ - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
+ behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
11
+ factory the host re-exports and migrates itself, one quote/charge waterfall
12
+ and a payment webhook inbox (verify → persist → apply exactly once).
13
+ - **Catalog, terms and entitlement** (0.2): the catalog as host config
14
+ (`defineCatalog`), subscription terms from credits, Polar, Apple and Google in
15
+ one shape, `resolveEntitlement` (stacking rules S1–S5), buying N months with
16
+ credits (`createPlans`: extend, prorated upgrade, scheduled downgrade),
17
+ renewal at the live price with `past_due` + grace (`createRenewal`), and
18
+ provider snapshots that supersede a credit term with a pro-rata refund
19
+ (`createSnapshotHandler`).
20
+ - **Providers**: SePay (`@tofound/billing/providers/sepay`) and, new in 0.2,
21
+ Polar (`@tofound/billing/providers/polar`). Apple and Google adapters are
22
+ not in 0.2 yet; their terms already fit the 0.2 shape.
23
+
24
+ ```sh
25
+ bun add @tofound/billing@0.2.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ ```
27
+
28
+ ```ts
29
+ import { createLedger } from '@tofound/billing'
30
+ import { uuid } from 'drizzle-orm/pg-core'
31
+ import { createBillingTables, createDrizzleLedgerStore } from '@tofound/billing/drizzle'
32
+
33
+ // in a file your drizzle-kit `schema` glob covers, so `db:generate` sees the tables
34
+ export const { billingAccounts, billingEntries } = createBillingTables({ accountId: (n) => uuid(n).notNull() })
35
+ const ledger = createLedger({ store: createDrizzleLedgerStore({ db, tables: { billingAccounts, billingEntries } }) })
36
+ await db.transaction((tx) => ledger.in(tx).debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${id}:charge` }))
37
+ ```
38
+
39
+ Plans, terms and entitlement run on the same `db`:
40
+
41
+ ```ts
42
+ import { createPlans, createRenewal, defineCatalog, resolveEntitlement } from '@tofound/billing'
43
+ import { createDrizzleTermStore, createTermTables } from '@tofound/billing/drizzle'
44
+
45
+ export const { billingTerms, billingTermAccounts } = createTermTables({ accountId: (n) => uuid(n).notNull() })
46
+ const catalog = defineCatalog(hostCatalogConfig) // plans, prices, policies: the host's data, never the library's
47
+ const terms = createDrizzleTermStore({ db, tables: { billingTerms, billingTermAccounts } })
48
+ const plans = createPlans({ ledger, terms, catalog })
49
+ const renewal = createRenewal({ ledger, terms, catalog })
50
+ const ent = resolveEntitlement(await terms.reader().listTerms(accountId), new Date(), catalog)
51
+ ```
52
+
53
+ ## Polar
54
+
55
+ `@tofound/billing/providers/polar` is a webhook and checkout adapter for the
56
+ ingest inbox. `createPolarAdapter({ environment, webhookSecrets, products,
57
+ accessToken })` verifies Standard Webhooks signatures (secret rotation, 300 s
58
+ replay window) before parsing. It normalizes Polar subscriptions to
59
+ `subscription.snapshot` (applied by `createSnapshotHandler`), one-time credit
60
+ pack orders to `purchase.completed` and full refunds to `purchase.reversed`.
61
+ It also opens checkouts (`createCheckout`) and customer portal sessions.
62
+ `resolvePolarEnvironment` turns the host's environment and production-arming
63
+ switches into one required value. `signPolarWebhook` signs test deliveries.
64
+ The full entry is in `docs/API.md`.
65
+
66
+ ## Documentation
67
+
68
+ These files ship inside the package (`node_modules/@tofound/billing/…`):
69
+
70
+ - `docs/API.md`: ledger, ports, waterfall, inbox, providers, catalog, terms,
71
+ entitlement, renewal and error codes.
72
+ - `docs/SCHEMA.md`: the schema factory, the tables each factory returns and the
73
+ additive migration rules.
74
+ - `CHANGELOG.md`: what each version adds, and what a host must do to adopt it.
75
+
76
+ Develop with bun ≥ 1.3.14: `bun install`, then `bun run check` (typecheck,
77
+ build, tests on memory and Postgres, pack smoke). It needs a local Postgres
78
+ `initdb` (`PG_BIN` or a Homebrew `postgresql@17`), or
79
+ `BILLING_TEST_DATABASE_URL`, in which it creates a throwaway schema. Never
80
+ point it at a shared or production database.
@@ -0,0 +1,115 @@
1
+ import type { CreditUnit, Currency, Money } from '../domain/types.js';
2
+ /** A market the host prices in; the API sets it per account, the user never picks it (D11). */
3
+ export interface MarketSpec {
4
+ key: string;
5
+ currency: Currency;
6
+ }
7
+ /** N months of a plan bought with credits (the VN path). */
8
+ export interface CreditOffer {
9
+ source: 'credit';
10
+ market: string;
11
+ months: number;
12
+ /** Credit minor units for the whole `months`. */
13
+ credits: number;
14
+ }
15
+ /** A provider-billed offer; `productRef` maps to the provider's product id in host config. */
16
+ export interface ProviderOffer {
17
+ source: 'polar' | 'apple' | 'google';
18
+ productRef: string;
19
+ market?: string;
20
+ interval?: 'month' | 'year';
21
+ price?: Money;
22
+ /** Google base plan id. */
23
+ basePlan?: string;
24
+ }
25
+ export type PlanOffer = CreditOffer | ProviderOffer;
26
+ export interface PlanSpec {
27
+ key: string;
28
+ /** Strictly ordered across plans; higher wins (S1). */
29
+ rank: number;
30
+ /** The plan an account without an entitled term resolves to. Exactly one, the lowest rank, with no offers. */
31
+ free?: boolean;
32
+ permissions?: readonly string[];
33
+ quotas?: Readonly<Record<string, number>>;
34
+ /** Per-period credit pool of provider-funded terms only (A1). */
35
+ includedCredits?: number;
36
+ offers?: readonly PlanOffer[];
37
+ }
38
+ export type PackProvider = 'sepay' | 'polar' | 'apple' | 'google';
39
+ export interface CreditPackSpec {
40
+ key: string;
41
+ market: string;
42
+ provider: PackProvider;
43
+ price: Money;
44
+ credits: number;
45
+ bonusCredits?: number;
46
+ productRef?: string;
47
+ }
48
+ export type UpgradeProration = 'remaining_time' | 'none';
49
+ export type ReversalShortfallPolicy = 'lapse_credit_terms' | 'record';
50
+ export interface CatalogPolicies {
51
+ /** Days in one catalog month; a term of N months lasts N × termDays. */
52
+ termDays: number;
53
+ /** 2Novel `remaining_time`, Lohi `none` (D8). */
54
+ upgradeProration: UpgradeProration;
55
+ /** Days a failed renewal stays entitled as `past_due` (D9). */
56
+ graceDays: number;
57
+ reversalShortfall: ReversalShortfallPolicy;
58
+ /** How early `renewDue` may renew before the period end. */
59
+ renewalLeadSec: number;
60
+ }
61
+ export declare const DEFAULT_POLICIES: Readonly<CatalogPolicies>;
62
+ export interface CatalogSpec {
63
+ version: string | number;
64
+ creditUnit: CreditUnit;
65
+ markets: readonly MarketSpec[];
66
+ plans: readonly PlanSpec[];
67
+ creditPacks?: readonly CreditPackSpec[];
68
+ policies?: Partial<CatalogPolicies>;
69
+ /** Longest plan/pack key the host can store (Lohi `user_subscriptions.tier` is 16). Default 64. */
70
+ maxKeyLength?: number;
71
+ }
72
+ export interface Plan {
73
+ key: string;
74
+ rank: number;
75
+ free: boolean;
76
+ permissions: readonly string[];
77
+ quotas: Readonly<Record<string, number>>;
78
+ includedCredits: number | null;
79
+ offers: readonly PlanOffer[];
80
+ }
81
+ export type CreditPack = Readonly<Required<Omit<CreditPackSpec, 'productRef'>>> & {
82
+ readonly productRef: string | null;
83
+ };
84
+ export type ProductMatch = {
85
+ kind: 'plan';
86
+ plan: Plan;
87
+ offer: ProviderOffer;
88
+ } | {
89
+ kind: 'pack';
90
+ pack: CreditPack;
91
+ };
92
+ export interface Catalog {
93
+ readonly version: string | number;
94
+ readonly creditUnit: CreditUnit;
95
+ readonly markets: readonly MarketSpec[];
96
+ readonly policies: Readonly<CatalogPolicies>;
97
+ /** Every plan, lowest rank first. */
98
+ readonly plans: readonly Plan[];
99
+ readonly creditPacks: readonly CreditPack[];
100
+ readonly freePlan: Plan;
101
+ /** Throws `plan_not_found`. */
102
+ plan(key: string): Plan;
103
+ findPlan(key: string): Plan | undefined;
104
+ plansWithPermission(permission: string): Plan[];
105
+ market(key: string): MarketSpec | undefined;
106
+ creditOffer(plan: string, market: string, months: number): CreditOffer | undefined;
107
+ /** Credit offers of a plan in a market, fewest months first. */
108
+ creditOffers(plan: string, market: string): CreditOffer[];
109
+ pack(key: string): CreditPack | undefined;
110
+ packsFor(market: string, provider?: PackProvider): CreditPack[];
111
+ /** The plan offer or credit pack a provider product ref names. */
112
+ offerByProductRef(productRef: string): ProductMatch | undefined;
113
+ }
114
+ /** Validate and freeze a host catalog. */
115
+ export declare function defineCatalog(spec: CatalogSpec): Catalog;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Catalog as config (design §4.4). The library ships no plan, price or tier
3
+ * literal: a host passes its own catalog values to `defineCatalog`, which
4
+ * validates and freezes them and answers the lookups the terms, renewal and
5
+ * entitlement code need. Errors are `BillingError('invalid_catalog')` at
6
+ * definition time, so a broken catalog fails at boot, not at checkout.
7
+ */
8
+ import { BillingError } from '../domain/errors.js';
9
+ import { CURRENCY_EXPONENT } from '../domain/money.js';
10
+ export const DEFAULT_POLICIES = Object.freeze({
11
+ termDays: 30,
12
+ upgradeProration: 'remaining_time',
13
+ graceDays: 3,
14
+ reversalShortfall: 'record',
15
+ renewalLeadSec: 0,
16
+ });
17
+ const KEY = /^[a-z0-9][a-z0-9_.-]*$/;
18
+ function fail(message, details = {}) {
19
+ throw new BillingError('invalid_catalog', message, details);
20
+ }
21
+ function safeInt(value, what, min) {
22
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min)
23
+ fail(`${what} must be a safe integer ≥ ${min}, got ${String(value)}`);
24
+ return value;
25
+ }
26
+ /** Validate and freeze a host catalog. */
27
+ export function defineCatalog(spec) {
28
+ const maxKeyLength = spec.maxKeyLength ?? 64;
29
+ safeInt(maxKeyLength, 'maxKeyLength', 1);
30
+ const checkKey = (key, what) => {
31
+ if (typeof key !== 'string' || !KEY.test(key))
32
+ fail(`${what} key must be lower-case [a-z0-9_.-], got ${JSON.stringify(key)}`);
33
+ if (key.length > maxKeyLength)
34
+ fail(`${what} key ${key} is longer than ${maxKeyLength}`, { key });
35
+ return key;
36
+ };
37
+ const unit = spec.creditUnit;
38
+ if (!unit?.code || !Number.isInteger(unit.exponent) || unit.exponent < 0 || unit.exponent > 6)
39
+ fail('creditUnit needs a code and an exponent 0..6');
40
+ const policies = { ...DEFAULT_POLICIES, ...(spec.policies ?? {}) };
41
+ safeInt(policies.termDays, 'policies.termDays', 1);
42
+ safeInt(policies.graceDays, 'policies.graceDays', 0);
43
+ safeInt(policies.renewalLeadSec, 'policies.renewalLeadSec', 0);
44
+ if (!['remaining_time', 'none'].includes(policies.upgradeProration))
45
+ fail(`unknown upgradeProration ${policies.upgradeProration}`);
46
+ if (!['lapse_credit_terms', 'record'].includes(policies.reversalShortfall))
47
+ fail(`unknown reversalShortfall ${policies.reversalShortfall}`);
48
+ if (!spec.markets?.length)
49
+ fail('a catalog needs at least one market');
50
+ const markets = new Map();
51
+ for (const m of spec.markets) {
52
+ checkKey(m.key, 'market');
53
+ if (markets.has(m.key))
54
+ fail(`duplicate market ${m.key}`);
55
+ if (!Object.hasOwn(CURRENCY_EXPONENT, m.currency))
56
+ fail(`market ${m.key}: unknown currency ${m.currency}`);
57
+ markets.set(m.key, Object.freeze({ key: m.key, currency: m.currency }));
58
+ }
59
+ const checkMoney = (price, market, what) => {
60
+ if (!price)
61
+ return;
62
+ if (!Object.hasOwn(CURRENCY_EXPONENT, price.currency))
63
+ fail(`${what}: unknown currency ${price.currency}`);
64
+ safeInt(price.amountMinor, `${what} price`, 1);
65
+ const m = market === undefined ? undefined : markets.get(market);
66
+ if (m && m.currency !== price.currency)
67
+ fail(`${what}: price in ${price.currency} but market ${m.key} prices in ${m.currency}`);
68
+ };
69
+ const checkMarket = (market, what) => {
70
+ if (market !== undefined && !markets.has(market))
71
+ fail(`${what}: unknown market ${market}`);
72
+ };
73
+ const productRefs = new Map();
74
+ const claimRef = (ref, match, what) => {
75
+ if (typeof ref !== 'string' || !ref)
76
+ fail(`${what}: productRef is required`);
77
+ if (productRefs.has(ref))
78
+ fail(`duplicate productRef ${ref}`, { productRef: ref });
79
+ productRefs.set(ref, match);
80
+ };
81
+ if (!spec.plans?.length)
82
+ fail('a catalog needs at least one plan');
83
+ const byKey = new Map();
84
+ const ranks = new Set();
85
+ for (const p of spec.plans) {
86
+ checkKey(p.key, 'plan');
87
+ if (byKey.has(p.key))
88
+ fail(`duplicate plan ${p.key}`);
89
+ safeInt(p.rank, `plan ${p.key} rank`, 0);
90
+ if (ranks.has(p.rank))
91
+ fail(`plan ranks must be strictly ordered; rank ${p.rank} repeats at ${p.key}`);
92
+ ranks.add(p.rank);
93
+ for (const [name, value] of Object.entries(p.quotas ?? {}))
94
+ safeInt(value, `plan ${p.key} quota ${name}`, 0);
95
+ if (p.includedCredits !== undefined)
96
+ safeInt(p.includedCredits, `plan ${p.key} includedCredits`, 0);
97
+ const offers = [];
98
+ const plan = {
99
+ key: p.key,
100
+ rank: p.rank,
101
+ free: p.free === true,
102
+ permissions: Object.freeze([...(p.permissions ?? [])]),
103
+ quotas: Object.freeze({ ...(p.quotas ?? {}) }),
104
+ includedCredits: p.includedCredits ?? null,
105
+ offers,
106
+ };
107
+ const creditMonths = new Set();
108
+ for (const o of p.offers ?? []) {
109
+ const what = `plan ${p.key} ${o.source} offer`;
110
+ if (o.source === 'credit') {
111
+ checkMarket(o.market, what);
112
+ if (o.market === undefined)
113
+ fail(`${what}: market is required`);
114
+ safeInt(o.months, `${what} months`, 1);
115
+ safeInt(o.credits, `${what} credits`, 1);
116
+ const slot = `${o.market}:${o.months}`;
117
+ if (creditMonths.has(slot))
118
+ fail(`${what}: ${o.months} months in ${o.market} is offered twice`);
119
+ creditMonths.add(slot);
120
+ offers.push(Object.freeze({ source: 'credit', market: o.market, months: o.months, credits: o.credits }));
121
+ }
122
+ else if (o.source === 'polar' || o.source === 'apple' || o.source === 'google') {
123
+ checkMarket(o.market, what);
124
+ checkMoney(o.price, o.market, what);
125
+ const offer = Object.freeze({ ...o });
126
+ claimRef(o.productRef, { kind: 'plan', plan, offer }, what);
127
+ offers.push(offer);
128
+ }
129
+ else {
130
+ fail(`${what}: unknown source`);
131
+ }
132
+ }
133
+ Object.freeze(offers);
134
+ byKey.set(p.key, Object.freeze(plan));
135
+ }
136
+ const plans = [...byKey.values()].sort((a, b) => a.rank - b.rank);
137
+ const frees = plans.filter((p) => p.free);
138
+ if (frees.length !== 1)
139
+ fail(`exactly one plan must be free, found ${frees.length}`);
140
+ const freePlan = frees[0];
141
+ if (freePlan !== plans[0])
142
+ fail(`free plan ${freePlan.key} must have the lowest rank`);
143
+ if (freePlan.offers.length)
144
+ fail(`free plan ${freePlan.key} cannot have offers`);
145
+ const packs = [];
146
+ const packKeys = new Set();
147
+ for (const k of spec.creditPacks ?? []) {
148
+ checkKey(k.key, 'pack');
149
+ if (packKeys.has(k.key))
150
+ fail(`duplicate pack ${k.key}`);
151
+ packKeys.add(k.key);
152
+ const what = `pack ${k.key}`;
153
+ checkMarket(k.market, what);
154
+ if (!['sepay', 'polar', 'apple', 'google'].includes(k.provider))
155
+ fail(`${what}: unknown provider ${k.provider}`);
156
+ checkMoney(k.price, k.market, what);
157
+ if (!k.price)
158
+ fail(`${what}: price is required`);
159
+ safeInt(k.credits, `${what} credits`, 1);
160
+ if (k.bonusCredits !== undefined)
161
+ safeInt(k.bonusCredits, `${what} bonusCredits`, 0);
162
+ const pack = Object.freeze({
163
+ key: k.key,
164
+ market: k.market,
165
+ provider: k.provider,
166
+ price: Object.freeze({ ...k.price }),
167
+ credits: k.credits,
168
+ bonusCredits: k.bonusCredits ?? 0,
169
+ productRef: k.productRef ?? null,
170
+ });
171
+ if (k.productRef !== undefined)
172
+ claimRef(k.productRef, { kind: 'pack', pack }, what);
173
+ packs.push(pack);
174
+ }
175
+ const creditOffers = (plan, market) => (byKey.get(plan)?.offers ?? [])
176
+ .filter((o) => o.source === 'credit' && o.market === market)
177
+ .sort((a, b) => a.months - b.months);
178
+ return Object.freeze({
179
+ version: spec.version,
180
+ creditUnit: Object.freeze({ code: unit.code, exponent: unit.exponent }),
181
+ markets: Object.freeze([...markets.values()]),
182
+ policies: Object.freeze(policies),
183
+ plans: Object.freeze(plans),
184
+ creditPacks: Object.freeze(packs),
185
+ freePlan,
186
+ plan(key) {
187
+ const p = byKey.get(key);
188
+ if (!p)
189
+ throw new BillingError('plan_not_found', `unknown plan ${key}`, { plan: key });
190
+ return p;
191
+ },
192
+ findPlan: (key) => byKey.get(key),
193
+ plansWithPermission: (permission) => plans.filter((p) => p.permissions.includes(permission)),
194
+ market: (key) => markets.get(key),
195
+ creditOffer: (plan, market, months) => creditOffers(plan, market).find((o) => o.months === months),
196
+ creditOffers,
197
+ pack: (key) => packs.find((p) => p.key === key),
198
+ packsFor: (market, provider) => packs.filter((p) => p.market === market && (!provider || p.provider === provider)),
199
+ offerByProductRef: (productRef) => productRefs.get(productRef),
200
+ });
201
+ }
@@ -0,0 +1,14 @@
1
+ import type { BillingErrorCode, InsufficientCredits } from './types.js';
2
+ /**
3
+ * The one error type the library throws for domain outcomes. Hosts map
4
+ * `code` to their own HTTP status and copy (e.g. `insufficient_credits` →
5
+ * 402 with `details.shortfall`); the message is for logs only.
6
+ */
7
+ export declare class BillingError extends Error {
8
+ readonly name = "BillingError";
9
+ readonly code: BillingErrorCode;
10
+ readonly details: Record<string, unknown>;
11
+ constructor(code: BillingErrorCode, message: string, details?: Record<string, unknown>);
12
+ }
13
+ export declare function isBillingError(value: unknown, code?: BillingErrorCode): value is BillingError;
14
+ export declare function insufficientCredits(details: InsufficientCredits): BillingError;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The one error type the library throws for domain outcomes. Hosts map
3
+ * `code` to their own HTTP status and copy (e.g. `insufficient_credits` →
4
+ * 402 with `details.shortfall`); the message is for logs only.
5
+ */
6
+ export class BillingError extends Error {
7
+ name = 'BillingError';
8
+ code;
9
+ details;
10
+ constructor(code, message, details = {}) {
11
+ super(message);
12
+ this.code = code;
13
+ this.details = details;
14
+ }
15
+ }
16
+ export function isBillingError(value, code) {
17
+ return value instanceof BillingError && (code === undefined || value.code === code);
18
+ }
19
+ export function insufficientCredits(details) {
20
+ return new BillingError('insufficient_credits', `insufficient credits: balance ${details.balance}, required ${details.required}`, { ...details });
21
+ }
@@ -0,0 +1,21 @@
1
+ import type { CreditUnit, Currency, Money, RoundingMode } from './types.js';
2
+ /** Minor-unit exponent of each fiat currency. */
3
+ export declare const CURRENCY_EXPONENT: Readonly<Record<Currency, number>>;
4
+ /** Throws `invalid_amount` unless `value` is a safe integer (≥ 0 unless `signed`). */
5
+ export declare function assertMinor(value: number, label?: string, options?: {
6
+ signed?: boolean;
7
+ positive?: boolean;
8
+ }): number;
9
+ export declare function money(currency: Currency, amountMinor: number): Money;
10
+ export declare function creditUnit(code: string, exponent: number): CreditUnit;
11
+ /**
12
+ * `numerator / denominator` rounded explicitly, for integers only. Grants and
13
+ * refunds pass `'ceil'` (the customer never loses a fraction); charges that
14
+ * favour the customer pass `'floor'`. Fees in the design (upgrade proration)
15
+ * name their own mode.
16
+ */
17
+ export declare function divRound(numerator: number, denominator: number, mode: RoundingMode): number;
18
+ /** `amount × numerator / denominator`, rounded, without intermediate overflow. */
19
+ export declare function mulDivRound(amount: number, numerator: number, denominator: number, mode: RoundingMode): number;
20
+ /** Render minor units as a plain decimal string (`150000, exp 2 → "1500.00"`). Display formatting is the host's. */
21
+ export declare function formatMinor(amountMinor: number, exponent: number): string;
@@ -0,0 +1,77 @@
1
+ import { BillingError } from './errors.js';
2
+ /** Minor-unit exponent of each fiat currency. */
3
+ export const CURRENCY_EXPONENT = Object.freeze({ VND: 0, USD: 2 });
4
+ /** Throws `invalid_amount` unless `value` is a safe integer (≥ 0 unless `signed`). */
5
+ export function assertMinor(value, label = 'amount', options = {}) {
6
+ if (!Number.isSafeInteger(value)) {
7
+ throw new BillingError('invalid_amount', `${label} must be a safe integer in minor units, got ${value}`, { [label]: value });
8
+ }
9
+ if (options.positive && value <= 0) {
10
+ throw new BillingError('invalid_amount', `${label} must be positive, got ${value}`, { [label]: value });
11
+ }
12
+ if (!options.signed && value < 0) {
13
+ throw new BillingError('invalid_amount', `${label} must not be negative, got ${value}`, { [label]: value });
14
+ }
15
+ return value;
16
+ }
17
+ export function money(currency, amountMinor) {
18
+ if (!Object.hasOwn(CURRENCY_EXPONENT, currency))
19
+ throw new BillingError('invalid_input', `unknown currency ${currency}`);
20
+ return { currency, amountMinor: assertMinor(amountMinor, 'amountMinor') };
21
+ }
22
+ export function creditUnit(code, exponent) {
23
+ if (!code)
24
+ throw new BillingError('invalid_input', 'credit unit code is required');
25
+ if (!Number.isInteger(exponent) || exponent < 0 || exponent > 6) {
26
+ throw new BillingError('invalid_input', `credit unit exponent must be an integer 0..6, got ${exponent}`);
27
+ }
28
+ return Object.freeze({ code, exponent });
29
+ }
30
+ /**
31
+ * `numerator / denominator` rounded explicitly, for integers only. Grants and
32
+ * refunds pass `'ceil'` (the customer never loses a fraction); charges that
33
+ * favour the customer pass `'floor'`. Fees in the design (upgrade proration)
34
+ * name their own mode.
35
+ */
36
+ export function divRound(numerator, denominator, mode) {
37
+ assertMinor(numerator, 'numerator', { signed: true });
38
+ assertMinor(denominator, 'denominator', { positive: true });
39
+ return roundQuotient(BigInt(numerator), BigInt(denominator), mode);
40
+ }
41
+ /** `amount × numerator / denominator`, rounded, without intermediate overflow. */
42
+ export function mulDivRound(amount, numerator, denominator, mode) {
43
+ assertMinor(amount, 'amount', { signed: true });
44
+ assertMinor(numerator, 'numerator', { signed: true });
45
+ assertMinor(denominator, 'denominator', { positive: true });
46
+ return roundQuotient(BigInt(amount) * BigInt(numerator), BigInt(denominator), mode);
47
+ }
48
+ function roundQuotient(n, d, mode) {
49
+ let q = n / d;
50
+ const r = n % d;
51
+ if (r !== 0n) {
52
+ const negative = n < 0n;
53
+ if (mode === 'ceil' && !negative)
54
+ q += 1n;
55
+ else if (mode === 'floor' && negative)
56
+ q -= 1n;
57
+ else if (mode === 'half_up' && (r < 0n ? -r : r) * 2n >= d)
58
+ q += negative ? -1n : 1n;
59
+ }
60
+ return toSafe(q);
61
+ }
62
+ /** Render minor units as a plain decimal string (`150000, exp 2 → "1500.00"`). Display formatting is the host's. */
63
+ export function formatMinor(amountMinor, exponent) {
64
+ assertMinor(amountMinor, 'amountMinor', { signed: true });
65
+ if (exponent === 0)
66
+ return String(amountMinor);
67
+ const negative = amountMinor < 0;
68
+ const digits = String(Math.abs(amountMinor)).padStart(exponent + 1, '0');
69
+ const out = `${digits.slice(0, -exponent)}.${digits.slice(-exponent)}`;
70
+ return negative ? `-${out}` : out;
71
+ }
72
+ function toSafe(value) {
73
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
74
+ throw new BillingError('balance_overflow', `result ${value} exceeds the safe integer range`);
75
+ }
76
+ return Number(value);
77
+ }