@tofound/billing 0.0.0-stage → 0.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +3 -0
  3. package/README.md +34 -2
  4. package/dist/domain/errors.d.ts +14 -0
  5. package/dist/domain/errors.js +21 -0
  6. package/dist/domain/money.d.ts +21 -0
  7. package/dist/domain/money.js +77 -0
  8. package/dist/domain/types.d.ts +165 -0
  9. package/dist/domain/types.js +18 -0
  10. package/dist/drizzle/index.d.ts +3 -0
  11. package/dist/drizzle/index.js +3 -0
  12. package/dist/drizzle/schema-factory.d.ts +586 -0
  13. package/dist/drizzle/schema-factory.js +206 -0
  14. package/dist/drizzle/store.d.ts +20 -0
  15. package/dist/drizzle/store.js +124 -0
  16. package/dist/inbox/apply.d.ts +48 -0
  17. package/dist/inbox/apply.js +299 -0
  18. package/dist/inbox/conformance.d.ts +20 -0
  19. package/dist/inbox/conformance.js +254 -0
  20. package/dist/inbox/drizzle.d.ts +14 -0
  21. package/dist/inbox/drizzle.js +203 -0
  22. package/dist/inbox/ingest.d.ts +108 -0
  23. package/dist/inbox/ingest.js +404 -0
  24. package/dist/inbox/memory.d.ts +13 -0
  25. package/dist/inbox/memory.js +172 -0
  26. package/dist/inbox/ports.d.ts +150 -0
  27. package/dist/inbox/ports.js +1 -0
  28. package/dist/inbox/redact.d.ts +2 -0
  29. package/dist/inbox/redact.js +47 -0
  30. package/dist/inbox/schema.d.ts +1158 -0
  31. package/dist/inbox/schema.js +90 -0
  32. package/dist/inbox/watermark.d.ts +13 -0
  33. package/dist/inbox/watermark.js +6 -0
  34. package/dist/index.d.ts +20 -0
  35. package/dist/index.js +18 -0
  36. package/dist/ledger/ledger.d.ts +47 -0
  37. package/dist/ledger/ledger.js +224 -0
  38. package/dist/ports/index.d.ts +2 -0
  39. package/dist/ports/index.js +1 -0
  40. package/dist/ports/ledger-store.d.ts +53 -0
  41. package/dist/ports/ledger-store.js +1 -0
  42. package/dist/ports/runtime.d.ts +9 -0
  43. package/dist/ports/runtime.js +1 -0
  44. package/dist/providers/port.d.ts +201 -0
  45. package/dist/providers/port.js +30 -0
  46. package/dist/providers/sepay/index.d.ts +34 -0
  47. package/dist/providers/sepay/index.js +241 -0
  48. package/dist/providers/sepay/order.d.ts +32 -0
  49. package/dist/providers/sepay/order.js +69 -0
  50. package/dist/providers/sepay/signature.d.ts +8 -0
  51. package/dist/providers/sepay/signature.js +51 -0
  52. package/dist/quote/conformance.d.ts +16 -0
  53. package/dist/quote/conformance.js +39 -0
  54. package/dist/quote/index.d.ts +3 -0
  55. package/dist/quote/index.js +3 -0
  56. package/dist/quote/steps.d.ts +54 -0
  57. package/dist/quote/steps.js +103 -0
  58. package/dist/quote/waterfall.d.ts +98 -0
  59. package/dist/quote/waterfall.js +82 -0
  60. package/dist/stores/conformance.d.ts +22 -0
  61. package/dist/stores/conformance.js +269 -0
  62. package/dist/stores/memory.d.ts +19 -0
  63. package/dist/stores/memory.js +137 -0
  64. package/dist/stores/testing.d.ts +11 -0
  65. package/dist/stores/testing.js +11 -0
  66. package/docs/API.md +198 -0
  67. package/docs/SCHEMA.md +108 -0
  68. package/package.json +75 -4
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Persistence port of the webhook inbox, checkout sessions and purchases.
3
+ *
4
+ * Like `LedgerStore`, a store exposes its native transaction type, and the
5
+ * ingest service hands that same transaction to `ledger.in(tx)`, so the
6
+ * inbox row, the purchase and the ledger entry commit together. Both
7
+ * implementations (memory, Drizzle) pass `ingestConformanceCases`.
8
+ *
9
+ * Lock order (design §4.3): inbox row → checkout session → purchase →
10
+ * account (taken by the ledger, last).
11
+ */
12
+ import type { AccountId, Money } from '../domain/types.js';
13
+ import type { ProviderEnvironment, ProviderId } from '../providers/port.js';
14
+ /**
15
+ * - `received`: stored, not yet processed (or a crash mid-apply; re-entered).
16
+ * - `applied` / `ignored`: final; a redelivery is answered `duplicate`.
17
+ * - `needs_review`: authentic but unusable; final until a manual replay.
18
+ * - `failed`: transient error; retried when `nextAttemptAt` is due.
19
+ * - `dead`: retry budget spent; final until a manual replay.
20
+ */
21
+ export type InboxStatus = 'received' | 'applied' | 'ignored' | 'needs_review' | 'failed' | 'dead';
22
+ export declare const FINAL_INBOX_STATUSES: ReadonlySet<InboxStatus>;
23
+ export interface InboxRow {
24
+ id: string;
25
+ provider: ProviderId;
26
+ environment: ProviderEnvironment;
27
+ eventId: string;
28
+ eventType: string;
29
+ subjectRef: string | null;
30
+ status: InboxStatus;
31
+ /** Processing attempts so far. */
32
+ attempts: number;
33
+ /** How many times the provider (or a poll) delivered this event. */
34
+ deliveryCount: number;
35
+ /** When the sweeper should pick the row up; null = not due (final, or redelivery-only). */
36
+ nextAttemptAt: Date | null;
37
+ lastError: string | null;
38
+ /** Outcome reason code (`no_match`, `amount_mismatch`, `late_expired` …). */
39
+ reason: string | null;
40
+ /** The redacted payload — the only copy kept, and what replay normalizes. */
41
+ payload: unknown;
42
+ occurredAt: Date;
43
+ receivedAt: Date;
44
+ lastReceivedAt: Date;
45
+ processedAt: Date | null;
46
+ }
47
+ export type InboxPatch = Partial<Pick<InboxRow, 'status' | 'attempts' | 'nextAttemptAt' | 'lastError' | 'reason' | 'processedAt'>>;
48
+ /**
49
+ * A server-issued checkout: the provider reference (SePay invoice, Polar
50
+ * metadata) is its id. Amount and credits come from the host's catalog when
51
+ * the session is created; the provider must later report the same amount.
52
+ */
53
+ export type CheckoutSessionStatus = 'pending' | 'completed' | 'expired' | 'cancelled' | 'voided';
54
+ export interface CheckoutSession {
55
+ id: string;
56
+ accountId: AccountId;
57
+ provider: ProviderId;
58
+ environment: ProviderEnvironment;
59
+ status: CheckoutSessionStatus;
60
+ amount: Money;
61
+ /** Credit minor units granted on payment. */
62
+ credits: number;
63
+ productRef: string | null;
64
+ /** The provider's purchase id once captured. */
65
+ externalId: string | null;
66
+ expiresAt: Date;
67
+ completedAt: Date | null;
68
+ meta: Record<string, unknown> | null;
69
+ createdAt: Date;
70
+ updatedAt: Date;
71
+ }
72
+ export type CheckoutSessionPatch = Partial<Pick<CheckoutSession, 'status' | 'externalId' | 'completedAt'>>;
73
+ /**
74
+ * One provider purchase, forward-only: `completed → reversed ⇄ reinstated`,
75
+ * the newest reversal/reinstatement winning (watermark). A purchase can be
76
+ * born `reversed` or `reinstated` when that event outruns its capture: a
77
+ * capture then credits only if the latest word is `reinstated`; under a
78
+ * reversal it is parked (`meta.pendingCredit`) for a later reinstatement.
79
+ */
80
+ export type PurchaseStatus = 'completed' | 'reversed' | 'reinstated';
81
+ export interface Purchase {
82
+ id: string;
83
+ accountId: AccountId;
84
+ provider: ProviderId;
85
+ environment: ProviderEnvironment;
86
+ externalId: string;
87
+ checkoutSessionId: string | null;
88
+ status: PurchaseStatus;
89
+ amount: Money;
90
+ /** Credit minor units granted by the capture; 0 until credited. */
91
+ credits: number;
92
+ /** The crediting entry the next reversal counters (the top-up, then a reinstatement). */
93
+ creditEntryId: string | null;
94
+ /** What the latest reversal actually took back. */
95
+ clawedBack: number;
96
+ /** What the latest reversal could not take back (balance already spent). */
97
+ shortfall: number;
98
+ reversals: number;
99
+ /** Watermark of reversal/reinstatement events: newest wins. */
100
+ lastEventAt: Date | null;
101
+ lastEventRef: string | null;
102
+ meta: Record<string, unknown> | null;
103
+ createdAt: Date;
104
+ updatedAt: Date;
105
+ }
106
+ export type PurchasePatch = Partial<Pick<Purchase, 'status' | 'credits' | 'creditEntryId' | 'clawedBack' | 'shortfall' | 'reversals' | 'lastEventAt' | 'lastEventRef' | 'meta'>>;
107
+ export interface InboxListOptions {
108
+ statuses?: readonly InboxStatus[];
109
+ limit: number;
110
+ /** Only rows received strictly before this instant (older pages). */
111
+ receivedBefore?: Date;
112
+ }
113
+ export interface IngestReader {
114
+ getInbox(provider: ProviderId, eventId: string): Promise<InboxRow | null>;
115
+ /** Newest first. */
116
+ listInbox(options: InboxListOptions): Promise<InboxRow[]>;
117
+ /** `received`/`failed` rows with `nextAttemptAt <= now`, oldest due first; only `providers` when given. */
118
+ listDue(now: Date, limit: number, providers?: readonly ProviderId[]): Promise<InboxRow[]>;
119
+ getSession(id: string): Promise<CheckoutSession | null>;
120
+ getPurchase(provider: ProviderId, environment: ProviderEnvironment, externalId: string): Promise<Purchase | null>;
121
+ }
122
+ export interface IngestTx extends IngestReader {
123
+ /**
124
+ * Insert the row, or — when `(provider, eventId)` exists — count the
125
+ * delivery on the existing one (`deliveryCount + 1`, `lastReceivedAt`).
126
+ * Never throws on the conflict.
127
+ */
128
+ receive(row: InboxRow): Promise<{
129
+ row: InboxRow;
130
+ inserted: boolean;
131
+ }>;
132
+ /** `SELECT … FOR UPDATE`. */
133
+ lockInbox(provider: ProviderId, eventId: string): Promise<InboxRow | null>;
134
+ updateInbox(id: string, patch: InboxPatch): Promise<void>;
135
+ insertSession(session: CheckoutSession): Promise<void>;
136
+ lockSession(id: string): Promise<CheckoutSession | null>;
137
+ updateSession(id: string, patch: CheckoutSessionPatch): Promise<void>;
138
+ lockPurchase(provider: ProviderId, environment: ProviderEnvironment, externalId: string): Promise<Purchase | null>;
139
+ /** Unique `(provider, environment, externalId)`; a conflict answers `{inserted:false}`. */
140
+ insertPurchase(purchase: Purchase): Promise<{
141
+ inserted: boolean;
142
+ }>;
143
+ updatePurchase(id: string, patch: PurchasePatch): Promise<void>;
144
+ }
145
+ export interface IngestStore<TTx = unknown> {
146
+ /** Must be the same transaction the paired `LedgerStore` runs in. */
147
+ transaction<T>(fn: (tx: TTx) => Promise<T>): Promise<T>;
148
+ bind(tx: TTx): IngestTx;
149
+ reader(): IngestReader;
150
+ }
@@ -0,0 +1 @@
1
+ export const FINAL_INBOX_STATUSES = new Set(['applied', 'ignored', 'needs_review', 'dead']);
@@ -0,0 +1,2 @@
1
+ export declare function isSensitiveKey(key: string): boolean;
2
+ export declare function redactPayload(value: unknown): unknown;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Inbox payloads are stored redacted (design §6, §12): any key naming
3
+ * personal data or a credential is dropped, at any depth. Matching is per
4
+ * word of the key (`customer_email`, `payerName`, `purchaseToken` …), so
5
+ * `order_invoice_number` or `order_amount` survive.
6
+ */
7
+ const SENSITIVE_WORDS = new Set([
8
+ 'email',
9
+ 'mail',
10
+ 'name',
11
+ 'phone',
12
+ 'mobile',
13
+ 'address',
14
+ 'token',
15
+ 'secret',
16
+ 'password',
17
+ 'signature',
18
+ 'card',
19
+ 'pan',
20
+ 'cvv',
21
+ 'ip',
22
+ 'dob',
23
+ 'birthday',
24
+ ]);
25
+ function words(key) {
26
+ return key
27
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
28
+ .toLowerCase()
29
+ .split(/[^a-z0-9]+/)
30
+ .filter(Boolean);
31
+ }
32
+ export function isSensitiveKey(key) {
33
+ return words(key).some((w) => SENSITIVE_WORDS.has(w));
34
+ }
35
+ export function redactPayload(value) {
36
+ if (Array.isArray(value))
37
+ return value.map(redactPayload);
38
+ if (value && typeof value === 'object') {
39
+ const out = {};
40
+ for (const [key, inner] of Object.entries(value)) {
41
+ if (!isSensitiveKey(key))
42
+ out[key] = redactPayload(inner);
43
+ }
44
+ return out;
45
+ }
46
+ return value;
47
+ }