@tofound/billing 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,7 +1,96 @@
1
1
  # Changelog
2
2
 
3
3
  All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
4
- are additive.
4
+ were additive. From 1.0.0 the public API is frozen: removing or narrowing
5
+ anything in the declaration snapshot is a major version.
6
+
7
+ ## 1.1.0 — 2026-10-24
8
+
9
+ Additive to 1.0: every 1.0 export is unchanged (the public-api declaration
10
+ snapshot only grows). No schema change.
11
+
12
+ To adopt: pin `@tofound/billing@1.1.0`.
13
+
14
+ - **`afterCredited` / `onHookError`** on `createIngest`: a hook called after
15
+ the delivery's transaction commits, at most once per credit, with a
16
+ `CreditedPurchase` (`provider`, `accountId`, `kind`, `entry`, `externalId`,
17
+ `sessionId`). It fires for the library's own appliers and for a host handler
18
+ that returns the new optional `credited` field on its result
19
+ (`HandlerResult`, an alias of `ApplyResult`). It never fires for a duplicate,
20
+ a replay of a settled row, an ignored delivery, a reversal, a rolled-back
21
+ attempt or an empty entry. A hook that throws goes to `onHookError` and never
22
+ changes the delivery outcome.
23
+ - **`defaultEventHandlers`** exported: the library's `purchase.completed`,
24
+ `purchase.reversed` and `purchase.reinstated` appliers, so a host that
25
+ overrides a kind for one provider can delegate the others back. `ApplyContext`
26
+ gains `store` (the ingest store bound to the handler's transaction) and
27
+ `newId`; handlers only read them, so existing handlers compile unchanged
28
+ (a test that builds an `ApplyContext` by hand adds the two fields).
29
+ - **`ingest.createCheckout` forwards `customerIpAddress`** to the adapter
30
+ (`CheckoutRequest.customerIpAddress`, optional). Polar uses it to pick the tax
31
+ country; before, only a direct `polar.createCheckout` sent it.
32
+ - **`docs/GUIDE.md`**, a task guide shipped in the package: credit packs, a
33
+ monthly plan end to end, a provider subscription and supersede, failed
34
+ renewals per source, refunds with shortfall, arming a provider, migrating a
35
+ legacy term table, and that Google Play subscriptions are not supported.
36
+
37
+ ## 1.0.0 — 2026-10-24
38
+
39
+ The 1.0 API freeze. Every 0.2 export is unchanged (changes since 0.2.0 are
40
+ the host kit, the Apple and Google adapters, the SePay tightening and the
41
+ API snapshot below); from here on any breaking API change is a major version.
42
+
43
+ To adopt: pin `@tofound/billing@1.0.0`. No schema change: no factory table
44
+ gained a column.
45
+
46
+ - **API freeze:** the public-api contract test snapshots the export names and
47
+ emitted declarations of every entry point. 1.0.0 is that snapshot.
48
+ - **Host kit** (`@tofound/billing/hostkit`, new entry point) for hosts that
49
+ keep their own tables and wire. Lohi first; see `docs/MIGRATION-LOHI.md`.
50
+ - `createLegacyLedgerStore(driver, codec)` builds a full `LedgerStore` over
51
+ a host's legacy wallet tables from a small driver of row I/O:
52
+ - seq is derived from `(createdAt, id)` order, and new rows are kept
53
+ strictly after the newest one;
54
+ - key-less pre-adapter rows read as `legacy:<id>`;
55
+ - the host reason column is written by `reasonOf`, and the kind of an old
56
+ row is read by `kindOf`.
57
+
58
+ A Lohi-shaped driver passes the full ledger store conformance suite on
59
+ memory and Postgres.
60
+ - `createAdminAdjustments({ store, overdraft })` handles operator balance
61
+ adjustments: one `adjustment` entry per request id, posted under the
62
+ account lock. A stale `expectedBalance` answers `balance_changed` and
63
+ posts nothing. Overdraft policy is `reject` (`insufficient_credits`) or
64
+ `clamp` (take what is there and report the `shortfall`). It runs in its
65
+ own transaction or in the host's.
66
+ - `serializeQuote` / `serializePlanQuote` produce the served quote:
67
+ - Lohi's key order, with unset optionals left out;
68
+ - labels only from a host labeler, so a host serving codes alone passes
69
+ none;
70
+ - the legacy `subscriptionCovered` key on request;
71
+ - plan periods as ISO strings.
72
+ - **Apple** (`@tofound/billing/providers/apple`, new entry point):
73
+ `createAppleAdapter`. Covers App Store Server Notifications v2 and
74
+ StoreKit 2 client proofs, verified through the JWS `x5c` chain to the pinned
75
+ Apple Root CA G3. One-time (consumable) purchases are keyed by transaction.
76
+ Refunds, refund reversals and revokes apply once, ordered by `signedDate`.
77
+ Auto-renewable notifications become subscription snapshots. Consumption
78
+ reporting goes through the App Store Server API.
79
+ - **Google** (`@tofound/billing/providers/google`, new entry point):
80
+ `createGoogleAdapter`. Covers Play RTDN over Pub/Sub push, with the OIDC
81
+ token verified. A purchase is trusted only as Play's own `products.get`
82
+ answer. A voided purchase, from RTDN or from `voidedpurchases.list`
83
+ (`listChangesSince`), is clawed back once. Subscription notifications are
84
+ acknowledged as ignored.
85
+ - **SePay:**
86
+ - `order.user_agent` (any `user_agent` key) is dropped from stored inbox
87
+ payloads, on top of the generic redaction.
88
+ - An IPN whose `transaction.transaction_amount` disagrees with
89
+ `order.order_amount` goes to `needs_review` with reason
90
+ `amount_mismatch` and credits (or reverses) nothing. The comparison uses
91
+ the magnitude, so a void reported as a negative movement still matches.
92
+ - Public types are unchanged.
93
+ - **Package:** ships `docs/MIGRATION-LOHI.md`.
5
94
 
6
95
  ## 0.2.0 — 2026-10-18
7
96
 
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  products (2Novel first, the Lohi reader api last). Each host API embeds it on
5
5
  its own database; there is no billing service.
6
6
 
7
- 0.2 ships:
7
+ 1.1 ships (the public API is frozen from 1.0.0 on; 1.1 only adds):
8
8
 
9
9
  - **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
10
10
  behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
@@ -17,12 +17,13 @@ its own database; there is no billing service.
17
17
  renewal at the live price with `past_due` + grace (`createRenewal`), and
18
18
  provider snapshots that supersede a credit term with a pro-rata refund
19
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.
20
+ - **Providers**: SePay (`@tofound/billing/providers/sepay`), Polar
21
+ (`@tofound/billing/providers/polar`, 0.2), and, new in 1.0, the App Store
22
+ (`@tofound/billing/providers/apple`) and Google Play
23
+ (`@tofound/billing/providers/google`) adapters.
23
24
 
24
25
  ```sh
25
- bun add @tofound/billing@0.2.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
+ bun add @tofound/billing@1.1.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
26
27
  ```
27
28
 
28
29
  ```ts
@@ -63,12 +64,26 @@ It also opens checkouts (`createCheckout`) and customer portal sessions.
63
64
  switches into one required value. `signPolarWebhook` signs test deliveries.
64
65
  The full entry is in `docs/API.md`.
65
66
 
67
+ ## Host kit
68
+
69
+ `@tofound/billing/hostkit` (new in 1.0) is for hosts that keep their own
70
+ tables and wire. It provides:
71
+ - `createLegacyLedgerStore`, a full `LedgerStore` over legacy wallet tables
72
+ built from a small driver of row I/O;
73
+ - `createAdminAdjustments`, for operator balance adjustments on the ledger;
74
+ - `serializeQuote` / `serializePlanQuote`, which turn a `Quote` into the
75
+ served JSON.
76
+
77
+ `docs/MIGRATION-LOHI.md` walks the Lohi reader API through it.
78
+
66
79
  ## Documentation
67
80
 
68
81
  These files ship inside the package (`node_modules/@tofound/billing/…`):
69
82
 
70
83
  - `docs/API.md`: ledger, ports, waterfall, inbox, providers, catalog, terms,
71
84
  entitlement, renewal and error codes.
85
+ - `docs/MIGRATION-LOHI.md`: moving the Lohi reader API onto the library with
86
+ the host kit.
72
87
  - `docs/SCHEMA.md`: the schema factory, the tables each factory returns and the
73
88
  additive migration rules.
74
89
  - `CHANGELOG.md`: what each version adds, and what a host must do to adopt it.
@@ -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
+ }