@classytic/revenue 1.1.2 → 1.1.4

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 (89) hide show
  1. package/README.md +8 -7
  2. package/dist/application/services/index.d.mts +4 -0
  3. package/dist/application/services/index.mjs +3 -0
  4. package/dist/base-CsTlVQJe.d.mts +136 -0
  5. package/dist/base-DCoyIUj6.mjs +152 -0
  6. package/dist/category-resolver-DV83N8ok.mjs +284 -0
  7. package/dist/commission-split-BzB8cd39.mjs +485 -0
  8. package/dist/core/events.d.mts +294 -0
  9. package/dist/core/events.mjs +100 -0
  10. package/dist/core/index.d.mts +9 -0
  11. package/dist/core/index.mjs +8 -0
  12. package/dist/enums/index.d.mts +157 -0
  13. package/dist/enums/index.mjs +56 -0
  14. package/dist/errors-rRdOqnWx.d.mts +787 -0
  15. package/dist/escrow.enums-CZGrrdg7.mjs +101 -0
  16. package/dist/{escrow.enums-CE0VQsfe.d.ts → escrow.enums-DwdLuuve.d.mts} +30 -28
  17. package/dist/idempotency-DaYcUGY1.mjs +172 -0
  18. package/dist/index-Dsp7H5Wb.d.mts +471 -0
  19. package/dist/index.d.mts +9 -0
  20. package/dist/index.mjs +38 -0
  21. package/dist/infrastructure/plugins/{index.d.ts → index.d.mts} +81 -109
  22. package/dist/infrastructure/plugins/index.mjs +345 -0
  23. package/dist/money-CvrDOijQ.mjs +271 -0
  24. package/dist/money-DPG8AtJ8.d.mts +112 -0
  25. package/dist/{payment.enums-C1BiGlRa.d.ts → payment.enums-HAuAS9Pp.d.mts} +14 -13
  26. package/dist/payment.enums-tEFVa-Xp.mjs +69 -0
  27. package/dist/plugin-BbK0OVHy.d.mts +327 -0
  28. package/dist/plugin-Cd_V04Em.mjs +210 -0
  29. package/dist/providers/index.d.mts +3 -0
  30. package/dist/providers/index.mjs +3 -0
  31. package/dist/reconciliation/{index.d.ts → index.d.mts} +90 -112
  32. package/dist/reconciliation/index.mjs +192 -0
  33. package/dist/retry-HHCOXYdn.d.mts +186 -0
  34. package/dist/revenue-BhdS7nXh.mjs +553 -0
  35. package/dist/schemas/index.d.mts +2665 -0
  36. package/dist/schemas/index.mjs +717 -0
  37. package/dist/schemas/validation.d.mts +375 -0
  38. package/dist/schemas/validation.mjs +325 -0
  39. package/dist/{settlement.enums-ByC1x0ye.d.ts → settlement.enums-DFhkqZEY.d.mts} +31 -29
  40. package/dist/settlement.schema-DnNSFpGd.d.mts +344 -0
  41. package/dist/settlement.service-DjzAjezU.d.mts +594 -0
  42. package/dist/settlement.service-DmdKv0Zu.mjs +2511 -0
  43. package/dist/split.enums-BrjabxIX.mjs +86 -0
  44. package/dist/split.enums-DmskfLOM.d.mts +43 -0
  45. package/dist/tax-BoCt5cEd.d.mts +61 -0
  46. package/dist/tax-EQ15DO81.mjs +162 -0
  47. package/dist/transaction.enums-pCyMFT4Z.mjs +96 -0
  48. package/dist/utils/{index.d.ts → index.d.mts} +91 -161
  49. package/dist/utils/index.mjs +346 -0
  50. package/package.json +39 -37
  51. package/dist/application/services/index.d.ts +0 -6
  52. package/dist/application/services/index.js +0 -3288
  53. package/dist/application/services/index.js.map +0 -1
  54. package/dist/core/events.d.ts +0 -455
  55. package/dist/core/events.js +0 -122
  56. package/dist/core/events.js.map +0 -1
  57. package/dist/core/index.d.ts +0 -13
  58. package/dist/core/index.js +0 -4591
  59. package/dist/core/index.js.map +0 -1
  60. package/dist/enums/index.d.ts +0 -159
  61. package/dist/enums/index.js +0 -296
  62. package/dist/enums/index.js.map +0 -1
  63. package/dist/index-DxIK0UmZ.d.ts +0 -633
  64. package/dist/index-EnfKzDbs.d.ts +0 -806
  65. package/dist/index-cLJBLUvx.d.ts +0 -478
  66. package/dist/index.d.ts +0 -43
  67. package/dist/index.js +0 -4864
  68. package/dist/index.js.map +0 -1
  69. package/dist/infrastructure/plugins/index.js +0 -292
  70. package/dist/infrastructure/plugins/index.js.map +0 -1
  71. package/dist/money-widWVD7r.d.ts +0 -111
  72. package/dist/plugin-Bb9HOE10.d.ts +0 -336
  73. package/dist/providers/index.d.ts +0 -145
  74. package/dist/providers/index.js +0 -141
  75. package/dist/providers/index.js.map +0 -1
  76. package/dist/reconciliation/index.js +0 -140
  77. package/dist/reconciliation/index.js.map +0 -1
  78. package/dist/retry-D4hFUwVk.d.ts +0 -194
  79. package/dist/schemas/index.d.ts +0 -2655
  80. package/dist/schemas/index.js +0 -841
  81. package/dist/schemas/index.js.map +0 -1
  82. package/dist/schemas/validation.d.ts +0 -384
  83. package/dist/schemas/validation.js +0 -303
  84. package/dist/schemas/validation.js.map +0 -1
  85. package/dist/settlement.schema-CpamV7ZY.d.ts +0 -343
  86. package/dist/split.enums-DG3TxQf9.d.ts +0 -42
  87. package/dist/tax-CV8A0sxl.d.ts +0 -60
  88. package/dist/utils/index.js +0 -1202
  89. package/dist/utils/index.js.map +0 -1
