@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
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Drizzle schema factory — the `billing.schema-factory` contract.
3
+ *
4
+ * The library never ships SQL. A host re-exports the tables from its own
5
+ * `schema.ts` (so its drizzle-kit glob sees them) and generates its own
6
+ * migration with `db:generate`. Rules every library table follows
7
+ * (docs/SCHEMA.md): new tables and indexes only, evolved later only with
8
+ * nullable columns without a volatile default, never `GENERATED … STORED`,
9
+ * never a statement on a host table. `checkAdditiveDdl` enforces them on
10
+ * generated SQL.
11
+ */
12
+ import { sql } from 'drizzle-orm';
13
+ import { bigint, check, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, varchar, } from 'drizzle-orm/pg-core';
14
+ export const DEFAULT_PREFIX = 'billing_';
15
+ /**
16
+ * Declares a table under the factory's schema and prefix. Other library
17
+ * modules (inbox, checkout sessions, purchases, terms) declare their tables
18
+ * through this so one host config names and places all of them.
19
+ */
20
+ export function billingTableBuilder(config) {
21
+ const prefix = config.prefix ?? DEFAULT_PREFIX;
22
+ if (!/^[a-z][a-z0-9_]*$/.test(prefix)) {
23
+ throw new Error(`billing schema prefix must be lower snake case, got ${JSON.stringify(prefix)}`);
24
+ }
25
+ const table = (config.schema ? config.schema.table.bind(config.schema) : pgTable);
26
+ return {
27
+ prefix,
28
+ /** `prefix + name`: use for index and constraint names too. */
29
+ name: (name) => `${prefix}${name}`,
30
+ table,
31
+ };
32
+ }
33
+ /** The ledger tables: one balance row per account and the append-only entries. */
34
+ export function createBillingTables(config) {
35
+ const b = billingTableBuilder(config);
36
+ const billingAccounts = b.table(b.name('accounts'), {
37
+ accountId: config.accountId('account_id'),
38
+ balance: bigint('balance', { mode: 'number' }).notNull().default(0),
39
+ seq: bigint('seq', { mode: 'number' }).notNull().default(0),
40
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
41
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
42
+ }, (t) => [
43
+ primaryKey({ name: b.name('accounts_pk'), columns: [t.accountId] }),
44
+ check(b.name('accounts_balance_nonneg'), sql `${t.balance} >= 0`),
45
+ ]);
46
+ const billingEntries = b.table(b.name('entries'), {
47
+ id: varchar('id', { length: 64 }).primaryKey(),
48
+ accountId: config.accountId('account_id'),
49
+ seq: bigint('seq', { mode: 'number' }).notNull(),
50
+ delta: bigint('delta', { mode: 'number' }).notNull(),
51
+ balanceAfter: bigint('balance_after', { mode: 'number' }).notNull(),
52
+ kind: varchar('kind', { length: 32 }).notNull(),
53
+ reason: text('reason'),
54
+ idempotencyKey: text('idempotency_key').notNull(),
55
+ sourceType: varchar('source_type', { length: 64 }),
56
+ sourceId: text('source_id'),
57
+ reversesId: varchar('reverses_id', { length: 64 }),
58
+ meta: jsonb('meta').$type(),
59
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
60
+ }, (t) => [
61
+ uniqueIndex(b.name('entries_idempotency_key_uq')).on(t.idempotencyKey),
62
+ uniqueIndex(b.name('entries_account_seq_uq')).on(t.accountId, t.seq),
63
+ // NULLs are distinct, so this is "UNIQUE when not null" (design §4.3).
64
+ uniqueIndex(b.name('entries_reverses_id_uq')).on(t.reversesId),
65
+ check(b.name('entries_balance_after_nonneg'), sql `${t.balanceAfter} >= 0`),
66
+ ]);
67
+ return { billingAccounts, billingEntries };
68
+ }
69
+ /** A default that is not a constant: computed per row, so ADD COLUMN rewrites the table. */
70
+ const VOLATILE_DEFAULT = /\b(?:"?[a-z_][a-z0-9_]*"?\s*\.\s*)?"?(now|random|gen_random_uuid|uuid_generate_v[14]|clock_timestamp|statement_timestamp|transaction_timestamp|timeofday|nextval|txid_current)"?\s*\(|\b(current_timestamp|current_date|current_time|localtimestamp|localtime)\b/i;
71
+ /** Column types and clauses that fill every existing row from a sequence. */
72
+ const SEQUENCE_FILL = /\b(small|big)?serial\b|\bserial[248]\b|\bgenerated\s+(always|by\s+default)\s+as\s+identity\b/i;
73
+ const IDENT = String.raw `(?:"[^"]+"|[a-z_][a-z0-9_$]*)`;
74
+ const QUALIFIED = String.raw `(?:${IDENT}\s*\.\s*)?(${IDENT})`;
75
+ function unquote(ident) {
76
+ return ident.startsWith('"') ? ident.slice(1, -1) : ident.toLowerCase();
77
+ }
78
+ /**
79
+ * Split on `separator` outside quotes and parentheses. A dollar-quoted body
80
+ * (functions, DO blocks) is not parsed: it stays in one piece and is then
81
+ * reported as `unrecognized`.
82
+ */
83
+ function splitTopLevel(text, separator) {
84
+ if (text.includes('$$'))
85
+ return [text];
86
+ const parts = [];
87
+ let depth = 0;
88
+ let quote = null;
89
+ let start = 0;
90
+ for (let i = 0; i < text.length; i++) {
91
+ const c = text[i];
92
+ if (quote) {
93
+ if (c === quote)
94
+ quote = null;
95
+ }
96
+ else if (c === '"' || c === "'")
97
+ quote = c;
98
+ else if (c === '(')
99
+ depth++;
100
+ else if (c === ')')
101
+ depth--;
102
+ else if (c === separator && depth === 0) {
103
+ parts.push(text.slice(start, i));
104
+ start = i + 1;
105
+ }
106
+ }
107
+ parts.push(text.slice(start));
108
+ return parts.map((p) => p.trim()).filter(Boolean);
109
+ }
110
+ /**
111
+ * Check generated migration statements against the library's additive rules.
112
+ * `statements` are the SQL of one migration (drizzle-kit output split on
113
+ * `--> statement-breakpoint`, or a custom migration); an element holding
114
+ * several `;`-separated statements is checked statement by statement.
115
+ * Returns every violation; empty = safe. Unknown shapes fail closed.
116
+ */
117
+ export function checkAdditiveDdl(statements, options) {
118
+ const library = new Set(options.libraryTables);
119
+ const violations = [];
120
+ const all = statements.flatMap((raw) => splitTopLevel(raw, ';'));
121
+ const created = new Set();
122
+ const createTable = new RegExp(String.raw `^create\s+table\s+(?:if\s+not\s+exists\s+)?${QUALIFIED}`, 'i');
123
+ for (const statement of all) {
124
+ const m = createTable.exec(statement);
125
+ if (m?.[1])
126
+ created.add(unquote(m[1]));
127
+ }
128
+ const flag = (rule, statement, message) => violations.push({ rule, statement, message });
129
+ const alterTable = new RegExp(String.raw `^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${QUALIFIED}\s+(.*)$`, 'is');
130
+ const createIndex = new RegExp(String.raw `^create\s+(?:unique\s+)?index\s+(concurrently\s+)?(?:if\s+not\s+exists\s+)?${IDENT}?\s*on\s+(?:only\s+)?${QUALIFIED}`, 'i');
131
+ const addColumn = new RegExp(String.raw `^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?${IDENT}\s+\S`, 'i');
132
+ const addConstraint = /^add\s+(?:constraint\s+\S+\s+)?(primary\s+key|unique|check|foreign\s+key|exclude)\b/i;
133
+ for (const statement of all) {
134
+ if (/\bgenerated\s+always\s+as\s*\(.*\)\s*stored\b/is.test(statement)) {
135
+ flag('generated_stored', statement, 'GENERATED … STORED rewrites the table; use a nullable column + trigger + batched backfill');
136
+ }
137
+ if (/^create\s+schema\b/i.test(statement))
138
+ continue;
139
+ // The migration preamble the rules require (docs/SCHEMA.md).
140
+ if (/^set\s+(local\s+)?(lock_timeout|statement_timeout)\b/i.test(statement))
141
+ continue;
142
+ const ct = createTable.exec(statement);
143
+ if (ct?.[1]) {
144
+ const table = unquote(ct[1]);
145
+ if (!library.has(table))
146
+ flag('non_library_table', statement, `creates ${table}, which is not a library table`);
147
+ continue;
148
+ }
149
+ const ci = createIndex.exec(statement);
150
+ if (ci?.[2]) {
151
+ const table = unquote(ci[2]);
152
+ if (!library.has(table))
153
+ flag('non_library_table', statement, `indexes host table ${table}`);
154
+ else if (!created.has(table) && !ci[1]) {
155
+ flag('blocking_index', statement, `index on existing ${table} blocks writes; use CREATE INDEX CONCURRENTLY in a custom migration`);
156
+ }
157
+ continue;
158
+ }
159
+ const at = alterTable.exec(statement);
160
+ if (at?.[1]) {
161
+ const table = unquote(at[1]);
162
+ if (!library.has(table)) {
163
+ flag('non_library_table', statement, `alters host table ${table}`);
164
+ continue;
165
+ }
166
+ const isNew = created.has(table);
167
+ for (const action of splitTopLevel(at[2] ?? '', ','))
168
+ checkAlterAction(table, isNew, action, statement);
169
+ continue;
170
+ }
171
+ if (/^(drop|truncate|delete|update|insert|alter|rename|comment|grant|revoke)\b/i.test(statement)) {
172
+ flag('destructive', statement, 'only CREATE TABLE / CREATE INDEX / ADD COLUMN / ADD CONSTRAINT are additive');
173
+ continue;
174
+ }
175
+ flag('unrecognized', statement, 'statement is not one the additive rules recognise');
176
+ }
177
+ return violations;
178
+ function checkAlterAction(table, isNew, action, statement) {
179
+ const constraint = addConstraint.exec(action);
180
+ if (constraint?.[1] || /^add\s+constraint\b/i.test(action)) {
181
+ if (isNew)
182
+ return;
183
+ const kind = (constraint?.[1] ?? '').toLowerCase();
184
+ if (/^(primary|unique|exclude)/.test(kind)) {
185
+ // Builds an index under ACCESS EXCLUSIVE unless it adopts a prebuilt one.
186
+ if (!/\busing\s+index\b/i.test(action)) {
187
+ flag('blocking_index', statement, `${kind.toUpperCase()} on existing ${table} builds an index under lock; CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT … USING INDEX`);
188
+ }
189
+ }
190
+ else if (!/\bnot\s+valid\b/i.test(action)) {
191
+ flag('validating_constraint', statement, `constraint on existing ${table} scans it under lock; add it NOT VALID and VALIDATE separately`);
192
+ }
193
+ return;
194
+ }
195
+ if (addColumn.test(action)) {
196
+ if (VOLATILE_DEFAULT.test(action) || SEQUENCE_FILL.test(action)) {
197
+ flag('volatile_default', statement, 'ADD COLUMN with a per-row (volatile or sequence) default rewrites every row');
198
+ }
199
+ if (!isNew && /\bnot\s+null\b/i.test(action)) {
200
+ flag('not_null_add_column', statement, 'ADD COLUMN on an existing table must be nullable');
201
+ }
202
+ return;
203
+ }
204
+ flag('destructive', statement, `ALTER TABLE ${table} ${action.split(/\s+/).slice(0, 3).join(' ')} is not additive`);
205
+ }
206
+ }
@@ -0,0 +1,20 @@
1
+ import type { PgDatabase, PgTable, PgQueryResultHKT, PgTransaction } from 'drizzle-orm/pg-core';
2
+ import type { LedgerStore } from '../ports/ledger-store.js';
3
+ /** Any Drizzle Postgres database (postgres-js, node-postgres, …). */
4
+ export type AnyPgDatabase = PgDatabase<PgQueryResultHKT, any, any>;
5
+ /** A transaction of that database, as handed to `db.transaction(fn)`. */
6
+ export type AnyPgTransaction = PgTransaction<PgQueryResultHKT, any, any>;
7
+ export interface DrizzleLedgerStoreOptions {
8
+ db: AnyPgDatabase;
9
+ /** The host's factory tables (`createBillingTables(...)`), whatever its account column type. */
10
+ tables: {
11
+ billingAccounts: PgTable;
12
+ billingEntries: PgTable;
13
+ };
14
+ }
15
+ /**
16
+ * Postgres `LedgerStore` over the factory tables. `bind(tx)` takes the host's
17
+ * own Drizzle transaction, so a posting commits or rolls back with the host's
18
+ * other writes. Expects READ COMMITTED (the Postgres default).
19
+ */
20
+ export declare function createDrizzleLedgerStore(options: DrizzleLedgerStoreOptions): LedgerStore<AnyPgTransaction>;
@@ -0,0 +1,124 @@
1
+ import { and, desc, eq, lt } from 'drizzle-orm';
2
+ /**
3
+ * Postgres `LedgerStore` over the factory tables. `bind(tx)` takes the host's
4
+ * own Drizzle transaction, so a posting commits or rolls back with the host's
5
+ * other writes. Expects READ COMMITTED (the Postgres default).
6
+ */
7
+ export function createDrizzleLedgerStore(options) {
8
+ const { db } = options;
9
+ // The account column's TS type is whatever the host's builder declares; the
10
+ // library only ever writes and reads the subject id as a string.
11
+ const accounts = options.tables.billingAccounts;
12
+ const entries = options.tables.billingEntries;
13
+ const toEntry = (row) => ({
14
+ id: row.id,
15
+ accountId: String(row.accountId),
16
+ seq: row.seq,
17
+ delta: row.delta,
18
+ balanceAfter: row.balanceAfter,
19
+ kind: row.kind,
20
+ reason: row.reason,
21
+ idempotencyKey: row.idempotencyKey,
22
+ sourceType: row.sourceType,
23
+ sourceId: row.sourceId,
24
+ reversesId: row.reversesId,
25
+ meta: row.meta ?? null,
26
+ createdAt: row.createdAt,
27
+ });
28
+ const reader = (ex) => ({
29
+ async getAccount(accountId) {
30
+ const [row] = await ex
31
+ .select({ accountId: accounts.accountId, balance: accounts.balance, seq: accounts.seq })
32
+ .from(accounts)
33
+ .where(eq(accounts.accountId, accountId));
34
+ return row ? { accountId: String(row.accountId), balance: row.balance, seq: row.seq } : null;
35
+ },
36
+ async getEntry(id) {
37
+ const [row] = await ex.select().from(entries).where(eq(entries.id, id));
38
+ return row ? toEntry(row) : null;
39
+ },
40
+ async findEntryByKey(key) {
41
+ const [row] = await ex.select().from(entries).where(eq(entries.idempotencyKey, key));
42
+ return row ? toEntry(row) : null;
43
+ },
44
+ async listEntries(accountId, opts) {
45
+ const scope = eq(entries.accountId, accountId);
46
+ const rows = await ex
47
+ .select()
48
+ .from(entries)
49
+ .where(opts.beforeSeq === undefined ? scope : and(scope, lt(entries.seq, opts.beforeSeq)))
50
+ .orderBy(desc(entries.seq))
51
+ .limit(opts.limit);
52
+ return rows.map(toEntry);
53
+ },
54
+ });
55
+ const bind = (tx) => {
56
+ async function selectForUpdate(accountId) {
57
+ const [row] = await tx
58
+ .select({ accountId: accounts.accountId, balance: accounts.balance, seq: accounts.seq })
59
+ .from(accounts)
60
+ .where(eq(accounts.accountId, accountId))
61
+ .for('update');
62
+ return row ? { accountId: String(row.accountId), balance: row.balance, seq: row.seq } : null;
63
+ }
64
+ return {
65
+ ...reader(tx),
66
+ async lockAccount(accountId) {
67
+ // One round trip once the account exists; the insert only runs for a new one.
68
+ const locked = await selectForUpdate(accountId);
69
+ if (locked)
70
+ return locked;
71
+ const created = await tx
72
+ .insert(accounts)
73
+ .values({ accountId: accountId, balance: 0, seq: 0 })
74
+ .onConflictDoNothing({ target: accounts.accountId })
75
+ .returning({ accountId: accounts.accountId });
76
+ // Our own uncommitted insert is already ours; a concurrent creator's
77
+ // committed row is visible to the next statement under READ COMMITTED.
78
+ if (created.length === 1)
79
+ return { accountId, balance: 0, seq: 0 };
80
+ const row = await selectForUpdate(accountId);
81
+ if (!row)
82
+ throw new Error(`billing account ${accountId} vanished after insert-or-lock`);
83
+ return row;
84
+ },
85
+ async findReversalOf(entryId) {
86
+ const [row] = await tx.select().from(entries).where(eq(entries.reversesId, entryId));
87
+ return row ? toEntry(row) : null;
88
+ },
89
+ async appendEntry(entry) {
90
+ const inserted = await tx
91
+ .insert(entries)
92
+ .values({
93
+ id: entry.id,
94
+ accountId: entry.accountId,
95
+ seq: entry.seq,
96
+ delta: entry.delta,
97
+ balanceAfter: entry.balanceAfter,
98
+ kind: entry.kind,
99
+ reason: entry.reason,
100
+ idempotencyKey: entry.idempotencyKey,
101
+ sourceType: entry.sourceType,
102
+ sourceId: entry.sourceId,
103
+ reversesId: entry.reversesId,
104
+ meta: entry.meta,
105
+ createdAt: entry.createdAt,
106
+ })
107
+ .onConflictDoNothing()
108
+ .returning({ id: entries.id });
109
+ return { inserted: inserted.length === 1 };
110
+ },
111
+ async setAccountState(state) {
112
+ await tx
113
+ .update(accounts)
114
+ .set({ balance: state.balance, seq: state.seq, updatedAt: new Date() })
115
+ .where(eq(accounts.accountId, state.accountId));
116
+ },
117
+ };
118
+ };
119
+ return {
120
+ transaction: (fn) => db.transaction((tx) => fn(tx)),
121
+ bind,
122
+ reader: () => reader(db),
123
+ };
124
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The one entitlement resolver (design §4.7): "what plan and permissions does
3
+ * this account have now", from every term of every source. Pure — the host
4
+ * reads the account's terms (`termStore.reader().listTerms`) and the result
5
+ * is a function of those terms, the clock and the catalog.
6
+ */
7
+ import type { Catalog } from '../catalog/catalog.js';
8
+ import type { Term, TermSource } from '../terms/types.js';
9
+ export type EntitlementStatus = 'active' | 'grace' | 'free';
10
+ export type EntitlementWarningCode =
11
+ /** S5: two auto-renewing provider subscriptions bill the account. */
12
+ 'two_subscriptions'
13
+ /** The winning term's renewal failed; it is entitled until `graceUntil`. */
14
+ | 'past_due'
15
+ /** The winning credit term renews soon and the balance does not cover the live price (needs `balance`). */
16
+ | 'renewal_shortfall'
17
+ /** A lower plan takes over at renewal or at the end of the term (S3b). */
18
+ | 'scheduled_downgrade';
19
+ export interface EntitlementWarning {
20
+ code: EntitlementWarningCode;
21
+ termIds: string[];
22
+ }
23
+ export interface EntitlementRenewal {
24
+ auto: boolean;
25
+ at: Date;
26
+ /** The plan the renewal buys (`nextPlanKey ?? planKey`). */
27
+ plan: string;
28
+ /** Credit terms: the live credit price; provider terms: the provider's price snapshot. `null` when unknown. */
29
+ price: {
30
+ amountMinor: number;
31
+ unit: string;
32
+ } | null;
33
+ }
34
+ export interface Entitlement {
35
+ plan: string;
36
+ rank: number;
37
+ permissions: readonly string[];
38
+ quotas: Readonly<Record<string, number>>;
39
+ /** Per-period pool; only provider-funded terms carry one (A1). */
40
+ includedCredits: number | null;
41
+ /** The winning term; `null` on the free plan. */
42
+ term: Term | null;
43
+ source: TermSource | null;
44
+ status: EntitlementStatus;
45
+ /** When the winning term's entitlement ends unless renewed. */
46
+ endsAt: Date | null;
47
+ graceUntil: Date | null;
48
+ renewal: EntitlementRenewal | null;
49
+ warnings: EntitlementWarning[];
50
+ }
51
+ export interface ResolveOptions {
52
+ /** Market for the live renewal price of credit terms; default the term's own market. */
53
+ market?: string;
54
+ /** Credit balance, to flag `renewal_shortfall` on an auto-renewing credit term. */
55
+ balance?: number;
56
+ }
57
+ /**
58
+ * Until when a term entitles its account, or `null` when it does not at `now`.
59
+ *
60
+ * - `active` before its period end. An auto-renewing term past its end is
61
+ * still entitled for `graceDays` while the renewal (job or provider
62
+ * webhook) catches up — the renewal itself decides past_due.
63
+ * - `grace` until `graceUntil` (the period end when the provider sent none).
64
+ * - `past_due` only while `graceUntil` is ahead (a credit term's 3-day grace,
65
+ * AC15); a provider `past_due` without one is not entitled (§4.6).
66
+ * - `scheduled` once `startsAt` passed and before its period end, in case
67
+ * activation has not run yet.
68
+ */
69
+ export declare function entitledUntil(term: Term, now: Date, graceDays: number): Date | null;
70
+ export declare function isEntitled(term: Term, now: Date, graceDays: number): boolean;
71
+ /**
72
+ * Resolve the account's entitlement (S1: highest rank wins, then the later
73
+ * end, then the older term; quotas and permissions never sum). Terms naming a
74
+ * plan the catalog no longer has are ignored. No entitled term → the free plan.
75
+ */
76
+ export declare function resolveEntitlement(terms: readonly Term[], now: Date, catalog: Catalog, options?: ResolveOptions): Entitlement;
@@ -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,48 @@
1
+ import type { AccountId, BillingEvent } from '../domain/types.js';
2
+ import type { LedgerOps } from '../ledger/ledger.js';
3
+ import type { NormalizedEvent, PurchaseChangedEvent, PurchaseCompletedEvent, VerifiedDelivery } from '../providers/port.js';
4
+ import type { IngestTx } from './ports.js';
5
+ export type ApplyStatus = 'applied' | 'ignored' | 'needs_review';
6
+ export interface ApplyResult {
7
+ status: ApplyStatus;
8
+ reason?: string;
9
+ /** No session or purchase on this host owns the event (the `onUnmatched` hook may forward it). */
10
+ unmatched?: boolean;
11
+ /** Ledger events to emit after commit. */
12
+ events?: BillingEvent[];
13
+ /** Reversal facts for the host's shortfall policy. */
14
+ reversal?: PurchaseReversed;
15
+ }
16
+ export interface PurchaseReversed {
17
+ accountId: AccountId;
18
+ provider: string;
19
+ externalId: string;
20
+ /** Credits actually taken back. */
21
+ clawedBack: number;
22
+ /** Credits the balance could not cover. */
23
+ shortfall: number;
24
+ }
25
+ /** What a host handler gets for event kinds the library does not apply itself (P1: subscriptions). */
26
+ export interface ApplyContext<TTx = unknown> {
27
+ tx: TTx;
28
+ ledger: LedgerOps;
29
+ delivery: VerifiedDelivery;
30
+ now: Date;
31
+ }
32
+ export type EventHandler<TTx = unknown> = (event: NormalizedEvent, ctx: ApplyContext<TTx>) => Promise<ApplyResult>;
33
+ interface Deps {
34
+ tx: IngestTx;
35
+ ledger: LedgerOps;
36
+ delivery: VerifiedDelivery;
37
+ now: Date;
38
+ newId: () => string;
39
+ }
40
+ export declare function applyPurchaseCompleted(event: PurchaseCompletedEvent, d: Deps): Promise<ApplyResult>;
41
+ /**
42
+ * `purchase.reversed` / `purchase.reinstated`. Only an event newer than the
43
+ * purchase's watermark changes it, so redelivered or out-of-order events
44
+ * cannot regress state; whatever order capture, reversal and reinstatement
45
+ * arrive in, the purchase ends where the newest event puts it.
46
+ */
47
+ export declare function applyPurchaseChanged(event: PurchaseChangedEvent, d: Deps): Promise<ApplyResult>;
48
+ export {};