@nehorai/credits 2.2.0 → 3.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 (43) hide show
  1. package/dist/adapters/index.cjs +169 -155
  2. package/dist/adapters/index.cjs.map +1 -1
  3. package/dist/adapters/index.d.cts +2 -2
  4. package/dist/adapters/index.d.ts +2 -2
  5. package/dist/adapters/index.js +169 -155
  6. package/dist/adapters/index.js.map +1 -1
  7. package/dist/core/index.cjs +148 -24
  8. package/dist/core/index.cjs.map +1 -1
  9. package/dist/core/index.d.cts +113 -22
  10. package/dist/core/index.d.ts +113 -22
  11. package/dist/core/index.js +137 -22
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/index-BrogG0Gc.d.cts +277 -0
  14. package/dist/index-DOvJES2m.d.ts +277 -0
  15. package/dist/index.cjs +324 -71
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +5 -5
  18. package/dist/index.d.ts +5 -5
  19. package/dist/index.js +311 -69
  20. package/dist/index.js.map +1 -1
  21. package/dist/repository/index.cjs +254 -49
  22. package/dist/repository/index.cjs.map +1 -1
  23. package/dist/repository/index.d.cts +3 -254
  24. package/dist/repository/index.d.ts +3 -254
  25. package/dist/repository/index.js +254 -49
  26. package/dist/repository/index.js.map +1 -1
  27. package/dist/sdk/index.cjs +1 -0
  28. package/dist/sdk/index.cjs.map +1 -1
  29. package/dist/sdk/index.d.cts +2 -2
  30. package/dist/sdk/index.d.ts +2 -2
  31. package/dist/sdk/index.js +1 -0
  32. package/dist/sdk/index.js.map +1 -1
  33. package/dist/service/index.cjs +42 -19
  34. package/dist/service/index.cjs.map +1 -1
  35. package/dist/service/index.d.cts +2 -2
  36. package/dist/service/index.d.ts +2 -2
  37. package/dist/service/index.js +42 -19
  38. package/dist/service/index.js.map +1 -1
  39. package/dist/{types-3c-IAwZI.d.ts → types-BL3YqxUD.d.ts} +28 -6
  40. package/dist/{types-MaViK5tD.d.cts → types-C3sxDvNb.d.cts} +29 -6
  41. package/dist/{types-MaViK5tD.d.ts → types-C3sxDvNb.d.ts} +29 -6
  42. package/dist/{types-XSjNXO5l.d.cts → types-YLAB8bFk.d.cts} +28 -6
  43. package/package.json +1 -1
