@nehorai/credits 1.0.2 → 1.3.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 (134) hide show
  1. package/dist/adapters/index.cjs +463 -0
  2. package/dist/adapters/index.cjs.map +1 -0
  3. package/dist/adapters/index.d.cts +66 -0
  4. package/dist/adapters/index.d.ts +66 -3
  5. package/dist/adapters/index.js +435 -1
  6. package/dist/adapters/index.js.map +1 -1
  7. package/dist/auth/index.cjs +96 -0
  8. package/dist/auth/index.cjs.map +1 -0
  9. package/dist/auth/{api-key.d.ts → index.d.cts} +9 -6
  10. package/dist/auth/index.d.ts +37 -5
  11. package/dist/auth/index.js +65 -7
  12. package/dist/auth/index.js.map +1 -1
  13. package/dist/core/index.cjs +522 -0
  14. package/dist/core/index.cjs.map +1 -0
  15. package/dist/core/index.d.cts +119 -0
  16. package/dist/core/index.d.ts +115 -25
  17. package/dist/core/index.js +475 -27
  18. package/dist/core/index.js.map +1 -1
  19. package/dist/{core/deferred.d.ts → deferred-C7rrRfkm.d.cts} +7 -6
  20. package/dist/{core/deferred.js → deferred-C7rrRfkm.d.ts} +23 -29
  21. package/dist/index.cjs +2506 -0
  22. package/dist/index.cjs.map +1 -0
  23. package/dist/index.d.cts +437 -0
  24. package/dist/index.d.ts +429 -49
  25. package/dist/index.js +2399 -62
  26. package/dist/index.js.map +1 -1
  27. package/dist/repository/index.cjs +816 -0
  28. package/dist/repository/index.cjs.map +1 -0
  29. package/dist/repository/{memory/index.d.ts → index.d.cts} +35 -5
  30. package/dist/repository/index.d.ts +97 -7
  31. package/dist/repository/index.js +783 -10
  32. package/dist/repository/index.js.map +1 -1
  33. package/dist/sdk/index.cjs +608 -0
  34. package/dist/sdk/index.cjs.map +1 -0
  35. package/dist/sdk/index.d.cts +495 -0
  36. package/dist/sdk/index.d.ts +491 -9
  37. package/dist/sdk/index.js +568 -12
  38. package/dist/sdk/index.js.map +1 -1
  39. package/dist/service/index.cjs +670 -0
  40. package/dist/service/index.cjs.map +1 -0
  41. package/dist/service/{credits-service.d.ts → index.d.cts} +9 -7
  42. package/dist/service/index.d.ts +141 -3
  43. package/dist/service/index.js +641 -1
  44. package/dist/service/index.js.map +1 -1
  45. package/dist/{core/types.d.ts → types-BBxIWHK2.d.cts} +25 -35
  46. package/dist/types-BBxIWHK2.d.ts +277 -0
  47. package/dist/types-D1vdeBcA.d.cts +305 -0
  48. package/dist/{auth/types.d.ts → types-OZU3I5OM.d.cts} +5 -4
  49. package/dist/types-OZU3I5OM.d.ts +32 -0
  50. package/dist/{repository/types.d.ts → types-aJsyv8df.d.ts} +35 -13
  51. package/package.json +14 -13
  52. package/dist/adapters/generic.d.ts +0 -18
  53. package/dist/adapters/generic.d.ts.map +0 -1
  54. package/dist/adapters/generic.js +0 -147
  55. package/dist/adapters/generic.js.map +0 -1
  56. package/dist/adapters/index.d.ts.map +0 -1
  57. package/dist/adapters/types.d.ts +0 -45
  58. package/dist/adapters/types.d.ts.map +0 -1
  59. package/dist/adapters/types.js +0 -8
  60. package/dist/adapters/types.js.map +0 -1
  61. package/dist/auth/api-key.d.ts.map +0 -1
  62. package/dist/auth/api-key.js +0 -94
  63. package/dist/auth/api-key.js.map +0 -1
  64. package/dist/auth/index.d.ts.map +0 -1
  65. package/dist/auth/types.d.ts.map +0 -1
  66. package/dist/auth/types.js +0 -2
  67. package/dist/auth/types.js.map +0 -1
  68. package/dist/config/costs.d.ts +0 -61
  69. package/dist/config/costs.d.ts.map +0 -1
  70. package/dist/config/costs.js +0 -86
  71. package/dist/config/costs.js.map +0 -1
  72. package/dist/config/index.d.ts +0 -165
  73. package/dist/config/index.d.ts.map +0 -1
  74. package/dist/config/index.js +0 -286
  75. package/dist/config/index.js.map +0 -1
  76. package/dist/core/deferred.d.ts.map +0 -1
  77. package/dist/core/deferred.js.map +0 -1
  78. package/dist/core/errors.d.ts +0 -78
  79. package/dist/core/errors.d.ts.map +0 -1
  80. package/dist/core/errors.js +0 -110
  81. package/dist/core/errors.js.map +0 -1
  82. package/dist/core/index.d.ts.map +0 -1
  83. package/dist/core/operations.d.ts +0 -36
  84. package/dist/core/operations.d.ts.map +0 -1
  85. package/dist/core/operations.js +0 -87
  86. package/dist/core/operations.js.map +0 -1
  87. package/dist/core/types.d.ts.map +0 -1
  88. package/dist/core/types.js +0 -93
  89. package/dist/core/types.js.map +0 -1
  90. package/dist/index.d.ts.map +0 -1
  91. package/dist/notifications/index.d.ts +0 -76
  92. package/dist/notifications/index.d.ts.map +0 -1
  93. package/dist/notifications/index.js +0 -182
  94. package/dist/notifications/index.js.map +0 -1
  95. package/dist/repository/index.d.ts.map +0 -1
  96. package/dist/repository/memory/index.d.ts.map +0 -1
  97. package/dist/repository/memory/index.js +0 -518
  98. package/dist/repository/memory/index.js.map +0 -1
  99. package/dist/repository/types.d.ts.map +0 -1
  100. package/dist/repository/types.js +0 -39
  101. package/dist/repository/types.js.map +0 -1
  102. package/dist/repository/utils.d.ts +0 -22
  103. package/dist/repository/utils.d.ts.map +0 -1
  104. package/dist/repository/utils.js +0 -40
  105. package/dist/repository/utils.js.map +0 -1
  106. package/dist/sdk/admin-client.d.ts +0 -146
  107. package/dist/sdk/admin-client.d.ts.map +0 -1
  108. package/dist/sdk/admin-client.js +0 -196
  109. package/dist/sdk/admin-client.js.map +0 -1
  110. package/dist/sdk/client.d.ts +0 -144
  111. package/dist/sdk/client.d.ts.map +0 -1
  112. package/dist/sdk/client.js +0 -247
  113. package/dist/sdk/client.js.map +0 -1
  114. package/dist/sdk/errors.d.ts +0 -91
  115. package/dist/sdk/errors.d.ts.map +0 -1
  116. package/dist/sdk/errors.js +0 -185
  117. package/dist/sdk/errors.js.map +0 -1
  118. package/dist/sdk/index.d.ts.map +0 -1
  119. package/dist/sdk/types.d.ts +0 -110
  120. package/dist/sdk/types.d.ts.map +0 -1
  121. package/dist/sdk/types.js +0 -20
  122. package/dist/sdk/types.js.map +0 -1
  123. package/dist/service/credits-service.d.ts.map +0 -1
  124. package/dist/service/credits-service.js +0 -372
  125. package/dist/service/credits-service.js.map +0 -1
  126. package/dist/service/index.d.ts.map +0 -1
  127. package/dist/utils/error-utils.d.ts +0 -48
  128. package/dist/utils/error-utils.d.ts.map +0 -1
  129. package/dist/utils/error-utils.js +0 -57
  130. package/dist/utils/error-utils.js.map +0 -1
  131. package/dist/utils/index.d.ts +0 -54
  132. package/dist/utils/index.d.ts.map +0 -1
  133. package/dist/utils/index.js +0 -72
  134. package/dist/utils/index.js.map +0 -1