@@ -1,806 +0,0 @@
1
- import { M as MonetizationService, P as PaymentService, T as TransactionService, E as EscrowService, S as SettlementService, C as Container } from './index-DxIK0UmZ.js';
2
- import EventBus from './core/events.js';
3
- import { P as PluginLogger, R as RevenuePlugin, a as PluginContext } from './plugin-Bb9HOE10.js';
4
- import { k as RetryConfig, l as CircuitBreakerConfig, R as Result } from './retry-D4hFUwVk.js';
5
- import { PaymentProvider } from './providers/index.js';
6
- import { M as MongooseModel, j as TransactionFlowValue, R as RevenueConfig, k as PaymentProviderInterface } from './index-cLJBLUvx.js';
7
- import { a as TransactionStatusValue, t as SettlementStatusValue } from './settlement.enums-ByC1x0ye.js';
8
- import { S as SubscriptionStatusValue, H as HoldStatusValue } from './escrow.enums-CE0VQsfe.js';
9
- import { a as SplitStatusValue } from './split.enums-DG3TxQf9.js';
10
-
11
- /**
12
- * Revenue - Modern Payment Management
13
- * @classytic/revenue
14
- *
15
- * Fluent Builder API with integrated services
16
- * Less code, more power
17
- *
18
- * Inspired by: Vercel AI SDK, Stripe SDK, tRPC
19
- */
20
-
21
- interface RevenueOptions {
22
- /** Default currency (ISO 4217) */
23
- defaultCurrency?: string;
24
- /** Environment */
25
- environment?: 'development' | 'staging' | 'production';
26
- /** Debug mode */
27
- debug?: boolean;
28
- /** Retry configuration for provider calls */
29
- retry?: Partial<RetryConfig>;
30
- /** Idempotency TTL in ms */
31
- idempotencyTtl?: number;
32
- /** Circuit breaker configuration for provider calls */
33
- circuitBreaker?: Partial<CircuitBreakerConfig> | boolean;
34
- /** Custom logger */
35
- logger?: PluginLogger;
36
- /** Commission rate as decimal (0-1, e.g., 0.10 for 10%) */
37
- commissionRate?: number;
38
- /** Gateway fee rate as decimal (0-1, e.g., 0.029 for 2.9%) */
39
- gatewayFeeRate?: number;
40
- }
41
- interface ModelsConfig {
42
- Transaction: MongooseModel<any>;
43
- Subscription?: MongooseModel<any>;
44
- [key: string]: MongooseModel<any> | undefined;
45
- }
46
- interface ProvidersConfig {
47
- [name: string]: PaymentProvider;
48
- }
49
- /**
50
- * Revenue - Main entry point
51
- *
52
- * @example
53
- * ```typescript
54
- * const revenue = Revenue
55
- * .create({ defaultCurrency: 'USD' })
56
- * .withModels({ Transaction, Subscription })
57
- * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
58
- * .withProvider('manual', new ManualProvider())
59
- * .withPlugin(auditPlugin())
60
- * .build();
61
- *
62
- * // Access services directly
63
- * await revenue.monetization.create({ ... });
64
- * await revenue.payments.verify({ ... });
65
- *
66
- * // Or use events
67
- * revenue.on('payment.verified', (event) => { ... });
68
- * ```
69
- */
70
- declare class Revenue {
71
- private readonly _container;
72
- private readonly _events;
73
- private readonly _plugins;
74
- private readonly _idempotency;
75
- private readonly _circuitBreaker?;
76
- private readonly _options;
77
- private readonly _logger;
78
- private readonly _providers;
79
- private readonly _config;
80
- /** Monetization service - purchases, subscriptions, free items */
81
- readonly monetization: MonetizationService;
82
- /** Payment service - verify, refund, webhooks */
83
- readonly payments: PaymentService;
84
- /** Transaction service - query, update transactions */
85
- readonly transactions: TransactionService;
86
- /** Escrow service - hold, release, splits */
87
- readonly escrow: EscrowService;
88
- /** Settlement service - payout tracking */
89
- readonly settlement: SettlementService;
90
- private constructor();
91
- /**
92
- * Create a new Revenue builder
93
- *
94
- * @example
95
- * ```typescript
96
- * const revenue = Revenue
97
- * .create({ defaultCurrency: 'BDT' })
98
- * .withModels({ Transaction, Subscription })
99
- * .withProvider('manual', new ManualProvider())
100
- * .build();
101
- * ```
102
- */
103
- static create(options?: RevenueOptions): RevenueBuilder;
104
- /** DI container (for advanced usage) */
105
- get container(): Container;
106
- /** Event bus */
107
- get events(): EventBus;
108
- /** Registered providers (frozen) */
109
- get providers(): Readonly<ProvidersConfig>;
110
- /** Configuration (frozen) */
111
- get config(): Readonly<Partial<RevenueConfig>>;
112
- /** Default currency */
113
- get defaultCurrency(): string;
114
- /** Current environment */
115
- get environment(): string;
116
- /**
117
- * Get a provider by name
118
- */
119
- getProvider(name: string): PaymentProviderInterface;
120
- /**
121
- * Get all provider names
122
- */
123
- getProviderNames(): string[];
124
- /**
125
- * Check if provider exists
126
- */
127
- hasProvider(name: string): boolean;
128
- /**
129
- * Subscribe to events
130
- *
131
- * @example
132
- * ```typescript
133
- * revenue.on('payment.verified', (event) => {
134
- * console.log('Payment:', event.transaction._id);
135
- * });
136
- * ```
137
- */
138
- on: EventBus['on'];
139
- /**
140
- * Subscribe once
141
- */
142
- once: EventBus['once'];
143
- /**
144
- * Unsubscribe
145
- */
146
- off: EventBus['off'];
147
- /**
148
- * Emit an event
149
- */
150
- emit: EventBus['emit'];
151
- /**
152
- * Execute operation with retry and idempotency
153
- */
154
- execute<T>(operation: () => Promise<T>, options?: {
155
- idempotencyKey?: string;
156
- params?: unknown;
157
- useRetry?: boolean;
158
- useCircuitBreaker?: boolean;
159
- }): Promise<Result<T, Error>>;
160
- /**
161
- * Create plugin context (for advanced usage)
162
- */
163
- createContext(meta?: {
164
- idempotencyKey?: string;
165
- }): PluginContext;
166
- /**
167
- * Destroy instance and cleanup
168
- */
169
- destroy(): Promise<void>;
170
- }
171
- /**
172
- * Revenue Builder - Fluent configuration API
173
- */
174
- declare class RevenueBuilder {
175
- private options;
176
- private models;
177
- private providers;
178
- private plugins;
179
- private categoryMappings;
180
- private transactionTypeMapping;
181
- constructor(options?: RevenueOptions);
182
- /**
183
- * Register models (required)
184
- *
185
- * @example
186
- * ```typescript
187
- * .withModels({
188
- * Transaction: TransactionModel,
189
- * Subscription: SubscriptionModel,
190
- * })
191
- * ```
192
- */
193
- withModels(models: ModelsConfig): this;
194
- /**
195
- * Register a single model
196
- */
197
- withModel(name: string, model: MongooseModel<any>): this;
198
- /**
199
- * Register a payment provider
200
- *
201
- * @example
202
- * ```typescript
203
- * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
204
- * .withProvider('manual', new ManualProvider())
205
- * ```
206
- */
207
- withProvider(name: string, provider: PaymentProvider): this;
208
- /**
209
- * Register multiple providers at once
210
- */
211
- withProviders(providers: ProvidersConfig): this;
212
- /**
213
- * Register a plugin
214
- *
215
- * @example
216
- * ```typescript
217
- * .withPlugin(loggingPlugin())
218
- * .withPlugin(auditPlugin({ store: saveToDb }))
219
- * ```
220
- */
221
- withPlugin(plugin: RevenuePlugin): this;
222
- /**
223
- * Register multiple plugins
224
- */
225
- withPlugins(plugins: RevenuePlugin[]): this;
226
- /**
227
- * Set retry configuration
228
- *
229
- * @example
230
- * ```typescript
231
- * .withRetry({ maxAttempts: 5, baseDelay: 2000 })
232
- * ```
233
- */
234
- withRetry(config: Partial<RetryConfig>): this;
235
- /**
236
- * Enable circuit breaker
237
- */
238
- withCircuitBreaker(enabled?: boolean): this;
239
- /**
240
- * Set custom logger
241
- */
242
- withLogger(logger: PluginLogger): this;
243
- /**
244
- * Set environment
245
- */
246
- forEnvironment(env: 'development' | 'staging' | 'production'): this;
247
- /**
248
- * Enable debug mode
249
- */
250
- withDebug(enabled?: boolean): this;
251
- /**
252
- * Set commission rate as decimal (0-1, e.g., 0.10 for 10%)
253
- *
254
- * @param rate - Commission rate (0-1 decimal format)
255
- * @param gatewayFeeRate - Gateway fee rate (0-1 decimal format, e.g., 0.029 for 2.9%)
256
- *
257
- * @example
258
- * ```typescript
259
- * .withCommission(0.10, 0.029) // 10% commission + 2.9% gateway fee
260
- * ```
261
- */
262
- withCommission(rate: number, gatewayFeeRate?: number): this;
263
- /**
264
- * Set category mappings (entity → category)
265
- *
266
- * @example
267
- * ```typescript
268
- * .withCategoryMappings({
269
- * PlatformSubscription: 'platform_subscription',
270
- * CourseEnrollment: 'course_enrollment',
271
- * ProductOrder: 'product_order',
272
- * })
273
- * ```
274
- */
275
- withCategoryMappings(mappings: Record<string, string>): this;
276
- /**
277
- * Set transaction flow mapping by category or monetization type
278
- *
279
- * @example
280
- * ```typescript
281
- * .withTransactionTypeMapping({
282
- * platform_subscription: 'inflow',
283
- * subscription: 'inflow',
284
- * refund: 'outflow',
285
- * })
286
- * ```
287
- */
288
- withTransactionTypeMapping(mapping: Record<string, TransactionFlowValue>): this;
289
- /**
290
- * Build the Revenue instance
291
- */
292
- build(): Revenue;
293
- }
294
- /**
295
- * Create Revenue instance (shorthand)
296
- *
297
- * @example
298
- * ```typescript
299
- * const revenue = createRevenue({
300
- * models: { Transaction, Subscription },
301
- * providers: { manual: new ManualProvider() },
302
- * });
303
- * ```
304
- */
305
- declare function createRevenue(config: {
306
- models: ModelsConfig;
307
- providers: ProvidersConfig;
308
- options?: RevenueOptions;
309
- plugins?: RevenuePlugin[];
310
- }): Revenue;
311
-
312
- /**
313
- * Revenue Error Classes
314
- * @classytic/revenue
315
- *
316
- * Typed errors with codes for better error handling
317
- */
318
- interface RevenueErrorOptions {
319
- retryable?: boolean;
320
- metadata?: Record<string, unknown>;
321
- }
322
- /**
323
- * Base Revenue Error
324
- */
325
- declare class RevenueError extends Error {
326
- readonly code: string;
327
- readonly retryable: boolean;
328
- readonly metadata: Record<string, unknown>;
329
- constructor(message: string, code: string, options?: RevenueErrorOptions);
330
- toJSON(): Record<string, unknown>;
331
- }
332
- /**
333
- * Configuration Errors
334
- */
335
- declare class ConfigurationError extends RevenueError {
336
- constructor(message: string, metadata?: Record<string, unknown>);
337
- }
338
- declare class ModelNotRegisteredError extends ConfigurationError {
339
- constructor(modelName: string);
340
- }
341
- /**
342
- * Provider Errors
343
- */
344
- declare class ProviderError extends RevenueError {
345
- constructor(message: string, code: string, options?: RevenueErrorOptions);
346
- }
347
- declare class ProviderNotFoundError extends ProviderError {
348
- constructor(providerName: string, availableProviders?: string[]);
349
- }
350
- declare class ProviderCapabilityError extends ProviderError {
351
- constructor(providerName: string, capability: string);
352
- }
353
- declare class PaymentIntentCreationError extends ProviderError {
354
- constructor(providerName: string, originalError: Error);
355
- }
356
- declare class PaymentVerificationError extends ProviderError {
357
- constructor(paymentIntentId: string, reason: string);
358
- }
359
- /**
360
- * Resource Not Found Errors
361
- */
362
- declare class NotFoundError extends RevenueError {
363
- constructor(message: string, code: string, metadata?: Record<string, unknown>);
364
- }
365
- declare class SubscriptionNotFoundError extends NotFoundError {
366
- constructor(subscriptionId: string);
367
- }
368
- declare class TransactionNotFoundError extends NotFoundError {
369
- constructor(transactionId: string);
370
- }
371
- /**
372
- * Validation Errors
373
- */
374
- declare class ValidationError extends RevenueError {
375
- constructor(message: string, metadata?: Record<string, unknown>);
376
- }
377
- declare class InvalidAmountError extends ValidationError {
378
- constructor(amount: number, message?: string);
379
- }
380
- declare class MissingRequiredFieldError extends ValidationError {
381
- constructor(fieldName: string);
382
- }
383
- /**
384
- * State Errors
385
- */
386
- declare class StateError extends RevenueError {
387
- constructor(message: string, code: string, metadata?: Record<string, unknown>);
388
- }
389
- declare class AlreadyVerifiedError extends StateError {
390
- constructor(transactionId: string);
391
- }
392
- declare class InvalidStateTransitionError extends StateError {
393
- constructor(resourceType: string, resourceId: string, fromState: string, toState: string);
394
- }
395
- declare class SubscriptionNotActiveError extends StateError {
396
- constructor(subscriptionId: string, message?: string);
397
- }
398
- /**
399
- * Operation Errors
400
- */
401
- declare class OperationError extends RevenueError {
402
- constructor(message: string, code: string, options?: RevenueErrorOptions);
403
- }
404
- declare class RefundNotSupportedError extends OperationError {
405
- constructor(providerName: string);
406
- }
407
- declare class RefundError extends OperationError {
408
- constructor(transactionId: string, reason: string);
409
- }
410
- /**
411
- * Error Code Constants
412
- */
413
- declare const ERROR_CODES: {
414
- readonly CONFIGURATION_ERROR: "CONFIGURATION_ERROR";
415
- readonly MODEL_NOT_REGISTERED: "MODEL_NOT_REGISTERED";
416
- readonly PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND";
417
- readonly PROVIDER_CAPABILITY_NOT_SUPPORTED: "PROVIDER_CAPABILITY_NOT_SUPPORTED";
418
- readonly PAYMENT_INTENT_CREATION_FAILED: "PAYMENT_INTENT_CREATION_FAILED";
419
- readonly PAYMENT_VERIFICATION_FAILED: "PAYMENT_VERIFICATION_FAILED";
420
- readonly SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND";
421
- readonly TRANSACTION_NOT_FOUND: "TRANSACTION_NOT_FOUND";
422
- readonly VALIDATION_ERROR: "VALIDATION_ERROR";
423
- readonly INVALID_AMOUNT: "INVALID_AMOUNT";
424
- readonly MISSING_REQUIRED_FIELD: "MISSING_REQUIRED_FIELD";
425
- readonly ALREADY_VERIFIED: "ALREADY_VERIFIED";
426
- readonly INVALID_STATE_TRANSITION: "INVALID_STATE_TRANSITION";
427
- readonly SUBSCRIPTION_NOT_ACTIVE: "SUBSCRIPTION_NOT_ACTIVE";
428
- readonly REFUND_NOT_SUPPORTED: "REFUND_NOT_SUPPORTED";
429
- readonly REFUND_FAILED: "REFUND_FAILED";
430
- };
431
- type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
432
- /**
433
- * Check if error is retryable
434
- */
435
- declare function isRetryable(error: unknown): boolean;
436
- /**
437
- * Check if error is from revenue package
438
- */
439
- declare function isRevenueError(error: unknown): error is RevenueError;
440
-
441
- /**
442
- * Audit Trail Types
443
- * @classytic/revenue
444
- *
445
- * State change tracking for compliance and debugging
446
- * Stored in document.metadata.stateHistory array
447
- */
448
- /**
449
- * State Change Audit Event
450
- * Records who changed what, when, and why
451
- *
452
- * Example usage:
453
- * ```typescript
454
- * const event: StateChangeEvent = {
455
- * resourceType: 'transaction',
456
- * resourceId: 'tx_123',
457
- * fromState: 'pending',
458
- * toState: 'verified',
459
- * changedAt: new Date(),
460
- * changedBy: 'admin_user_id',
461
- * reason: 'Payment verified by payment gateway',
462
- * metadata: { verificationId: 'ver_abc' }
463
- * };
464
- * ```
465
- */
466
- interface StateChangeEvent<TState = string> {
467
- /** Type of resource (e.g., 'transaction', 'subscription') */
468
- resourceType: string;
469
- /** Unique identifier of the resource */
470
- resourceId: string;
471
- /** State before the transition */
472
- fromState: TState;
473
- /** State after the transition */
474
- toState: TState;
475
- /** Timestamp when the change occurred */
476
- changedAt: Date;
477
- /** User ID or system identifier who triggered the change */
478
- changedBy?: string;
479
- /** Human-readable reason for the state change */
480
- reason?: string;
481
- /** Additional contextual data */
482
- metadata?: Record<string, unknown>;
483
- }
484
- /**
485
- * Helper to append audit event to document metadata
486
- *
487
- * This is a metadata-based approach that stores audit trail
488
- * directly in the document's metadata.stateHistory array.
489
- *
490
- * Example:
491
- * ```typescript
492
- * const transaction = await Transaction.findById(id);
493
- *
494
- * const auditEvent = {
495
- * resourceType: 'transaction',
496
- * resourceId: transaction._id.toString(),
497
- * fromState: 'pending',
498
- * toState: 'verified',
499
- * changedAt: new Date(),
500
- * changedBy: 'admin_123',
501
- * };
502
- *
503
- * const updated = appendAuditEvent(transaction, auditEvent);
504
- * await updated.save();
505
- * ```
506
- *
507
- * @param document - Mongoose document or plain object with optional metadata field
508
- * @param event - State change event to append
509
- * @returns Updated document with event in metadata.stateHistory
510
- */
511
- declare function appendAuditEvent<T extends {
512
- metadata?: any;
513
- }>(document: T, event: StateChangeEvent): T;
514
- /**
515
- * Helper to get audit trail from document metadata
516
- *
517
- * Example:
518
- * ```typescript
519
- * const transaction = await Transaction.findById(id);
520
- * const history = getAuditTrail(transaction);
521
- *
522
- * console.log(history);
523
- * // [
524
- * // { fromState: 'pending', toState: 'processing', changedAt: ... },
525
- * // { fromState: 'processing', toState: 'verified', changedAt: ... },
526
- * // ]
527
- * ```
528
- *
529
- * @param document - Document to extract audit trail from
530
- * @returns Array of state change events (empty array if none)
531
- */
532
- declare function getAuditTrail<T extends {
533
- metadata?: any;
534
- }>(document: T): StateChangeEvent[];
535
- /**
536
- * Helper to get the last state change from audit trail
537
- *
538
- * @param document - Document to extract last change from
539
- * @returns Last state change event or undefined if none
540
- */
541
- declare function getLastStateChange<T extends {
542
- metadata?: any;
543
- }>(document: T): StateChangeEvent | undefined;
544
- /**
545
- * Helper to find state changes by criteria
546
- *
547
- * Example:
548
- * ```typescript
549
- * const transaction = await Transaction.findById(id);
550
- *
551
- * // Find all changes made by a specific user
552
- * const userChanges = filterAuditTrail(transaction, {
553
- * changedBy: 'admin_123'
554
- * });
555
- *
556
- * // Find all transitions to 'failed' state
557
- * const failures = filterAuditTrail(transaction, {
558
- * toState: 'failed'
559
- * });
560
- * ```
561
- *
562
- * @param document - Document to filter audit trail from
563
- * @param criteria - Filter criteria
564
- * @returns Filtered array of state change events
565
- */
566
- declare function filterAuditTrail<T extends {
567
- metadata?: any;
568
- }>(document: T, criteria: Partial<StateChangeEvent>): StateChangeEvent[];
569
-
570
- /**
571
- * Generic State Machine Validator
572
- * @classytic/revenue
573
- *
574
- * Inspired by Stripe's state transition validation
575
- * Provides centralized, type-safe state transition management
576
- */
577
-
578
- /**
579
- * Generic State Machine for validating state transitions
580
- *
581
- * @template TState - The state type (typically a union of string literals)
582
- *
583
- * @example
584
- * ```typescript
585
- * const stateMachine = new StateMachine(
586
- * new Map([
587
- * ['pending', new Set(['processing', 'failed'])],
588
- * ['processing', new Set(['completed', 'failed'])],
589
- * ['completed', new Set([])], // Terminal state
590
- * ['failed', new Set([])], // Terminal state
591
- * ]),
592
- * 'payment'
593
- * );
594
- *
595
- * // Validate transition
596
- * stateMachine.validate('pending', 'processing', 'pay_123'); // ✅ OK
597
- * stateMachine.validate('completed', 'pending', 'pay_123'); // ❌ Throws InvalidStateTransitionError
598
- *
599
- * // Check without throwing
600
- * stateMachine.canTransition('pending', 'processing'); // true
601
- * stateMachine.canTransition('completed', 'pending'); // false
602
- * ```
603
- */
604
- declare class StateMachine<TState extends string> {
605
- private readonly transitions;
606
- private readonly resourceType;
607
- /**
608
- * @param transitions - Map of state → allowed next states
609
- * @param resourceType - Type of resource (for error messages)
610
- */
611
- constructor(transitions: Map<TState, Set<TState>>, resourceType: string);
612
- /**
613
- * Validate state transition is allowed
614
- *
615
- * @param from - Current state
616
- * @param to - Target state
617
- * @param resourceId - ID of the resource being transitioned
618
- * @throws InvalidStateTransitionError if transition is invalid
619
- *
620
- * @example
621
- * ```typescript
622
- * try {
623
- * stateMachine.validate('pending', 'completed', 'tx_123');
624
- * } catch (error) {
625
- * if (error instanceof InvalidStateTransitionError) {
626
- * console.error('Invalid transition:', error.message);
627
- * }
628
- * }
629
- * ```
630
- */
631
- validate(from: TState, to: TState, resourceId: string): void;
632
- /**
633
- * Check if transition is valid (non-throwing)
634
- *
635
- * @param from - Current state
636
- * @param to - Target state
637
- * @returns true if transition is allowed
638
- *
639
- * @example
640
- * ```typescript
641
- * if (stateMachine.canTransition('pending', 'processing')) {
642
- * // Safe to proceed with transition
643
- * transaction.status = 'processing';
644
- * }
645
- * ```
646
- */
647
- canTransition(from: TState, to: TState): boolean;
648
- /**
649
- * Get all allowed next states from current state
650
- *
651
- * @param from - Current state
652
- * @returns Array of allowed next states
653
- *
654
- * @example
655
- * ```typescript
656
- * const nextStates = stateMachine.getAllowedTransitions('pending');
657
- * console.log(nextStates); // ['processing', 'failed']
658
- * ```
659
- */
660
- getAllowedTransitions(from: TState): TState[];
661
- /**
662
- * Check if state is terminal (no outgoing transitions)
663
- *
664
- * @param state - State to check
665
- * @returns true if state has no outgoing transitions
666
- *
667
- * @example
668
- * ```typescript
669
- * stateMachine.isTerminalState('completed'); // true
670
- * stateMachine.isTerminalState('pending'); // false
671
- * ```
672
- */
673
- isTerminalState(state: TState): boolean;
674
- /**
675
- * Get the resource type this state machine manages
676
- *
677
- * @returns Resource type string
678
- */
679
- getResourceType(): string;
680
- /**
681
- * Validate state transition and create audit event
682
- *
683
- * This is a convenience method that combines validation with audit event creation.
684
- * Use this when you want to both validate a transition and record it in the audit trail.
685
- *
686
- * @param from - Current state
687
- * @param to - Target state
688
- * @param resourceId - ID of the resource being transitioned
689
- * @param context - Optional audit context (who, why, metadata)
690
- * @returns StateChangeEvent ready to be appended to document metadata
691
- * @throws InvalidStateTransitionError if transition is invalid
692
- *
693
- * @example
694
- * ```typescript
695
- * import { appendAuditEvent } from '@classytic/revenue';
696
- *
697
- * // Validate and create audit event
698
- * const auditEvent = TRANSACTION_STATE_MACHINE.validateAndCreateAuditEvent(
699
- * transaction.status,
700
- * 'verified',
701
- * transaction._id.toString(),
702
- * {
703
- * changedBy: 'admin_123',
704
- * reason: 'Payment verified by payment gateway',
705
- * metadata: { verificationId: 'ver_abc' }
706
- * }
707
- * );
708
- *
709
- * // Apply state change
710
- * transaction.status = 'verified';
711
- *
712
- * // Append audit event to metadata
713
- * Object.assign(transaction, appendAuditEvent(transaction, auditEvent));
714
- *
715
- * // Save
716
- * await transaction.save();
717
- * ```
718
- */
719
- validateAndCreateAuditEvent(from: TState, to: TState, resourceId: string, context?: {
720
- changedBy?: string;
721
- reason?: string;
722
- metadata?: Record<string, unknown>;
723
- }): StateChangeEvent<TState>;
724
- }
725
-
726
- /**
727
- * State Machine Definitions
728
- * @classytic/revenue
729
- *
730
- * Centralized state transition rules for all entities
731
- * Inspired by Stripe, PayPal, and Shopify state management patterns
732
- */
733
-
734
- /**
735
- * Transaction State Machine
736
- *
737
- * Flow:
738
- * ```
739
- * pending → payment_initiated → processing → verified → completed
740
- * ↓ ↓ ↓
741
- * failed requires_action refunded
742
- * ↓ partially_refunded
743
- * failed
744
- * ```
745
- *
746
- * Terminal states: failed, refunded, cancelled, expired
747
- */
748
- declare const TRANSACTION_STATE_MACHINE: StateMachine<TransactionStatusValue>;
749
- /**
750
- * Subscription State Machine
751
- *
752
- * Flow:
753
- * ```
754
- * pending → active → paused → active
755
- * ↓ ↓
756
- * cancelled cancelled
757
- * ↓
758
- * expired
759
- * ```
760
- *
761
- * Terminal states: cancelled, expired
762
- */
763
- declare const SUBSCRIPTION_STATE_MACHINE: StateMachine<SubscriptionStatusValue>;
764
- /**
765
- * Settlement State Machine
766
- *
767
- * Flow:
768
- * ```
769
- * pending → processing → completed
770
- * ↓
771
- * failed → pending (retry allowed)
772
- * ```
773
- *
774
- * Terminal states: completed, cancelled
775
- * Note: failed can retry to pending
776
- */
777
- declare const SETTLEMENT_STATE_MACHINE: StateMachine<SettlementStatusValue>;
778
- /**
779
- * Escrow Hold State Machine
780
- *
781
- * Flow:
782
- * ```
783
- * held → partially_released → released
784
- * ↓
785
- * cancelled
786
- * ```
787
- *
788
- * Terminal states: released, cancelled, expired
789
- */
790
- declare const HOLD_STATE_MACHINE: StateMachine<HoldStatusValue>;
791
- /**
792
- * Split Payment State Machine
793
- *
794
- * Flow:
795
- * ```
796
- * pending → due → paid
797
- * ↓
798
- * waived
799
- * cancelled
800
- * ```
801
- *
802
- * Terminal states: paid, waived, cancelled
803
- */
804
- declare const SPLIT_STATE_MACHINE: StateMachine<SplitStatusValue>;
805
-
806
- export { AlreadyVerifiedError as A, RefundError as B, ConfigurationError as C, type ErrorCode as D, ERROR_CODES as E, isRetryable as F, isRevenueError as G, HOLD_STATE_MACHINE as H, InvalidAmountError as I, type ModelsConfig as M, NotFoundError as N, OperationError as O, type ProvidersConfig as P, Revenue as R, StateMachine as S, TRANSACTION_STATE_MACHINE as T, ValidationError as V, RevenueError as a, RevenueBuilder as b, createRevenue as c, type RevenueOptions as d, SUBSCRIPTION_STATE_MACHINE as e, SETTLEMENT_STATE_MACHINE as f, SPLIT_STATE_MACHINE as g, type StateChangeEvent as h, appendAuditEvent as i, getAuditTrail as j, getLastStateChange as k, filterAuditTrail as l, type RevenueErrorOptions as m, ModelNotRegisteredError as n, ProviderError as o, ProviderNotFoundError as p, ProviderCapabilityError as q, PaymentIntentCreationError as r, PaymentVerificationError as s, SubscriptionNotFoundError as t, TransactionNotFoundError as u, MissingRequiredFieldError as v, StateError as w, InvalidStateTransitionError as x, SubscriptionNotActiveError as y, RefundNotSupportedError as z };