@tofound/billing 0.1.0 → 1.0.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 (67) hide show
  1. package/CHANGELOG.md +136 -1
  2. package/README.md +73 -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/hostkit/adjustments.d.ts +65 -0
  11. package/dist/hostkit/adjustments.js +84 -0
  12. package/dist/hostkit/index.d.ts +9 -0
  13. package/dist/hostkit/index.js +9 -0
  14. package/dist/hostkit/legacy-ledger.d.ts +87 -0
  15. package/dist/hostkit/legacy-ledger.js +111 -0
  16. package/dist/hostkit/quote-wire.d.ts +73 -0
  17. package/dist/hostkit/quote-wire.js +50 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +9 -0
  20. package/dist/providers/apple/events.d.ts +24 -0
  21. package/dist/providers/apple/events.js +232 -0
  22. package/dist/providers/apple/index.d.ts +54 -0
  23. package/dist/providers/apple/index.js +231 -0
  24. package/dist/providers/apple/jws.d.ts +50 -0
  25. package/dist/providers/apple/jws.js +206 -0
  26. package/dist/providers/google/api.d.ts +57 -0
  27. package/dist/providers/google/api.js +226 -0
  28. package/dist/providers/google/events.d.ts +46 -0
  29. package/dist/providers/google/events.js +135 -0
  30. package/dist/providers/google/index.d.ts +37 -0
  31. package/dist/providers/google/index.js +228 -0
  32. package/dist/providers/polar/events.d.ts +17 -0
  33. package/dist/providers/polar/events.js +213 -0
  34. package/dist/providers/polar/index.d.ts +50 -0
  35. package/dist/providers/polar/index.js +271 -0
  36. package/dist/providers/polar/signature.d.ts +23 -0
  37. package/dist/providers/polar/signature.js +52 -0
  38. package/dist/providers/port.d.ts +6 -0
  39. package/dist/providers/sepay/index.js +29 -0
  40. package/dist/renewal/renewal.d.ts +69 -0
  41. package/dist/renewal/renewal.js +198 -0
  42. package/dist/stores/testing.d.ts +4 -2
  43. package/dist/stores/testing.js +4 -2
  44. package/dist/terms/conformance.d.ts +17 -0
  45. package/dist/terms/conformance.js +198 -0
  46. package/dist/terms/decide.d.ts +97 -0
  47. package/dist/terms/decide.js +176 -0
  48. package/dist/terms/drizzle.d.ts +12 -0
  49. package/dist/terms/drizzle.js +131 -0
  50. package/dist/terms/memory.d.ts +23 -0
  51. package/dist/terms/memory.js +126 -0
  52. package/dist/terms/plans.d.ts +85 -0
  53. package/dist/terms/plans.js +331 -0
  54. package/dist/terms/ports.d.ts +55 -0
  55. package/dist/terms/ports.js +1 -0
  56. package/dist/terms/rules.d.ts +11 -0
  57. package/dist/terms/rules.js +36 -0
  58. package/dist/terms/schema.d.ts +711 -0
  59. package/dist/terms/schema.js +70 -0
  60. package/dist/terms/snapshot.d.ts +20 -0
  61. package/dist/terms/snapshot.js +134 -0
  62. package/dist/terms/types.d.ts +85 -0
  63. package/dist/terms/types.js +4 -0
  64. package/docs/API.md +415 -6
  65. package/docs/MIGRATION-LOHI.md +237 -0
  66. package/docs/SCHEMA.md +57 -2
  67. package/package.json +22 -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
