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