@@ -0,0 +1,437 @@
1
+ import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-BBxIWHK2.cjs';
2
+ export { A as AIProviderType, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-BBxIWHK2.cjs';
3
+ export { CreditError, CreditErrorCode, CreditErrorCodeType, commitReservationWithJournal, createInsufficientCreditsError, createInvalidOperationTypeError, createReservationAlreadyProcessedError, createReservationExpiredError, createReservationNotFoundError, createUserNotFoundError, isCreditError, isInsufficientCreditsError, releaseReservationWithJournal, reserveCreditsForOperation } from './core/index.cjs';
4
+ export { D as DeferredExecutor, c as createDeferredExecutor, g as genericDeferred, n as noopDeferred, s as synchronousDeferred } from './deferred-C7rrRfkm.cjs';
5
+ import { z } from 'zod';
6
+ export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-D1vdeBcA.cjs';
7
+ export { InMemoryCreditRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset } from './repository/index.cjs';
8
+ export { C as CreditsAuthProviderFactory, a as CreditsUser, I as ICreditsAuthProvider } from './types-OZU3I5OM.cjs';
9
+ export { ApiKeyCreditsProvider, createApiKeyProvider, verifyAdminApiKey, verifyBearerToken } from './auth/index.cjs';
10
+ export { CreditsService, LowBalanceNotificationCallback, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.cjs';
11
+ export { ActionResult, CreditActionHandler, CreditsAdapter, CreditsAdapterConfig, createGenericAdapter } from './adapters/index.cjs';
12
+ export { AdminCreditsClient, AdminCreditsClientConfig, ApiResponse, AuthenticationError, AuthorizationError, CreditsClient, CreditsClientConfig, CreditsConfig, CreditsSDKError, ListUsersOptions, ListUsersResponse, NetworkError, PaginationOptions, ReservationResult, SDKErrorCode, SDKErrorCodeType, InsufficientCreditsError as SDKInsufficientCreditsError, ReservationExpiredError as SDKReservationExpiredError, ReservationNotFoundError as SDKReservationNotFoundError, UsageHistoryEntry as SDKUsageHistoryEntry, UsageHistoryResponse as SDKUsageHistoryResponse, ServerError, ValidationError, parseApiError } from './sdk/index.cjs';
13
+
14
+ /**
15
+ * Schema for credit system configuration
16
+ */
17
+ declare const creditSystemConfigSchema: z.ZodObject<{
18
+ /**
19
+ * Operation costs in credits
20
+ * Keys are operation type names (any non-empty string)
21
+ * Values are positive numbers representing credit cost
22
+ */
23
+ operationCosts: z.ZodRecord<z.ZodString, z.ZodNumber>;
24
+ /**
25
+ * Display labels for operation types (English canonical labels).
26
+ * Falls back to auto-generating from snake_case keys if not provided.
27
+ */
28
+ operationLabels: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
29
+ /**
30
+ * Tier configurations
31
+ */
32
+ tierConfigs: z.ZodRecord<z.ZodEnum<["free", "basic", "premium", "unlimited"]>, z.ZodObject<{
33
+ tier: z.ZodEnum<["free", "basic", "premium", "unlimited"]>;
34
+ monthlyCredits: z.ZodNumber;
35
+ priceUsd: z.ZodNumber;
36
+ features: z.ZodArray<z.ZodString, "many">;
37
+ }, "strip", z.ZodTypeAny, {
38
+ tier: "free" | "basic" | "premium" | "unlimited";
39
+ monthlyCredits: number;
40
+ priceUsd: number;
41
+ features: string[];
42
+ }, {
43
+ tier: "free" | "basic" | "premium" | "unlimited";
44
+ monthlyCredits: number;
45
+ priceUsd: number;
46
+ features: string[];
47
+ }>>;
48
+ /**
49
+ * Reservation expiry time in milliseconds
50
+ */
51
+ reservationExpiryMs: z.ZodDefault<z.ZodNumber>;
52
+ /**
53
+ * Default credits for new users (free tier)
54
+ */
55
+ defaultFreeCredits: z.ZodDefault<z.ZodNumber>;
56
+ /**
57
+ * Grace period in days after subscription expires before downgrade
58
+ */
59
+ subscriptionGracePeriodDays: z.ZodDefault<z.ZodNumber>;
60
+ /**
61
+ * Low balance notification threshold
62
+ */
63
+ lowBalanceThreshold: z.ZodDefault<z.ZodNumber>;
64
+ /**
65
+ * Cooldown in hours between low balance notifications
66
+ */
67
+ lowBalanceNotificationCooldownHours: z.ZodDefault<z.ZodNumber>;
68
+ /**
69
+ * Feature flags for optional features
70
+ */
71
+ features: z.ZodDefault<z.ZodObject<{
72
+ journalEntries: z.ZodDefault<z.ZodBoolean>;
73
+ notifications: z.ZodDefault<z.ZodBoolean>;
74
+ subscriptionExpiry: z.ZodDefault<z.ZodBoolean>;
75
+ usageHistory: z.ZodDefault<z.ZodBoolean>;
76
+ }, "strip", z.ZodTypeAny, {
77
+ journalEntries: boolean;
78
+ notifications: boolean;
79
+ subscriptionExpiry: boolean;
80
+ usageHistory: boolean;
81
+ }, {
82
+ journalEntries?: boolean | undefined;
83
+ notifications?: boolean | undefined;
84
+ subscriptionExpiry?: boolean | undefined;
85
+ usageHistory?: boolean | undefined;
86
+ }>>;
87
+ }, "strip", z.ZodTypeAny, {
88
+ operationCosts: Record<string, number>;
89
+ operationLabels: Record<string, string>;
90
+ tierConfigs: Partial<Record<"free" | "basic" | "premium" | "unlimited", {
91
+ tier: "free" | "basic" | "premium" | "unlimited";
92
+ monthlyCredits: number;
93
+ priceUsd: number;
94
+ features: string[];
95
+ }>>;
96
+ features: {
97
+ journalEntries: boolean;
98
+ notifications: boolean;
99
+ subscriptionExpiry: boolean;
100
+ usageHistory: boolean;
101
+ };
102
+ reservationExpiryMs: number;
103
+ defaultFreeCredits: number;
104
+ subscriptionGracePeriodDays: number;
105
+ lowBalanceThreshold: number;
106
+ lowBalanceNotificationCooldownHours: number;
107
+ }, {
108
+ operationCosts: Record<string, number>;
109
+ tierConfigs: Partial<Record<"free" | "basic" | "premium" | "unlimited", {
110
+ tier: "free" | "basic" | "premium" | "unlimited";
111
+ monthlyCredits: number;
112
+ priceUsd: number;
113
+ features: string[];
114
+ }>>;
115
+ operationLabels?: Record<string, string> | undefined;
116
+ features?: {
117
+ journalEntries?: boolean | undefined;
118
+ notifications?: boolean | undefined;
119
+ subscriptionExpiry?: boolean | undefined;
120
+ usageHistory?: boolean | undefined;
121
+ } | undefined;
122
+ reservationExpiryMs?: number | undefined;
123
+ defaultFreeCredits?: number | undefined;
124
+ subscriptionGracePeriodDays?: number | undefined;
125
+ lowBalanceThreshold?: number | undefined;
126
+ lowBalanceNotificationCooldownHours?: number | undefined;
127
+ }>;
128
+ /**
129
+ * Credit system configuration type
130
+ */
131
+ type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;
132
+ /**
133
+ * Load configuration from environment variables
134
+ * Can be extended to load from other sources (file, remote config, etc.)
135
+ *
136
+ * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:
137
+ * CREDITS_OPERATION_COSTS={"story_generation":5,"image_generation":10}
138
+ */
139
+ declare function loadConfigFromEnv(): Partial<CreditSystemConfig>;
140
+ /**
141
+ * Initialize configuration
142
+ * Merges default config with environment overrides
143
+ */
144
+ declare function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig;
145
+ /**
146
+ * Get the current configuration.
147
+ * If an external provider is registered, delegates to it.
148
+ * Otherwise falls back to the local currentConfig.
149
+ */
150
+ declare function getConfig(): CreditSystemConfig;
151
+ /**
152
+ * Get all valid operation types from configuration
153
+ * Returns the keys of the operationCosts object
154
+ */
155
+ declare function getValidOperationTypes(): string[];
156
+ /**
157
+ * Check if an operation type is valid (configured in the system)
158
+ * @param type - The operation type to check
159
+ * @returns true if the operation type is configured
160
+ */
161
+ declare function isValidOperationType(type: string): boolean;
162
+ /**
163
+ * Get operation cost from configuration
164
+ * @throws Error if the operation type is not configured
165
+ */
166
+ declare function getConfigOperationCost(operationType: string): number;
167
+ /**
168
+ * Get tier configuration from configuration
169
+ */
170
+ declare function getConfigTierConfig(tier: SubscriptionTier): TierConfig;
171
+ /**
172
+ * Get monthly limit for a tier from configuration
173
+ * Returns Infinity for unlimited tier
174
+ */
175
+ declare function getConfigMonthlyLimit(tier: SubscriptionTier): number;
176
+ /**
177
+ * Check if a feature is enabled
178
+ */
179
+ declare function isFeatureEnabled(feature: keyof CreditSystemConfig["features"]): boolean;
180
+ /**
181
+ * Get the display label for an operation type.
182
+ * Falls back to converting snake_case to Title Case if no label is configured.
183
+ */
184
+ declare function getOperationLabel(operationType: string): string;
185
+ /**
186
+ * Get all operation labels as a record.
187
+ * For any operation in operationCosts that lacks a label, generates one from the key.
188
+ */
189
+ declare function getOperationLabels(): Record<string, string>;
190
+ /**
191
+ * Reset configuration to defaults (for testing)
192
+ */
193
+ declare function resetConfig(): void;
194
+
195
+ /** Interface for external config providers (e.g. Firestore-backed) */
196
+ interface ICreditConfigProvider {
197
+ getConfig(): CreditSystemConfig;
198
+ }
199
+ /** Register an external config provider. Called once at app startup. */
200
+ declare function registerConfigProvider(provider: ICreditConfigProvider): void;
201
+ /** Get the registered provider, or null if none registered. */
202
+ declare function getConfigProvider(): ICreditConfigProvider | null;
203
+ /** Clear registered provider (for testing). */
204
+ declare function clearConfigProvider(): void;
205
+
206
+ /**
207
+ * Get operation costs as a record
208
+ * Returns all configured operation costs from the current config
209
+ */
210
+ declare function getOperationCosts(): Record<string, number>;
211
+ /**
212
+ * Get the credit cost for an operation type
213
+ * Uses the configuration system for dynamic costs
214
+ *
215
+ * @param type - Operation type (must be configured in the system)
216
+ * @returns Credit cost for the operation
217
+ * @throws Error if the operation type is not configured
218
+ */
219
+ declare function getOperationCost(type: string): number;
220
+
221
+ /**
222
+ * Get tier configuration
223
+ * Uses the configuration system for dynamic configs
224
+ *
225
+ * @param tier - Subscription tier
226
+ * @returns Tier configuration
227
+ */
228
+ declare function getTierConfig(tier: SubscriptionTier): TierConfig;
229
+ /**
230
+ * Get monthly credit limit for a tier
231
+ * Returns Infinity for unlimited tier
232
+ * Uses the configuration system for dynamic limits
233
+ *
234
+ * @param tier - Subscription tier
235
+ * @returns Monthly credit limit
236
+ */
237
+ declare function getMonthlyLimit(tier: SubscriptionTier): number;
238
+ /**
239
+ * Get default free credits from configuration
240
+ */
241
+ declare function getDefaultFreeCredits(): number;
242
+ /**
243
+ * Get reservation expiry time from configuration
244
+ */
245
+ declare function getReservationExpiryMs(): number;
246
+ /**
247
+ * Information about an operation's cost and display label
248
+ */
249
+ interface OperationCostInfo {
250
+ key: string;
251
+ cost: number;
252
+ label: string;
253
+ }
254
+ /**
255
+ * Get all operation costs with their display labels.
256
+ * Returns a record keyed by operation type with cost + label.
257
+ */
258
+ declare function getOperationCostsWithLabels(): Record<string, OperationCostInfo>;
259
+
260
+ /**
261
+ * Notification event types
262
+ */
263
+ type CreditNotificationEvent = {
264
+ type: "low_balance";
265
+ userId: string;
266
+ balance: number;
267
+ threshold: number;
268
+ } | {
269
+ type: "balance_depleted";
270
+ userId: string;
271
+ } | {
272
+ type: "subscription_expiring";
273
+ userId: string;
274
+ expiresAt: Date;
275
+ daysRemaining: number;
276
+ } | {
277
+ type: "subscription_expired";
278
+ userId: string;
279
+ wasDowngraded: boolean;
280
+ };
281
+ /**
282
+ * Notification handler interface
283
+ * Implementations can send emails, push notifications, etc.
284
+ */
285
+ interface ICreditNotificationHandler {
286
+ /**
287
+ * Handle a notification event
288
+ * @param event - The notification event
289
+ */
290
+ handleNotification(event: CreditNotificationEvent): Promise<void>;
291
+ }
292
+ /**
293
+ * Register a notification handler
294
+ */
295
+ declare function registerNotificationHandler(handler: ICreditNotificationHandler): void;
296
+ /**
297
+ * Clear all notification handlers (for testing)
298
+ */
299
+ declare function clearNotificationHandlers(): void;
300
+ /**
301
+ * Clear cooldown state (for testing)
302
+ */
303
+ declare function clearCooldownState(): void;
304
+ /**
305
+ * Check and trigger low balance notification if needed
306
+ * Call this after commit operations
307
+ *
308
+ * @param userId - User ID
309
+ * @param newBalance - Balance after the operation
310
+ * @param threshold - Custom threshold (defaults to 10)
311
+ */
312
+ declare function checkAndNotifyLowBalance(userId: string, newBalance: number, threshold?: number): Promise<void>;
313
+ /**
314
+ * Trigger subscription expiring notification
315
+ *
316
+ * @param userId - User ID
317
+ * @param expiresAt - When subscription expires
318
+ * @param daysRemaining - Days until expiry
319
+ */
320
+ declare function notifySubscriptionExpiring(userId: string, expiresAt: Date, daysRemaining: number): Promise<void>;
321
+ /**
322
+ * Trigger subscription expired notification
323
+ *
324
+ * @param userId - User ID
325
+ * @param wasDowngraded - Whether the user was downgraded to free tier
326
+ */
327
+ declare function notifySubscriptionExpired(userId: string, wasDowngraded: boolean): Promise<void>;
328
+ /**
329
+ * Console notification handler for development/testing
330
+ * Logs notifications to console
331
+ */
332
+ declare class ConsoleNotificationHandler implements ICreditNotificationHandler {
333
+ handleNotification(event: CreditNotificationEvent): Promise<void>;
334
+ }
335
+
336
+ /**
337
+ * Credit error utilities
338
+ *
339
+ * Provides functions to parse and identify credit-related errors
340
+ * for consistent error handling across the application.
341
+ */
342
+ /**
343
+ * Parsed information from a credit error message
344
+ */
345
+ interface CreditErrorInfo {
346
+ /** Credits currently available */
347
+ available: number;
348
+ /** Credits required for the operation */
349
+ required: number;
350
+ /** Difference between required and available */
351
+ shortfall: number;
352
+ /** Original error message */
353
+ rawMessage: string;
354
+ }
355
+ /**
356
+ * Parse a credit error message to extract available/required credits
357
+ *
358
+ * @param error - Error message string
359
+ * @returns Parsed credit info or null if not a valid credit error format
360
+ *
361
+ * @example
362
+ * ```ts
363
+ * const error = "Insufficient credits. Available: 3, Required: 10";
364
+ * const info = parseCreditError(error);
365
+ * // { available: 3, required: 10, shortfall: 7, rawMessage: "..." }
366
+ * ```
367
+ */
368
+ declare function parseCreditError(error: string): CreditErrorInfo | null;
369
+ /**
370
+ * Check if an error message is a credit-related error
371
+ *
372
+ * @param error - Error message string
373
+ * @returns true if the error is credit-related
374
+ *
375
+ * @example
376
+ * ```ts
377
+ * if (isCreditError(error)) {
378
+ * showCreditErrorDialog(parseCreditError(error));
379
+ * }
380
+ * ```
381
+ */
382
+ declare function isCreditErrorMessage(error: string): boolean;
383
+
384
+ /**
385
+ * Credit utility functions
386
+ *
387
+ * Common helper functions for credit calculations
388
+ */
389
+
390
+ /**
391
+ * Calculate total available credits from balance and bonus credits
392
+ *
393
+ * @param credits - Object containing balance and bonusCredits properties
394
+ * @returns Total credits (balance + bonusCredits)
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * const total = getTotalCredits({ balance: 100, bonusCredits: 50 });
399
+ * // Returns 150
400
+ * ```
401
+ */
402
+ declare function getTotalCredits(credits: {
403
+ balance: number;
404
+ bonusCredits: number;
405
+ }): number;
406
+ /**
407
+ * Generate a unique request ID
408
+ *
409
+ * Format: req_{timestamp}_{randomPart}
410
+ * Example: req_1706234567890_a1b2c3d4e5f6
411
+ *
412
+ * @returns URL-safe request ID string
413
+ */
414
+ declare function generateRequestId(): string;
415
+ /**
416
+ * Check if the input data indicates preview mode
417
+ *
418
+ * Preview mode skips actual credit deduction - used for dry runs
419
+ * and UI previews where the user wants to see results without committing.
420
+ *
421
+ * @param data - The input data to check
422
+ * @returns true if data has preview: true
423
+ */
424
+ declare function isPreviewMode(data: unknown): boolean;
425
+ /**
426
+ * Create a dummy reservation for preview mode
427
+ *
428
+ * Used when `isPreviewMode(data)` returns true to provide
429
+ * a valid reservation object without actual credit operations.
430
+ *
431
+ * @param userId - The user ID
432
+ * @param operationType - The operation type
433
+ * @returns A dummy PortableReservation with id "preview-mode"
434
+ */
435
+ declare function createDummyReservation(userId: string, operationType: string): PortableReservation;
436
+
437
+ export { ConsoleNotificationHandler, type CreditErrorInfo, type CreditNotificationEvent, PortableReservation as CreditReservation, type CreditSystemConfig, type ICreditConfigProvider, type ICreditNotificationHandler, type OperationCostInfo, PortableReservation, SubscriptionTier as SDKSubscriptionTier, SubscriptionTier, TierConfig, checkAndNotifyLowBalance, clearConfigProvider, clearCooldownState, clearNotificationHandlers, createDummyReservation, generateRequestId, getConfig, getConfigMonthlyLimit, getConfigOperationCost, getConfigProvider, getConfigTierConfig, getDefaultFreeCredits, getMonthlyLimit, getOperationCost, getOperationCosts, getOperationCostsWithLabels, getOperationLabel, getOperationLabels, getReservationExpiryMs, getTierConfig, getTotalCredits, getValidOperationTypes, initializeConfig, isCreditErrorMessage, isFeatureEnabled, isPreviewMode, isValidOperationType, loadConfigFromEnv, notifySubscriptionExpired, notifySubscriptionExpiring, parseCreditError, registerConfigProvider, registerNotificationHandler, resetConfig };