@@ -1,254 +1,3 @@
1
- import { I as ICreditRepository, b as AddCreditsV2Input, a as AddCreditsOutcome, m as ReservationTransitionOptions, C as CommitOutcome, R as ReleaseOutcome, n as ReserveCreditsV2Input, o as ReserveOutcome, g as CreditBalanceUpdate, h as CreditPolicyOptions, p as TierUpdateInput, d as CreateReservationInput, j as ExpireReservationV2Options, E as ExpireOutcome, A as AddCreditsAtomicOptions, e as CreateTransactionInput, f as CreateUsageLogInput, U as UsageLogQuery, c as CreateJournalEntryInput, J as JournalEntryQuery } from '../types-XSjNXO5l.cjs';
2
- export { i as CreditRepositoryFactory, k as ICreditRepositoryCreditsV2, l as ICreditRepositoryV2, t as reservationJournalKey, u as supportsCreditsV2, v as supportsIdempotentCredit, w as toClientUserCredits } from '../types-XSjNXO5l.cjs';
3
- import { c as PortableUserCredits, S as SubscriptionTier, a as PortableReservation, R as ReservationStatus, P as PortableTransaction, d as PortableUsageLog, f as PortableJournalEntry, M as MonthlyResetResult, e as SubscriptionExpiryResult } from '../types-MaViK5tD.cjs';
4
-
5
- /**
6
- * One reservation flow for both repository generations.
7
- *
8
- * Adapters that implement the V2 boundary get the idempotent, race-safe path
9
- * and own their journal entry. Adapters that do not (Firestore, custom
10
- * implementations) keep the legacy read-then-write path, with the service
11
- * writing the journal exactly as it always did — so upgrading this package
12
- * does not change their behaviour, and does not double-write anyone's ledger.
13
- */
14
-
15
- /**
16
- * Reserve credits through V2 when available.
17
- *
18
- * A legacy adapter cannot honour an idempotency key — it has no unique index
19
- * to enforce it — so asking for one there is a caller error rather than a
20
- * silently ignored option.
21
- */
22
- declare function reserveThroughRepository(repository: ICreditRepository, input: ReserveCreditsV2Input): Promise<ReserveOutcome>;
23
- /**
24
- * Commit through V2 when available, else the legacy read-then-write path.
25
- *
26
- * **The legacy path cannot promise a single winner.** It reads the status and
27
- * then writes, with no lock and no compare-and-set between the two, so two
28
- * concurrent commits of the same reservation can both observe `reserved` and
29
- * both proceed. The typed outcome still describes what *this* call saw, but on
30
- * a legacy adapter `committed` means "this call did the work", not "this call
31
- * was the only one that did". Callers needing exactly-once must use a
32
- * repository for which `supportsCreditsV2` returns `true`.
33
- */
34
- declare function commitThroughRepository(repository: ICreditRepository, userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<CommitOutcome>;
35
- /**
36
- * Release through V2 when available, else the legacy read-then-write path.
37
- *
38
- * Same caveat as {@link commitThroughRepository}: on a legacy adapter the
39
- * read-then-write sequence is unguarded, so `released` does not exclude a
40
- * concurrent commit having also run. Only V2 repositories serialise the two.
41
- */
42
- declare function releaseThroughRepository(repository: ICreditRepository, userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<ReleaseOutcome>;
43
- /**
44
- * Credit an account through the idempotent path when the adapter has one.
45
- *
46
- * A legacy adapter cannot resolve `created` / `replayed` / `conflict`: it has
47
- * no global unique index over `payment_ref`, so it cannot tell a re-delivered
48
- * webhook from a second, genuinely different payment that reuses a reference.
49
- * Rather than invent an outcome, this reports `created` — which is what the
50
- * legacy method actually did — and the ambiguity is documented on the return
51
- * type instead of hidden inside it.
52
- *
53
- * The reference is normalised here as well as in the adapters, so a legacy
54
- * adapter that stores the raw string does not persist a whitespace-only
55
- * reference that would then deduplicate nothing.
56
- */
57
- declare function addCreditsThroughRepository(repository: ICreditRepository, input: AddCreditsV2Input): Promise<AddCreditsOutcome>;
58
-
59
- /**
60
- * Shared utilities for credit repository implementations
61
- *
62
- * These are pure functions with no server-only dependencies,
63
- * making them safe to use in any repository implementation.
64
- */
65
-
66
- /**
67
- * Generate a unique ID
68
- * Uses timestamp + random string for uniqueness
69
- */
70
- declare function generateId(): string;
71
- /**
72
- * Convert date-like value to Date object
73
- * Handles: Date, string, Firestore Timestamp
74
- */
75
- declare function toDate(value: Date | string | unknown): Date;
76
- /**
77
- * Get the first day of next month
78
- * Used for calculating monthly reset dates
79
- */
80
- declare function getNextMonthlyReset(from?: Date): Date;
81
- /** Result of validating a balance update. */
82
- interface BalanceValidationResult {
83
- valid: boolean;
84
- errors: string[];
85
- }
86
- /**
87
- * Whether an update leaves a valid account: no negative field, and `reserved` covered
88
- * by `balance + bonusCredits`, which is the floor outstanding holds put under the
89
- * balance. An increment is applied on top of the absolute value when a call names both.
90
- *
91
- * An update is a delta the caller asked for, so one that cannot be honoured is refused,
92
- * as a deduct is. Only tier writes and resets stop at the floor: they state a target.
93
- *
94
- * A negative balance increment is a charge, so it draws only on the balance above
95
- * `expiredHoldBacking`: those credits are expired and leave when their hold closes, so
96
- * charging them would hand the charge back. An absolute balance replaces the field and
97
- * the marks with it, so only an increment on the stored balance meets this limit.
98
- */
99
- declare function validateBalanceUpdate(current: Pick<PortableUserCredits, "balance" | "bonusCredits" | "reserved" | "expiredHoldBacking">, updates: CreditBalanceUpdate): BalanceValidationResult;
100
- /** Refuse an update {@link validateBalanceUpdate} finds invalid. */
101
- declare function assertValidBalanceUpdate(current: Pick<PortableUserCredits, "balance" | "bonusCredits" | "reserved" | "expiredHoldBacking">, updates: CreditBalanceUpdate): void;
102
-
103
- /**
104
- * In-Memory Credit Repository Implementation
105
- *
106
- * A database-agnostic implementation of ICreditRepository for testing and prototyping.
107
- * All data is stored in memory and lost when the process restarts.
108
- *
109
- * Usage:
110
- * - Unit tests without database dependency
111
- * - Local development and prototyping
112
- * - Reference implementation for custom repositories
113
- */
114
-
115
- declare class InMemoryCreditRepository implements ICreditRepository {
116
- private readonly store;
117
- private readonly options;
118
- constructor(options?: CreditPolicyOptions);
119
- /**
120
- * A copy, never the live record.
121
- *
122
- * Handing out the stored object made this adapter behave unlike any real
123
- * one: a caller holding a "before" snapshot saw it mutate under them. The
124
- * service's monthly reset compared `resetResult.credits.balance` against the
125
- * balance it had read moments earlier, got zero because both were the same
126
- * object, and silently skipped the reset's journal entry — while the SQL
127
- * adapter, which maps each row into a fresh object, wrote it.
128
- */
129
- getUserCredits(userId: string): Promise<PortableUserCredits | null>;
130
- initializeUserCredits(userId: string, tier: SubscriptionTier, initialBalance: number): Promise<PortableUserCredits>;
131
- /**
132
- * The synchronous body of `initializeUserCredits`.
133
- *
134
- * Kept `await`-free on purpose: `addCreditsV2` seeds a missing user *inside*
135
- * its critical section, and an `await` between the payment-reference check
136
- * and the transaction write opens a gap another caller can run through — two
137
- * simultaneous first deliveries of the same reference would then both credit.
138
- */
139
- private seedUser;
140
- updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;
141
- updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;
142
- createReservation(input: CreateReservationInput): Promise<PortableReservation>;
143
- getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;
144
- updateReservationStatus(userId: string, reservationId: string, status: ReservationStatus, completedAt?: Date): Promise<void>;
145
- reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome>;
146
- commitReservationV2(userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<CommitOutcome>;
147
- releaseReservationV2(userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<ReleaseOutcome>;
148
- expireReservationV2(userId: string, reservationId: string, options?: ExpireReservationV2Options): Promise<ExpireOutcome>;
149
- reserveCreditsAtomic(userId: string, amount: number, operationType: string, expiresAt: Date): Promise<PortableReservation>;
150
- commitReservationAtomic(userId: string, reservationId: string): Promise<void>;
151
- releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;
152
- /**
153
- * The stored transaction carrying this reference, in *any* user's ledger.
154
- *
155
- * Deliberately not scoped to one user. The SQL adapter's unique index covers
156
- * `payment_ref` alone, so searching only the crediting user's own history made
157
- * the same reference credit two different accounts here while the SQL adapter
158
- * treated the second delivery as a duplicate. See `core/payment-ref.ts`.
159
- */
160
- private findByPaymentRef;
161
- /** The journal entry written alongside a stored purchase, if there is one. */
162
- private journalForTransaction;
163
- /**
164
- * Credit an account, resolving `paymentRef` to created / replayed / conflict.
165
- *
166
- * The reference is checked and the transaction is recorded with no `await`
167
- * between them. `createTransaction` is `async` but its body is synchronous, so
168
- * under JavaScript's run-to-completion semantics no other caller can observe
169
- * the gap — which is what stands in for the SQL adapter's unique index.
170
- *
171
- * A `replayed` or `conflict` outcome writes nothing at all: the check runs
172
- * before the balance moves, not after.
173
- */
174
- addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome>;
175
- /**
176
- * The legacy signature, on top of {@link addCreditsV2}.
177
- *
178
- * `Promise<void>` has nowhere to report a conflict, and silently returning is
179
- * indistinguishable from "credited" — the exact failure this round is closing
180
- * — so a conflict throws. A genuine replay still returns quietly, because
181
- * that *is* the idempotent no-op the caller asked for.
182
- */
183
- addCreditsAtomic(userId: string, amount: number, description: string, paymentRef?: string, options?: AddCreditsAtomicOptions): Promise<void>;
184
- deductCreditsAtomic(userId: string, amount: number): Promise<{
185
- previousBalance: number;
186
- newBalance: number;
187
- }>;
188
- createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;
189
- /** The unguarded writer, for `addCreditsV2` — which has moved the balance. */
190
- private recordTransaction;
191
- getTransactions(userId: string, limit?: number, offset?: number): Promise<PortableTransaction[]>;
192
- logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;
193
- getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;
194
- getUsageLogsCount(query: Omit<UsageLogQuery, "limit" | "offset">): Promise<number>;
195
- createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;
196
- /**
197
- * The synchronous body of `createJournalEntry`, so `atomicMonthlyReset` can
198
- * write its journal line inside the same run-to-completion step as the
199
- * balance write — an `await` between the two is exactly the gap that loses
200
- * the line when the second half fails.
201
- */
202
- private recordJournalEntry;
203
- getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;
204
- getJournalEntriesCount(query: Omit<JournalEntryQuery, "limit" | "offset">): Promise<number>;
205
- /**
206
- * Expire every hold whose deadline has passed.
207
- *
208
- * Each candidate goes through the guarded {@link expireReservationV2}, which
209
- * re-checks the status and the deadline under the user's lock. The previous
210
- * implementation released the hold and then overwrote the status to
211
- * `expired`, so a commit landing in between got its credits handed back and
212
- * was then relabelled.
213
- */
214
- findAndExpireReservations(_batchSize?: number, _maxIterations?: number): Promise<{
215
- expiredCount: number;
216
- creditsReleased: number;
217
- errors: string[];
218
- }>;
219
- /**
220
- * @param _tier - Not trusted. The caller read it earlier and the account may
221
- * have changed tier since, so the reset uses the tier stored on the account.
222
- */
223
- atomicMonthlyReset(userId: string, _tier: SubscriptionTier, expectedResetAt: Date | string): Promise<MonthlyResetResult>;
224
- checkAndHandleSubscriptionExpiry(userId: string, gracePeriodDays?: number): Promise<SubscriptionExpiryResult>;
225
- /**
226
- * Clear all data (useful for testing)
227
- */
228
- clear(): void;
229
- /**
230
- * Install a yield point inside every V2 critical section (testing only).
231
- *
232
- * Unset, the critical sections run start-to-finish synchronously, so
233
- * concurrent callers never interleave and a concurrency test would pass even
234
- * with the locking removed. Setting this to a real yield (a macrotask or a
235
- * barrier) makes callers genuinely overlap, so the tests exercise the lock
236
- * instead of the event loop. Never call this in production code.
237
- */
238
- setSchedulingHook(hook: (() => Promise<void>) | undefined): void;
239
- /**
240
- * Get all users (useful for testing/debugging)
241
- */
242
- getAllUsers(): PortableUserCredits[];
243
- /**
244
- * Get all reservations for a user (useful for testing)
245
- */
246
- getAllReservations(userId: string): PortableReservation[];
247
- }
248
- /**
249
- * Create a new in-memory repository instance
250
- * Each call creates a fresh, isolated instance
251
- */
252
- declare function createInMemoryCreditRepository(options?: CreditPolicyOptions): InMemoryCreditRepository;
253
-
254
- export { AddCreditsAtomicOptions, AddCreditsV2Input, type BalanceValidationResult, CreateJournalEntryInput, CreateReservationInput, CreateTransactionInput, CreateUsageLogInput, CreditBalanceUpdate, ExpireReservationV2Options, ICreditRepository, InMemoryCreditRepository, JournalEntryQuery, ReservationTransitionOptions, ReserveCreditsV2Input, TierUpdateInput, UsageLogQuery, addCreditsThroughRepository, assertValidBalanceUpdate, commitThroughRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset, releaseThroughRepository, reserveThroughRepository, toDate, validateBalanceUpdate };
1
+ export { A as AddCreditsAtomicOptions, b as AddCreditsV2Input, c as CreateJournalEntryInput, d as CreateReservationInput, e as CreateTransactionInput, f as CreateUsageLogInput, g as CreditBalanceUpdate, i as CreditRepositoryFactory, D as DeductJournalInput, j as ExpireReservationV2Options, I as ICreditRepository, k as ICreditRepositoryCreditsV2, l as ICreditRepositoryV2, J as JournalEntryQuery, m as ReservationTransitionOptions, n as ReserveCreditsV2Input, p as TierUpdateInput, U as UsageLogQuery, t as reservationJournalKey, u as supportsCreditsV2, v as supportsIdempotentCredit, w as toClientUserCredits } from '../types-YLAB8bFk.cjs';
2
+ export { B as BalanceValidationResult, I as InMemoryCreditRepository, a as addCreditsThroughRepository, b as assertValidBalanceUpdate, c as commitThroughRepository, d as createInMemoryCreditRepository, g as generateId, e as getNextMonthlyReset, r as releaseThroughRepository, f as reserveThroughRepository, h as toDate, v as validateBalanceUpdate } from '../index-BrogG0Gc.cjs';
3
+ import '../types-C3sxDvNb.cjs';
@@ -1,254 +1,3 @@
1
- import { I as ICreditRepository, b as AddCreditsV2Input, a as AddCreditsOutcome, m as ReservationTransitionOptions, C as CommitOutcome, R as ReleaseOutcome, n as ReserveCreditsV2Input, o as ReserveOutcome, g as CreditBalanceUpdate, h as CreditPolicyOptions, p as TierUpdateInput, d as CreateReservationInput, j as ExpireReservationV2Options, E as ExpireOutcome, A as AddCreditsAtomicOptions, e as CreateTransactionInput, f as CreateUsageLogInput, U as UsageLogQuery, c as CreateJournalEntryInput, J as JournalEntryQuery } from '../types-3c-IAwZI.js';
2
- export { i as CreditRepositoryFactory, k as ICreditRepositoryCreditsV2, l as ICreditRepositoryV2, t as reservationJournalKey, u as supportsCreditsV2, v as supportsIdempotentCredit, w as toClientUserCredits } from '../types-3c-IAwZI.js';
3
- import { c as PortableUserCredits, S as SubscriptionTier, a as PortableReservation, R as ReservationStatus, P as PortableTransaction, d as PortableUsageLog, f as PortableJournalEntry, M as MonthlyResetResult, e as SubscriptionExpiryResult } from '../types-MaViK5tD.js';
4
-
5
- /**
6
- * One reservation flow for both repository generations.
7
- *
8
- * Adapters that implement the V2 boundary get the idempotent, race-safe path
9
- * and own their journal entry. Adapters that do not (Firestore, custom
10
- * implementations) keep the legacy read-then-write path, with the service
11
- * writing the journal exactly as it always did — so upgrading this package
12
- * does not change their behaviour, and does not double-write anyone's ledger.
13
- */
14
-
15
- /**
16
- * Reserve credits through V2 when available.
17
- *
18
- * A legacy adapter cannot honour an idempotency key — it has no unique index
19
- * to enforce it — so asking for one there is a caller error rather than a
20
- * silently ignored option.
21
- */
22
- declare function reserveThroughRepository(repository: ICreditRepository, input: ReserveCreditsV2Input): Promise<ReserveOutcome>;
23
- /**
24
- * Commit through V2 when available, else the legacy read-then-write path.
25
- *
26
- * **The legacy path cannot promise a single winner.** It reads the status and
27
- * then writes, with no lock and no compare-and-set between the two, so two
28
- * concurrent commits of the same reservation can both observe `reserved` and
29
- * both proceed. The typed outcome still describes what *this* call saw, but on
30
- * a legacy adapter `committed` means "this call did the work", not "this call
31
- * was the only one that did". Callers needing exactly-once must use a
32
- * repository for which `supportsCreditsV2` returns `true`.
33
- */
34
- declare function commitThroughRepository(repository: ICreditRepository, userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<CommitOutcome>;
35
- /**
36
- * Release through V2 when available, else the legacy read-then-write path.
37
- *
38
- * Same caveat as {@link commitThroughRepository}: on a legacy adapter the
39
- * read-then-write sequence is unguarded, so `released` does not exclude a
40
- * concurrent commit having also run. Only V2 repositories serialise the two.
41
- */
42
- declare function releaseThroughRepository(repository: ICreditRepository, userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<ReleaseOutcome>;
43
- /**
44
- * Credit an account through the idempotent path when the adapter has one.
45
- *
46
- * A legacy adapter cannot resolve `created` / `replayed` / `conflict`: it has
47
- * no global unique index over `payment_ref`, so it cannot tell a re-delivered
48
- * webhook from a second, genuinely different payment that reuses a reference.
49
- * Rather than invent an outcome, this reports `created` — which is what the
50
- * legacy method actually did — and the ambiguity is documented on the return
51
- * type instead of hidden inside it.
52
- *
53
- * The reference is normalised here as well as in the adapters, so a legacy
54
- * adapter that stores the raw string does not persist a whitespace-only
55
- * reference that would then deduplicate nothing.
56
- */
57
- declare function addCreditsThroughRepository(repository: ICreditRepository, input: AddCreditsV2Input): Promise<AddCreditsOutcome>;
58
-
59
- /**
60
- * Shared utilities for credit repository implementations
61
- *
62
- * These are pure functions with no server-only dependencies,
63
- * making them safe to use in any repository implementation.
64
- */
65
-
66
- /**
67
- * Generate a unique ID
68
- * Uses timestamp + random string for uniqueness
69
- */
70
- declare function generateId(): string;
71
- /**
72
- * Convert date-like value to Date object
73
- * Handles: Date, string, Firestore Timestamp
74
- */
75
- declare function toDate(value: Date | string | unknown): Date;
76
- /**
77
- * Get the first day of next month
78
- * Used for calculating monthly reset dates
79
- */
80
- declare function getNextMonthlyReset(from?: Date): Date;
81
- /** Result of validating a balance update. */
82
- interface BalanceValidationResult {
83
- valid: boolean;
84
- errors: string[];
85
- }
86
- /**
87
- * Whether an update leaves a valid account: no negative field, and `reserved` covered
88
- * by `balance + bonusCredits`, which is the floor outstanding holds put under the
89
- * balance. An increment is applied on top of the absolute value when a call names both.
90
- *
91
- * An update is a delta the caller asked for, so one that cannot be honoured is refused,
92
- * as a deduct is. Only tier writes and resets stop at the floor: they state a target.
93
- *
94
- * A negative balance increment is a charge, so it draws only on the balance above
95
- * `expiredHoldBacking`: those credits are expired and leave when their hold closes, so
96
- * charging them would hand the charge back. An absolute balance replaces the field and
97
- * the marks with it, so only an increment on the stored balance meets this limit.
98
- */
99
- declare function validateBalanceUpdate(current: Pick<PortableUserCredits, "balance" | "bonusCredits" | "reserved" | "expiredHoldBacking">, updates: CreditBalanceUpdate): BalanceValidationResult;
100
- /** Refuse an update {@link validateBalanceUpdate} finds invalid. */
101
- declare function assertValidBalanceUpdate(current: Pick<PortableUserCredits, "balance" | "bonusCredits" | "reserved" | "expiredHoldBacking">, updates: CreditBalanceUpdate): void;
102
-
103
- /**
104
- * In-Memory Credit Repository Implementation
105
- *
106
- * A database-agnostic implementation of ICreditRepository for testing and prototyping.
107
- * All data is stored in memory and lost when the process restarts.
108
- *
109
- * Usage:
110
- * - Unit tests without database dependency
111
- * - Local development and prototyping
112
- * - Reference implementation for custom repositories
113
- */
114
-
115
- declare class InMemoryCreditRepository implements ICreditRepository {
116
- private readonly store;
117
- private readonly options;
118
- constructor(options?: CreditPolicyOptions);
119
- /**
120
- * A copy, never the live record.
121
- *
122
- * Handing out the stored object made this adapter behave unlike any real
123
- * one: a caller holding a "before" snapshot saw it mutate under them. The
124
- * service's monthly reset compared `resetResult.credits.balance` against the
125
- * balance it had read moments earlier, got zero because both were the same
126
- * object, and silently skipped the reset's journal entry — while the SQL
127
- * adapter, which maps each row into a fresh object, wrote it.
128
- */
129
- getUserCredits(userId: string): Promise<PortableUserCredits | null>;
130
- initializeUserCredits(userId: string, tier: SubscriptionTier, initialBalance: number): Promise<PortableUserCredits>;
131
- /**
132
- * The synchronous body of `initializeUserCredits`.
133
- *
134
- * Kept `await`-free on purpose: `addCreditsV2` seeds a missing user *inside*
135
- * its critical section, and an `await` between the payment-reference check
136
- * and the transaction write opens a gap another caller can run through — two
137
- * simultaneous first deliveries of the same reference would then both credit.
138
- */
139
- private seedUser;
140
- updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;
141
- updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;
142
- createReservation(input: CreateReservationInput): Promise<PortableReservation>;
143
- getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;
144
- updateReservationStatus(userId: string, reservationId: string, status: ReservationStatus, completedAt?: Date): Promise<void>;
145
- reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome>;
146
- commitReservationV2(userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<CommitOutcome>;
147
- releaseReservationV2(userId: string, reservationId: string, options?: ReservationTransitionOptions): Promise<ReleaseOutcome>;
148
- expireReservationV2(userId: string, reservationId: string, options?: ExpireReservationV2Options): Promise<ExpireOutcome>;
149
- reserveCreditsAtomic(userId: string, amount: number, operationType: string, expiresAt: Date): Promise<PortableReservation>;
150
- commitReservationAtomic(userId: string, reservationId: string): Promise<void>;
151
- releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;
152
- /**
153
- * The stored transaction carrying this reference, in *any* user's ledger.
154
- *
155
- * Deliberately not scoped to one user. The SQL adapter's unique index covers
156
- * `payment_ref` alone, so searching only the crediting user's own history made
157
- * the same reference credit two different accounts here while the SQL adapter
158
- * treated the second delivery as a duplicate. See `core/payment-ref.ts`.
159
- */
160
- private findByPaymentRef;
161
- /** The journal entry written alongside a stored purchase, if there is one. */
162
- private journalForTransaction;
163
- /**
164
- * Credit an account, resolving `paymentRef` to created / replayed / conflict.
165
- *
166
- * The reference is checked and the transaction is recorded with no `await`
167
- * between them. `createTransaction` is `async` but its body is synchronous, so
168
- * under JavaScript's run-to-completion semantics no other caller can observe
169
- * the gap — which is what stands in for the SQL adapter's unique index.
170
- *
171
- * A `replayed` or `conflict` outcome writes nothing at all: the check runs
172
- * before the balance moves, not after.
173
- */
174
- addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome>;
175
- /**
176
- * The legacy signature, on top of {@link addCreditsV2}.
177
- *
178
- * `Promise<void>` has nowhere to report a conflict, and silently returning is
179
- * indistinguishable from "credited" — the exact failure this round is closing
180
- * — so a conflict throws. A genuine replay still returns quietly, because
181
- * that *is* the idempotent no-op the caller asked for.
182
- */
183
- addCreditsAtomic(userId: string, amount: number, description: string, paymentRef?: string, options?: AddCreditsAtomicOptions): Promise<void>;
184
- deductCreditsAtomic(userId: string, amount: number): Promise<{
185
- previousBalance: number;
186
- newBalance: number;
187
- }>;
188
- createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;
189
- /** The unguarded writer, for `addCreditsV2` — which has moved the balance. */
190
- private recordTransaction;
191
- getTransactions(userId: string, limit?: number, offset?: number): Promise<PortableTransaction[]>;
192
- logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;
193
- getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;
194
- getUsageLogsCount(query: Omit<UsageLogQuery, "limit" | "offset">): Promise<number>;
195
- createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;
196
- /**
197
- * The synchronous body of `createJournalEntry`, so `atomicMonthlyReset` can
198
- * write its journal line inside the same run-to-completion step as the
199
- * balance write — an `await` between the two is exactly the gap that loses
200
- * the line when the second half fails.
201
- */
202
- private recordJournalEntry;
203
- getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;
204
- getJournalEntriesCount(query: Omit<JournalEntryQuery, "limit" | "offset">): Promise<number>;
205
- /**
206
- * Expire every hold whose deadline has passed.
207
- *
208
- * Each candidate goes through the guarded {@link expireReservationV2}, which
209
- * re-checks the status and the deadline under the user's lock. The previous
210
- * implementation released the hold and then overwrote the status to
211
- * `expired`, so a commit landing in between got its credits handed back and
212
- * was then relabelled.
213
- */
214
- findAndExpireReservations(_batchSize?: number, _maxIterations?: number): Promise<{
215
- expiredCount: number;
216
- creditsReleased: number;
217
- errors: string[];
218
- }>;
219
- /**
220
- * @param _tier - Not trusted. The caller read it earlier and the account may
221
- * have changed tier since, so the reset uses the tier stored on the account.
222
- */
223
- atomicMonthlyReset(userId: string, _tier: SubscriptionTier, expectedResetAt: Date | string): Promise<MonthlyResetResult>;
224
- checkAndHandleSubscriptionExpiry(userId: string, gracePeriodDays?: number): Promise<SubscriptionExpiryResult>;
225
- /**
226
- * Clear all data (useful for testing)
227
- */
228
- clear(): void;
229
- /**
230
- * Install a yield point inside every V2 critical section (testing only).
231
- *
232
- * Unset, the critical sections run start-to-finish synchronously, so
233
- * concurrent callers never interleave and a concurrency test would pass even
234
- * with the locking removed. Setting this to a real yield (a macrotask or a
235
- * barrier) makes callers genuinely overlap, so the tests exercise the lock
236
- * instead of the event loop. Never call this in production code.
237
- */
238
- setSchedulingHook(hook: (() => Promise<void>) | undefined): void;
239
- /**
240
- * Get all users (useful for testing/debugging)
241
- */
242
- getAllUsers(): PortableUserCredits[];
243
- /**
244
- * Get all reservations for a user (useful for testing)
245
- */
246
- getAllReservations(userId: string): PortableReservation[];
247
- }
248
- /**
249
- * Create a new in-memory repository instance
250
- * Each call creates a fresh, isolated instance
251
- */
252
- declare function createInMemoryCreditRepository(options?: CreditPolicyOptions): InMemoryCreditRepository;
253
-
254
- export { AddCreditsAtomicOptions, AddCreditsV2Input, type BalanceValidationResult, CreateJournalEntryInput, CreateReservationInput, CreateTransactionInput, CreateUsageLogInput, CreditBalanceUpdate, ExpireReservationV2Options, ICreditRepository, InMemoryCreditRepository, JournalEntryQuery, ReservationTransitionOptions, ReserveCreditsV2Input, TierUpdateInput, UsageLogQuery, addCreditsThroughRepository, assertValidBalanceUpdate, commitThroughRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset, releaseThroughRepository, reserveThroughRepository, toDate, validateBalanceUpdate };
1
+ export { A as AddCreditsAtomicOptions, b as AddCreditsV2Input, c as CreateJournalEntryInput, d as CreateReservationInput, e as CreateTransactionInput, f as CreateUsageLogInput, g as CreditBalanceUpdate, i as CreditRepositoryFactory, D as DeductJournalInput, j as ExpireReservationV2Options, I as ICreditRepository, k as ICreditRepositoryCreditsV2, l as ICreditRepositoryV2, J as JournalEntryQuery, m as ReservationTransitionOptions, n as ReserveCreditsV2Input, p as TierUpdateInput, U as UsageLogQuery, t as reservationJournalKey, u as supportsCreditsV2, v as supportsIdempotentCredit, w as toClientUserCredits } from '../types-BL3YqxUD.js';
2
+ export { B as BalanceValidationResult, I as InMemoryCreditRepository, a as addCreditsThroughRepository, b as assertValidBalanceUpdate, c as commitThroughRepository, d as createInMemoryCreditRepository, g as generateId, e as getNextMonthlyReset, r as releaseThroughRepository, f as reserveThroughRepository, h as toDate, v as validateBalanceUpdate } from '../index-DOvJES2m.js';
3
+ import '../types-C3sxDvNb.js';