+ }
@@ -0,0 +1,65 @@
1
+ import type { AccountId, BillingEvent, EntryMeta, LedgerEntry } from '../domain/types.js';
2
+ import type { LedgerStore } from '../ports/ledger-store.js';
3
+ import type { BillingEventSink, Clock, IdGenerator } from '../ports/runtime.js';
4
+ /**
5
+ * Operator balance adjustments (2Novel `adjustUserBalance`, Lohi
6
+ * `POST /admin/users/:id/topup`) on the ledger: one entry of kind
7
+ * `adjustment` per request id, posted under the account lock, never a direct
8
+ * balance write. The host keeps its own audit row, permission check and copy;
9
+ * this owns the money rules.
10
+ */
11
+ /**
12
+ * What a debit larger than the balance does:
13
+ * - `reject` → `insufficient_credits` (2Novel);
14
+ * - `clamp` → take what is there and report the rest as `shortfall` (Lohi's
15
+ * `max(0, balance + amount)`).
16
+ */
17
+ export type AdjustmentOverdraft = 'reject' | 'clamp';
18
+ export interface AdjustmentInput {
19
+ accountId: AccountId;
20
+ /** Signed credit minor units; never 0. */
21
+ amount: number;
22
+ /** Minted once per operator action; a retry with it posts nothing more. */
23
+ requestId: string;
24
+ /** The balance the operator saw. A different one answers `balance_changed` and posts nothing. */
25
+ expectedBalance?: number;
26
+ /** Host reason column, e.g. `admin_adjustment` or Lohi's `admin_topup:<note>`. Default `admin_adjustment`. */
27
+ reason?: string;
28
+ actorId?: string | null;
29
+ note?: string | null;
30
+ source?: {
31
+ type: string;
32
+ id: string;
33
+ } | null;
34
+ meta?: EntryMeta | null;
35
+ }
36
+ export type AdjustmentResult = {
37
+ status: 'applied' | 'replayed';
38
+ entry: LedgerEntry;
39
+ balanceBefore: number;
40
+ balanceAfter: number;
41
+ /** Credit minor units a clamped debit could not take; 0 otherwise. */
42
+ shortfall: number;
43
+ /** Ledger events, already sent to `events` when the kit owned the transaction. */
44
+ events: BillingEvent[];
45
+ } | {
46
+ status: 'balance_changed';
47
+ balance: number;
48
+ };
49
+ export interface AdminAdjustmentsOptions<TTx> {
50
+ store: LedgerStore<TTx>;
51
+ /** Default `reject`. */
52
+ overdraft?: AdjustmentOverdraft;
53
+ /** Idempotency key prefix; the key is `<prefix><requestId>`. Default `admin:`. */
54
+ keyPrefix?: string;
55
+ clock?: Clock;
56
+ ids?: IdGenerator;
57
+ /** Receives events after commit of transactions the kit opened. */
58
+ events?: BillingEventSink;
59
+ onEventError?: (error: unknown, event: BillingEvent) => void;
60
+ }
61
+ export interface AdminAdjustments<TTx> {
62
+ /** Post one adjustment, in its own transaction or inside the host's `tx`. */
63
+ adjust(input: AdjustmentInput, tx?: TTx): Promise<AdjustmentResult>;
64
+ }
65
+ export declare function createAdminAdjustments<TTx>(options: AdminAdjustmentsOptions<TTx>): AdminAdjustments<TTx>;
@@ -0,0 +1,84 @@
1
+ import { BillingError } from '../domain/errors.js';
2
+ import { assertMinor } from '../domain/money.js';
3
+ import { createLedger } from '../ledger/ledger.js';
4
+ export function createAdminAdjustments(options) {
5
+ const { store } = options;
6
+ const overdraft = options.overdraft ?? 'reject';
7
+ const keyPrefix = options.keyPrefix ?? 'admin:';
8
+ // Events are emitted here after the kit's own commit, not by the ledger.
9
+ const ledger = createLedger({
10
+ store,
11
+ ...(options.clock ? { clock: options.clock } : {}),
12
+ ...(options.ids ? { ids: options.ids } : {}),
13
+ });
14
+ async function run(tx, input) {
15
+ const idempotencyKey = `${keyPrefix}${input.requestId}`;
16
+ // Lock first, so the expected-balance check and the posting see one state.
17
+ const account = await store.bind(tx).lockAccount(input.accountId);
18
+ const ops = ledger.in(tx);
19
+ const prior = await ops.findByKey(idempotencyKey);
20
+ if (!prior && input.expectedBalance !== undefined && input.expectedBalance !== account.balance) {
21
+ return { status: 'balance_changed', balance: account.balance };
22
+ }
23
+ const meta = {
24
+ ...(input.meta ?? {}),
25
+ adjustment: { actorId: input.actorId ?? null, note: input.note ?? null, requestId: input.requestId },
26
+ };
27
+ const post = {
28
+ accountId: input.accountId,
29
+ kind: 'adjustment',
30
+ amount: Math.abs(input.amount),
31
+ idempotencyKey,
32
+ reason: input.reason ?? 'admin_adjustment',
33
+ source: input.source ?? null,
34
+ meta,
35
+ };
36
+ let shortfall = 0;
37
+ let posted;
38
+ if (input.amount > 0)
39
+ posted = await ops.credit(post);
40
+ else if (overdraft === 'clamp') {
41
+ const clamped = await ops.debitUpTo(post);
42
+ shortfall = clamped.shortfall;
43
+ posted = clamped;
44
+ }
45
+ else
46
+ posted = await ops.debit(post);
47
+ const { entry } = posted;
48
+ return {
49
+ status: posted.replayed ? 'replayed' : 'applied',
50
+ entry,
51
+ balanceBefore: entry.balanceAfter - entry.delta,
52
+ balanceAfter: entry.balanceAfter,
53
+ shortfall,
54
+ events: posted.events,
55
+ };
56
+ }
57
+ return {
58
+ async adjust(input, tx) {
59
+ if (!input.accountId)
60
+ throw new BillingError('invalid_input', 'accountId is required');
61
+ if (!input.requestId)
62
+ throw new BillingError('invalid_input', 'requestId is required');
63
+ assertMinor(input.amount, 'amount', { signed: true });
64
+ if (input.amount === 0)
65
+ throw new BillingError('invalid_amount', 'an adjustment moves a non-zero amount', { amount: 0 });
66
+ if (input.expectedBalance !== undefined)
67
+ assertMinor(input.expectedBalance, 'expectedBalance');
68
+ if (tx !== undefined)
69
+ return run(tx, input);
70
+ const result = await store.transaction((own) => run(own, input));
71
+ if (result.status !== 'balance_changed' && options.events) {
72
+ for (const event of result.events) {
73
+ try {
74
+ await options.events(event);
75
+ }
76
+ catch (error) {
77
+ options.onEventError?.(error, event);
78
+ }
79
+ }
80
+ }
81
+ return result;
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@tofound/billing/hostkit` — helpers for hosts that keep their own tables
3
+ * and wire (Lohi first, see `docs/MIGRATION-LOHI.md`): a `LedgerStore` over
4
+ * legacy wallet tables, operator adjustments on the ledger, and the quote
5
+ * serializer.
6
+ */
7
+ export { createLegacyLedgerStore, LEGACY_KEY_PREFIX, type LegacyEntryRow, type LegacyLedgerCodec, type LegacyLedgerFields, type LegacyWalletDriver, } from './legacy-ledger.js';
8
+ export { createAdminAdjustments, type AdjustmentInput, type AdjustmentOverdraft, type AdjustmentResult, type AdminAdjustments, type AdminAdjustmentsOptions, } from './adjustments.js';
9
+ export { serializePlanQuote, serializeQuote, type FundingLineWire, type PlanQuoteWire, type QuoteLabeler, type QuoteWire, type QuoteWireOptions, } from './quote-wire.js';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@tofound/billing/hostkit` — helpers for hosts that keep their own tables
3
+ * and wire (Lohi first, see `docs/MIGRATION-LOHI.md`): a `LedgerStore` over
4
+ * legacy wallet tables, operator adjustments on the ledger, and the quote
5
+ * serializer.
6
+ */
7
+ export { createLegacyLedgerStore, LEGACY_KEY_PREFIX, } from './legacy-ledger.js';
8
+ export { createAdminAdjustments, } from './adjustments.js';
9
+ export { serializePlanQuote, serializeQuote, } from './quote-wire.js';
@@ -0,0 +1,87 @@
1
+ import type { AccountId, EntryKind, EntryMeta, LedgerEntry } from '../domain/types.js';
2
+ import type { LedgerStore } from '../ports/ledger-store.js';
3
+ /**
4
+ * A `LedgerStore` over a host's own wallet tables (design §11): Lohi keeps
5
+ * `user_wallets` / `wallet_transactions`, its reason strings and its
6
+ * analytics, and still gets the library's ledger rules. The host writes a
7
+ * small driver of row I/O against its tables; this module supplies
8
+ * everything the store contract adds on top:
9
+ *
10
+ * - **seq** — a legacy table has none, so an entry's seq is its 1-based
11
+ * position in the account's `(createdAt, id)` order. To keep that order
12
+ * equal to posting order, a new row's `createdAt` is moved to 1 ms after
13
+ * the account's newest row when the clock has not advanced past it (the
14
+ * wallet lock serializes postings, so this is race-free).
15
+ * - **rows written before the adapter** — they have no idempotency key and no
16
+ * library fields: their key reads as `legacy:<id>` and their kind comes from
17
+ * `kindOf(row)`.
18
+ * - **reason** — the host's reason column is written from `reasonOf(entry)`,
19
+ * so analytics keyed on reason prefixes keep working.
20
+ *
21
+ * The result must pass `ledgerConformanceCases` from `@tofound/billing/testing`
22
+ * against the host's real database; that suite is the acceptance test for a
23
+ * driver.
24
+ */
25
+ /** Library fields a legacy table has no column for; the driver persists them (one nullable jsonb column will do). */
26
+ export interface LegacyLedgerFields {
27
+ kind: EntryKind;
28
+ reversesId: string | null;
29
+ sourceType: string | null;
30
+ sourceId: string | null;
31
+ meta: EntryMeta | null;
32
+ }
33
+ /** One row of the host's transaction table, in library terms. */
34
+ export interface LegacyEntryRow {
35
+ id: string;
36
+ accountId: AccountId;
37
+ /** Signed delta (Lohi `amount`). */
38
+ amount: number;
39
+ balanceBefore: number;
40
+ balanceAfter: number;
41
+ /** The host's reason column, e.g. Lohi `tts_pro` or `admin_topup:<note>`. */
42
+ reason: string;
43
+ /** `null` on rows written before the adapter. */
44
+ idempotencyKey: string | null;
45
+ createdAt: Date;
46
+ /** `null` on rows written before the adapter. */
47
+ ledger: LegacyLedgerFields | null;
48
+ }
49
+ /**
50
+ * Row I/O against the host's tables. `q` is the open transaction, or `null`
51
+ * for a read outside one. Order is always `(createdAt, id)`.
52
+ */
53
+ export interface LegacyWalletDriver<TTx> {
54
+ transaction<T>(fn: (tx: TTx) => Promise<T>): Promise<T>;
55
+ /** `SELECT … FOR UPDATE` the wallet row, inserting it at balance 0 first when missing; returns the balance. */
56
+ lockWallet(tx: TTx, accountId: AccountId): Promise<number>;
57
+ setBalance(tx: TTx, accountId: AccountId, balance: number): Promise<void>;
58
+ /**
59
+ * `INSERT … ON CONFLICT DO NOTHING`. The table must refuse a second row with
60
+ * the same `idempotencyKey`, and a second row reversing the same
61
+ * `ledger.reversesId`; a refused row answers `false` without aborting the
62
+ * transaction.
63
+ */
64
+ insertRow(tx: TTx, row: LegacyEntryRow): Promise<boolean>;
65
+ /** The wallet balance; `null` when the account has no wallet row. */
66
+ getBalance(q: TTx | null, accountId: AccountId): Promise<number | null>;
67
+ getRow(q: TTx | null, id: string): Promise<LegacyEntryRow | null>;
68
+ findRowByKey(q: TTx | null, idempotencyKey: string): Promise<LegacyEntryRow | null>;
69
+ /** The row whose `ledger.reversesId` is `entryId`. */
70
+ findReversalOf(q: TTx | null, entryId: string): Promise<LegacyEntryRow | null>;
71
+ /** Rows of the account; with `before`, only those ordered strictly before it. */
72
+ countRows(q: TTx | null, accountId: AccountId, before?: LegacyEntryRow): Promise<number>;
73
+ /** Newest first, skipping the `offset` newest rows. */
74
+ listRows(q: TTx | null, accountId: AccountId, page: {
75
+ limit: number;
76
+ offset: number;
77
+ }): Promise<LegacyEntryRow[]>;
78
+ }
79
+ export interface LegacyLedgerCodec {
80
+ /** The host reason written for an entry. Default `entry.reason ?? entry.kind`. */
81
+ reasonOf?(entry: LedgerEntry): string;
82
+ /** The kind of a row written before the adapter. Default: `topup` for a credit, `spend` otherwise. */
83
+ kindOf?(row: LegacyEntryRow): EntryKind;
84
+ }
85
+ /** Key of a pre-adapter row, which has none of its own. */
86
+ export declare const LEGACY_KEY_PREFIX = "legacy:";
87
+ export declare function createLegacyLedgerStore<TTx>(driver: LegacyWalletDriver<TTx>, codec?: LegacyLedgerCodec): LedgerStore<TTx>;
@@ -0,0 +1,111 @@
1
+ /** Key of a pre-adapter row, which has none of its own. */
2
+ export const LEGACY_KEY_PREFIX = 'legacy:';
3
+ export function createLegacyLedgerStore(driver, codec = {}) {
4
+ const reasonOf = codec.reasonOf ?? ((entry) => entry.reason ?? entry.kind);
5
+ const kindOf = codec.kindOf ?? ((row) => (row.amount > 0 ? 'topup' : 'spend'));
6
+ const toEntry = (row, seq) => ({
7
+ id: row.id,
8
+ accountId: row.accountId,
9
+ seq,
10
+ delta: row.amount,
11
+ balanceAfter: row.balanceAfter,
12
+ kind: row.ledger?.kind ?? kindOf(row),
13
+ reason: row.reason,
14
+ idempotencyKey: row.idempotencyKey ?? `${LEGACY_KEY_PREFIX}${row.id}`,
15
+ sourceType: row.ledger?.sourceType ?? null,
16
+ sourceId: row.ledger?.sourceId ?? null,
17
+ reversesId: row.ledger?.reversesId ?? null,
18
+ meta: row.ledger?.meta ?? null,
19
+ createdAt: row.createdAt,
20
+ });
21
+ const reader = (q) => {
22
+ const withSeq = async (row) => row ? toEntry(row, (await driver.countRows(q, row.accountId, row)) + 1) : null;
23
+ return {
24
+ async getAccount(accountId) {
25
+ const balance = await driver.getBalance(q, accountId);
26
+ return balance === null ? null : { accountId, balance, seq: await driver.countRows(q, accountId) };
27
+ },
28
+ getEntry: async (id) => withSeq(await driver.getRow(q, id)),
29
+ async findEntryByKey(key) {
30
+ const row = await driver.findRowByKey(q, key);
31
+ if (row || !key.startsWith(LEGACY_KEY_PREFIX))
32
+ return withSeq(row);
33
+ const legacy = await driver.getRow(q, key.slice(LEGACY_KEY_PREFIX.length));
34
+ return withSeq(legacy?.idempotencyKey === null ? legacy : null);
35
+ },
36
+ async listEntries(accountId, options) {
37
+ // A written row's position never moves (rows only append after the
38
+ // newest), but the total can grow between the count and the page read.
39
+ // So the page's seqs come from its first row's own position, and a page
40
+ // a concurrent posting shifted is read again from the corrected offset.
41
+ const { beforeSeq } = options;
42
+ let offset = null;
43
+ for (let attempt = 0;; attempt++) {
44
+ if (offset === null) {
45
+ const total = await driver.countRows(q, accountId);
46
+ // Rows with seq < beforeSeq are the oldest beforeSeq − 1.
47
+ offset = beforeSeq === undefined ? 0 : Math.max(0, total - Math.max(0, beforeSeq - 1));
48
+ }
49
+ const rows = await driver.listRows(q, accountId, { limit: options.limit, offset });
50
+ if (rows.length === 0)
51
+ return [];
52
+ const first = (await driver.countRows(q, accountId, rows[0])) + 1;
53
+ const shift = beforeSeq === undefined ? 0 : first - (beforeSeq - 1);
54
+ if (shift <= 0 || attempt === 2) {
55
+ const entries = rows.map((row, i) => toEntry(row, first - i));
56
+ return beforeSeq === undefined ? entries : entries.filter((e) => e.seq < beforeSeq);
57
+ }
58
+ offset += shift;
59
+ }
60
+ },
61
+ };
62
+ };
63
+ function bind(tx) {
64
+ const read = reader(tx);
65
+ return {
66
+ ...read,
67
+ async lockAccount(accountId) {
68
+ const balance = await driver.lockWallet(tx, accountId);
69
+ return { accountId, balance, seq: await driver.countRows(tx, accountId) };
70
+ },
71
+ findReversalOf: async (entryId) => {
72
+ const row = await driver.findReversalOf(tx, entryId);
73
+ return row ? read.getEntry(row.id) : null;
74
+ },
75
+ async appendEntry(entry) {
76
+ const [newest] = await driver.listRows(tx, entry.accountId, { limit: 1, offset: 0 });
77
+ if (newest && entry.createdAt.getTime() <= newest.createdAt.getTime()) {
78
+ // Order is position: the entry the ledger returns carries the stored time.
79
+ entry.createdAt = new Date(newest.createdAt.getTime() + 1);
80
+ }
81
+ const inserted = await driver.insertRow(tx, {
82
+ id: entry.id,
83
+ accountId: entry.accountId,
84
+ amount: entry.delta,
85
+ balanceBefore: entry.balanceAfter - entry.delta,
86
+ balanceAfter: entry.balanceAfter,
87
+ reason: reasonOf(entry),
88
+ idempotencyKey: entry.idempotencyKey,
89
+ createdAt: entry.createdAt,
90
+ ledger: {
91
+ kind: entry.kind,
92
+ reversesId: entry.reversesId,
93
+ sourceType: entry.sourceType,
94
+ sourceId: entry.sourceId,
95
+ meta: entry.meta,
96
+ },
97
+ });
98
+ return { inserted };
99
+ },
100
+ async setAccountState(state) {
101
+ // seq is derived from the rows; only the balance is stored.
102
+ await driver.setBalance(tx, state.accountId, state.balance);
103
+ },
104
+ };
105
+ }
106
+ return {
107
+ transaction: (fn) => driver.transaction(fn),
108
+ bind,
109
+ reader: () => reader(null),
110
+ };
111
+ }
@@ -0,0 +1,73 @@
1
+ import type { FundingLine, Quote, QuoteReason, Settlement } from '../domain/types.js';
2
+ import type { PlanQuoteKind } from '../terms/decide.js';
3
+ import type { PlanQuote } from '../terms/plans.js';
4
+ /**
5
+ * The quote a host serves (design §8, §9). A client renders these lines and
6
+ * prints these labels; it never re-derives a price, so the wire carries the
7
+ * whole outcome and nothing a client could send back as a price. Keys come
8
+ * out in Lohi's `access/quote.ts` order, and optional fields that are unset
9
+ * are left out rather than sent as `null`.
10
+ */
11
+ export interface FundingLineWire {
12
+ source: string;
13
+ unit: string;
14
+ amount: number;
15
+ remainingBefore: number | null;
16
+ remainingAfter: number | null;
17
+ label?: string;
18
+ }
19
+ export interface QuoteWire {
20
+ originalPrice: number;
21
+ price: number;
22
+ currency: string;
23
+ reason: {
24
+ code: string;
25
+ label?: string;
26
+ detail?: string;
27
+ };
28
+ funding: FundingLineWire[];
29
+ settlement: Settlement;
30
+ canSettle: boolean;
31
+ shortfall?: number;
32
+ balance: number | null;
33
+ upsell?: {
34
+ plan: string;
35
+ label?: string;
36
+ };
37
+ expiresInSec: number;
38
+ /** Legacy "a subscription covers this outright", present only with `coveredSources`. */
39
+ subscriptionCovered?: boolean;
40
+ }
41
+ export interface PlanQuoteWire extends QuoteWire {
42
+ kind: PlanQuoteKind;
43
+ plan: string;
44
+ months: number;
45
+ market: string;
46
+ /** ISO 8601; `null` when blocked. */
47
+ periodStart: string | null;
48
+ periodEnd: string | null;
49
+ scheduled: boolean;
50
+ }
51
+ /**
52
+ * Host copy. Return `undefined` to keep the label the step set, if any; a host
53
+ * that lets clients localize codes (2Novel) passes no labeler.
54
+ */
55
+ export interface QuoteLabeler {
56
+ reason?(reason: QuoteReason, quote: Quote): string | undefined;
57
+ line?(line: FundingLine, quote: Quote): string | undefined;
58
+ upsell?(upsell: NonNullable<Quote['upsell']>, quote: Quote): string | undefined;
59
+ }
60
+ export interface QuoteWireOptions {
61
+ labels?: QuoteLabeler;
62
+ /**
63
+ * Funding sources that mean a subscription covers the charge. When given,
64
+ * `subscriptionCovered` is served: true when the quote settles and only
65
+ * these sources fund it — the key shipped iOS builds still decode. A pool
66
+ * that funds part of the price, with the wallet paying the rest, is not
67
+ * covered.
68
+ */
69
+ coveredSources?: readonly string[];
70
+ }
71
+ export declare function serializeQuote(quote: Quote, options?: QuoteWireOptions): QuoteWire;
72
+ /** A plan quote (`createPlans().quote`): the purchase fields first, then the quote, then the period as ISO strings. */
73
+ export declare function serializePlanQuote(quote: PlanQuote, options?: QuoteWireOptions): PlanQuoteWire;
@@ -0,0 +1,50 @@
1
+ export function serializeQuote(quote, options = {}) {
2
+ const labels = options.labels ?? {};
3
+ const reasonLabel = labels.reason?.(quote.reason, quote) ?? quote.reason.label;
4
+ const upsellLabel = quote.upsell ? (labels.upsell?.(quote.upsell, quote) ?? quote.upsell.label) : undefined;
5
+ return {
6
+ originalPrice: quote.originalPrice,
7
+ price: quote.price,
8
+ currency: quote.currency,
9
+ reason: {
10
+ code: quote.reason.code,
11
+ ...(reasonLabel === undefined ? {} : { label: reasonLabel }),
12
+ ...(quote.reason.detail === undefined ? {} : { detail: quote.reason.detail }),
13
+ },
14
+ funding: quote.funding.map((line) => {
15
+ const label = labels.line?.(line, quote) ?? line.label;
16
+ return {
17
+ source: line.source,
18
+ unit: line.unit,
19
+ amount: line.amount,
20
+ remainingBefore: line.remainingBefore,
21
+ remainingAfter: line.remainingAfter,
22
+ ...(label === undefined ? {} : { label }),
23
+ };
24
+ }),
25
+ settlement: quote.settlement,
26
+ canSettle: quote.canSettle,
27
+ ...(quote.shortfall === undefined ? {} : { shortfall: quote.shortfall }),
28
+ balance: quote.balance,
29
+ ...(quote.upsell ? { upsell: { plan: quote.upsell.plan, ...(upsellLabel === undefined ? {} : { label: upsellLabel }) } } : {}),
30
+ expiresInSec: quote.expiresInSec,
31
+ ...(options.coveredSources
32
+ ? {
33
+ subscriptionCovered: quote.canSettle && quote.funding.length > 0 && quote.funding.every((l) => options.coveredSources.includes(l.source)),
34
+ }
35
+ : {}),
36
+ };
37
+ }
38
+ /** A plan quote (`createPlans().quote`): the purchase fields first, then the quote, then the period as ISO strings. */
39
+ export function serializePlanQuote(quote, options = {}) {
40
+ return {
41
+ kind: quote.kind,
42
+ plan: quote.plan,
43
+ months: quote.months,
44
+ market: quote.market,
45
+ ...serializeQuote(quote, options),
46
+ periodStart: quote.periodStart?.toISOString() ?? null,
47
+ periodEnd: quote.periodEnd?.toISOString() ?? null,
48
+ scheduled: quote.scheduled,
49
+ };
50
+ }
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';