@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,70 +0,0 @@
1
- //#region src/enums/payment.enums.d.ts
2
- /**
3
- * Payment Enums
4
- * @classytic/revenue
5
- *
6
- * Library-managed payment enums only.
7
- * Users define their own payment methods in their schema.
8
- */
9
- /**
10
- * Payment Status - Library-managed states
11
- */
12
- declare const PAYMENT_STATUS: {
13
- readonly PENDING: "pending";
14
- readonly VERIFIED: "verified";
15
- readonly FAILED: "failed";
16
- readonly REFUNDED: "refunded";
17
- readonly CANCELLED: "cancelled";
18
- };
19
- type PaymentStatus = typeof PAYMENT_STATUS;
20
- type PaymentStatusValue = PaymentStatus[keyof PaymentStatus];
21
- declare const PAYMENT_STATUS_VALUES: PaymentStatusValue[];
22
- /**
23
- * Common gateway type constants for convenience
24
- *
25
- * ⚠️ IMPORTANT: These are NOT restrictions - just common reference values
26
- *
27
- * You can register ANY custom gateway provider by passing it to createRevenue():
28
- *
29
- * @example
30
- * ```typescript
31
- * const revenue = createRevenue({
32
- * providers: {
33
- * manual: new ManualProvider(),
34
- * bkash: new BkashProvider(), // ✅ Custom gateway
35
- * nagad: new NagadProvider(), // ✅ Custom gateway
36
- * stripe: new StripeProvider(), // ✅ Custom gateway
37
- * paypal: new PaypalProvider(), // ✅ Any gateway you want
38
- * }
39
- * });
40
- *
41
- * // Use by name
42
- * await revenue.monetization.create({ gateway: 'bkash', ... });
43
- * ```
44
- *
45
- * Reference values:
46
- * - MANUAL: Built-in manual provider (@classytic/revenue-manual)
47
- * - STRIPE: Stripe provider (build with @classytic/revenue-stripe)
48
- * - SSLCOMMERZ: SSLCommerz provider (build with @classytic/revenue-sslcommerz)
49
- *
50
- * Add your own: bkash, nagad, rocket, paypal, razorpay, flutterwave, etc.
51
- */
52
- declare const PAYMENT_GATEWAY_TYPE: {
53
- readonly MANUAL: "manual";
54
- readonly STRIPE: "stripe";
55
- readonly SSLCOMMERZ: "sslcommerz";
56
- };
57
- type PaymentGatewayType = typeof PAYMENT_GATEWAY_TYPE;
58
- type PaymentGatewayTypeValue = PaymentGatewayType[keyof PaymentGatewayType];
59
- declare const PAYMENT_GATEWAY_TYPE_VALUES: PaymentGatewayTypeValue[];
60
- declare const GATEWAY_TYPES: {
61
- readonly MANUAL: "manual";
62
- readonly STRIPE: "stripe";
63
- readonly SSLCOMMERZ: "sslcommerz";
64
- };
65
- declare const GATEWAY_TYPE_VALUES: PaymentGatewayTypeValue[];
66
- declare function isPaymentStatus(value: unknown): value is PaymentStatusValue;
67
- declare function isPaymentGatewayType(value: unknown): value is PaymentGatewayTypeValue;
68
- declare const isGatewayType: typeof isPaymentGatewayType;
69
- //#endregion
70
- export { PAYMENT_STATUS as a, PaymentGatewayTypeValue as c, isGatewayType as d, isPaymentGatewayType as f, PAYMENT_GATEWAY_TYPE_VALUES as i, PaymentStatus as l, GATEWAY_TYPE_VALUES as n, PAYMENT_STATUS_VALUES as o, isPaymentStatus as p, PAYMENT_GATEWAY_TYPE as r, PaymentGatewayType as s, GATEWAY_TYPES as t, PaymentStatusValue as u };
@@ -1,69 +0,0 @@
1
- //#region src/enums/payment.enums.ts
2
- /**
3
- * Payment Enums
4
- * @classytic/revenue
5
- *
6
- * Library-managed payment enums only.
7
- * Users define their own payment methods in their schema.
8
- */
9
- /**
10
- * Payment Status - Library-managed states
11
- */
12
- const PAYMENT_STATUS = {
13
- PENDING: "pending",
14
- VERIFIED: "verified",
15
- FAILED: "failed",
16
- REFUNDED: "refunded",
17
- CANCELLED: "cancelled"
18
- };
19
- const PAYMENT_STATUS_VALUES = Object.values(PAYMENT_STATUS);
20
- /**
21
- * Common gateway type constants for convenience
22
- *
23
- * ⚠️ IMPORTANT: These are NOT restrictions - just common reference values
24
- *
25
- * You can register ANY custom gateway provider by passing it to createRevenue():
26
- *
27
- * @example
28
- * ```typescript
29
- * const revenue = createRevenue({
30
- * providers: {
31
- * manual: new ManualProvider(),
32
- * bkash: new BkashProvider(), // ✅ Custom gateway
33
- * nagad: new NagadProvider(), // ✅ Custom gateway
34
- * stripe: new StripeProvider(), // ✅ Custom gateway
35
- * paypal: new PaypalProvider(), // ✅ Any gateway you want
36
- * }
37
- * });
38
- *
39
- * // Use by name
40
- * await revenue.monetization.create({ gateway: 'bkash', ... });
41
- * ```
42
- *
43
- * Reference values:
44
- * - MANUAL: Built-in manual provider (@classytic/revenue-manual)
45
- * - STRIPE: Stripe provider (build with @classytic/revenue-stripe)
46
- * - SSLCOMMERZ: SSLCommerz provider (build with @classytic/revenue-sslcommerz)
47
- *
48
- * Add your own: bkash, nagad, rocket, paypal, razorpay, flutterwave, etc.
49
- */
50
- const PAYMENT_GATEWAY_TYPE = {
51
- MANUAL: "manual",
52
- STRIPE: "stripe",
53
- SSLCOMMERZ: "sslcommerz"
54
- };
55
- const PAYMENT_GATEWAY_TYPE_VALUES = Object.values(PAYMENT_GATEWAY_TYPE);
56
- const GATEWAY_TYPES = PAYMENT_GATEWAY_TYPE;
57
- const GATEWAY_TYPE_VALUES = PAYMENT_GATEWAY_TYPE_VALUES;
58
- const paymentStatusSet = new Set(PAYMENT_STATUS_VALUES);
59
- const paymentGatewayTypeSet = new Set(PAYMENT_GATEWAY_TYPE_VALUES);
60
- function isPaymentStatus(value) {
61
- return typeof value === "string" && paymentStatusSet.has(value);
62
- }
63
- function isPaymentGatewayType(value) {
64
- return typeof value === "string" && paymentGatewayTypeSet.has(value);
65
- }
66
- const isGatewayType = isPaymentGatewayType;
67
-
68
- //#endregion
69
- export { PAYMENT_STATUS as a, isPaymentGatewayType as c, PAYMENT_GATEWAY_TYPE_VALUES as i, isPaymentStatus as l, GATEWAY_TYPE_VALUES as n, PAYMENT_STATUS_VALUES as o, PAYMENT_GATEWAY_TYPE as r, isGatewayType as s, GATEWAY_TYPES as t };
@@ -1,327 +0,0 @@
1
- import { EventBus, RevenueEvents } from "./core/events.mjs";
2
-
3
- //#region src/core/plugin.d.ts
4
- /**
5
- * Plugin context passed to hooks
6
- */
7
- interface PluginContext {
8
- /** Event bus for emitting events */
9
- events: EventBus;
10
- /** Logger instance */
11
- logger: PluginLogger;
12
- /** Plugin-specific storage (use this to share data between hook calls) */
13
- storage: Map<string, unknown>;
14
- /** Request metadata */
15
- meta: {
16
- idempotencyKey?: string;
17
- requestId: string;
18
- timestamp: Date;
19
- [key: string]: unknown;
20
- };
21
- }
22
- /**
23
- * Plugin logger interface
24
- */
25
- interface PluginLogger {
26
- debug(message: string, data?: unknown): void;
27
- info(message: string, data?: unknown): void;
28
- warn(message: string, data?: unknown): void;
29
- error(message: string, data?: unknown): void;
30
- }
31
- /**
32
- * Hook function type
33
- */
34
- type HookFn<TInput = unknown, TOutput = unknown> = (ctx: PluginContext, input: TInput, next: () => Promise<TOutput>) => Promise<TOutput>;
35
- /**
36
- * Available hook points
37
- */
38
- interface PluginHooks {
39
- 'monetization.create.before': HookFn<MonetizationCreateInput>;
40
- 'monetization.create.after': HookFn<MonetizationCreateInput, MonetizationCreateOutput>;
41
- 'payment.create.before': HookFn<PaymentCreateInput>;
42
- 'payment.create.after': HookFn<PaymentCreateInput, PaymentCreateOutput>;
43
- 'payment.verify.before': HookFn<PaymentVerifyInput>;
44
- 'payment.verify.after': HookFn<PaymentVerifyInput, PaymentVerifyOutput>;
45
- 'payment.refund.before': HookFn<RefundInput>;
46
- 'payment.refund.after': HookFn<RefundInput, RefundOutput>;
47
- 'subscription.create.before': HookFn<SubscriptionCreateInput>;
48
- 'subscription.create.after': HookFn<SubscriptionCreateInput, SubscriptionCreateOutput>;
49
- 'subscription.activate.before': HookFn<SubscriptionActivateInput>;
50
- 'subscription.activate.after': HookFn<SubscriptionActivateInput, SubscriptionActivateOutput>;
51
- 'subscription.cancel.before': HookFn<SubscriptionCancelInput>;
52
- 'subscription.cancel.after': HookFn<SubscriptionCancelInput, SubscriptionCancelOutput>;
53
- 'subscription.pause.before': HookFn<SubscriptionPauseInput>;
54
- 'subscription.pause.after': HookFn<SubscriptionPauseInput, SubscriptionPauseOutput>;
55
- 'subscription.resume.before': HookFn<SubscriptionResumeInput>;
56
- 'subscription.resume.after': HookFn<SubscriptionResumeInput, SubscriptionResumeOutput>;
57
- 'transaction.create.before': HookFn<TransactionCreateInput>;
58
- 'transaction.create.after': HookFn<TransactionCreateInput, TransactionCreateOutput>;
59
- 'transaction.update.before': HookFn<TransactionUpdateInput>;
60
- 'transaction.update.after': HookFn<TransactionUpdateInput, TransactionUpdateOutput>;
61
- 'escrow.hold.before': HookFn<EscrowHoldInput>;
62
- 'escrow.hold.after': HookFn<EscrowHoldInput, EscrowHoldOutput>;
63
- 'escrow.release.before': HookFn<EscrowReleaseInput>;
64
- 'escrow.release.after': HookFn<EscrowReleaseInput, EscrowReleaseOutput>;
65
- }
66
- /**
67
- * Clean, explicit hook input/output types
68
- * Self-documenting and fully type-safe - no more `as any` needed!
69
- */
70
- /**
71
- * Data passed to monetization.create hooks
72
- * Includes all parameters plus tax if injected by tax plugin
73
- */
74
- interface MonetizationCreateInput {
75
- data: {
76
- organizationId?: string;
77
- customerId?: string;
78
- sourceId?: string;
79
- sourceModel?: string;
80
- };
81
- planKey: string;
82
- amount: number;
83
- currency?: string;
84
- gateway?: string;
85
- entity?: string | null;
86
- monetizationType?: 'subscription' | 'purchase' | 'free';
87
- paymentData?: Record<string, unknown>;
88
- metadata?: Record<string, unknown>;
89
- idempotencyKey?: string | null;
90
- tax?: {
91
- isApplicable: boolean;
92
- rate: number;
93
- baseAmount: number;
94
- taxAmount: number;
95
- totalAmount: number;
96
- pricesIncludeTax: boolean;
97
- type: 'collected' | 'paid' | 'exempt';
98
- };
99
- }
100
- interface MonetizationCreateOutput {
101
- transactionId?: string;
102
- subscriptionId?: string;
103
- }
104
- /**
105
- * Data passed to payment.create hooks
106
- */
107
- interface PaymentCreateInput {
108
- transactionId: string;
109
- amount: number;
110
- currency: string;
111
- gateway: string;
112
- paymentData?: Record<string, unknown>;
113
- metadata?: Record<string, unknown>;
114
- }
115
- interface PaymentCreateOutput {
116
- paymentIntentId: string;
117
- clientSecret?: string;
118
- }
119
- interface PaymentVerifyInput {
120
- id: string;
121
- verifiedBy?: string;
122
- }
123
- interface PaymentVerifyOutput {
124
- verified: boolean;
125
- }
126
- interface RefundInput {
127
- transactionId: string;
128
- amount?: number;
129
- reason?: string;
130
- }
131
- interface RefundOutput {
132
- refundId: string;
133
- }
134
- /**
135
- * Data passed to subscription.create hooks
136
- * Note: subscriptionId is undefined in .before hook (not yet created)
137
- * and populated in .after hook (already created)
138
- */
139
- interface SubscriptionCreateInput {
140
- subscriptionId?: string;
141
- planKey: string;
142
- customerId?: string;
143
- organizationId?: string;
144
- entity?: string | null;
145
- }
146
- interface SubscriptionCreateOutput {
147
- subscription: unknown;
148
- transaction?: unknown;
149
- }
150
- /**
151
- * Data passed to subscription.activate hooks
152
- */
153
- interface SubscriptionActivateInput {
154
- subscriptionId: string;
155
- transactionId?: string;
156
- activatedAt?: Date;
157
- }
158
- interface SubscriptionActivateOutput {
159
- activated: boolean;
160
- activatedAt: Date;
161
- }
162
- /**
163
- * Data passed to subscription.cancel hooks
164
- */
165
- interface SubscriptionCancelInput {
166
- subscriptionId: string;
167
- immediate?: boolean;
168
- reason?: string;
169
- }
170
- interface SubscriptionCancelOutput {
171
- cancelled: boolean;
172
- effectiveDate?: Date;
173
- }
174
- /**
175
- * Data passed to subscription.pause hooks
176
- */
177
- interface SubscriptionPauseInput {
178
- subscriptionId: string;
179
- reason?: string;
180
- }
181
- interface SubscriptionPauseOutput {
182
- paused: boolean;
183
- pausedAt: Date;
184
- }
185
- /**
186
- * Data passed to subscription.resume hooks
187
- */
188
- interface SubscriptionResumeInput {
189
- subscriptionId: string;
190
- extendPeriod?: boolean;
191
- }
192
- interface SubscriptionResumeOutput {
193
- resumed: boolean;
194
- resumedAt: Date;
195
- }
196
- /**
197
- * Data passed to transaction.create hooks
198
- */
199
- interface TransactionCreateInput {
200
- amount: number;
201
- currency: string;
202
- type: string;
203
- organizationId?: string;
204
- customerId?: string;
205
- metadata?: Record<string, unknown>;
206
- }
207
- interface TransactionCreateOutput {
208
- transactionId: string;
209
- }
210
- interface TransactionUpdateInput {
211
- transactionId: string;
212
- updates: Record<string, unknown>;
213
- }
214
- interface TransactionUpdateOutput {
215
- transaction: unknown;
216
- }
217
- interface EscrowHoldInput {
218
- transactionId: string;
219
- reason?: string;
220
- }
221
- interface EscrowHoldOutput {
222
- held: boolean;
223
- }
224
- interface EscrowReleaseInput {
225
- transactionId: string;
226
- recipientId?: string;
227
- recipientType?: string;
228
- }
229
- interface EscrowReleaseOutput {
230
- released: boolean;
231
- }
232
- /**
233
- * Plugin definition
234
- */
235
- interface RevenuePlugin {
236
- /** Unique plugin name */
237
- name: string;
238
- /** Plugin version */
239
- version?: string;
240
- /** Plugin description */
241
- description?: string;
242
- /** Dependencies on other plugins */
243
- dependencies?: string[];
244
- /** Hook implementations */
245
- hooks?: Partial<PluginHooks>;
246
- /** Event listeners */
247
- events?: Partial<{ [K in keyof RevenueEvents]: (event: RevenueEvents[K]) => void | Promise<void> }>;
248
- /** Initialize plugin */
249
- init?: (ctx: PluginContext) => void | Promise<void>;
250
- /** Cleanup plugin */
251
- destroy?: () => void | Promise<void>;
252
- }
253
- /**
254
- * Plugin manager - handles registration and execution
255
- */
256
- declare class PluginManager {
257
- private plugins;
258
- private hooks;
259
- private initialized;
260
- /**
261
- * Register a plugin
262
- */
263
- register(plugin: RevenuePlugin): this;
264
- /**
265
- * Initialize all plugins
266
- */
267
- init(ctx: PluginContext): Promise<void>;
268
- /**
269
- * Execute a hook chain
270
- */
271
- executeHook<TInput, TOutput>(hookName: string, ctx: PluginContext, input: TInput, execute: () => Promise<TOutput>): Promise<TOutput>;
272
- /**
273
- * Check if plugin is registered
274
- */
275
- has(name: string): boolean;
276
- /**
277
- * Get a plugin by name
278
- */
279
- get(name: string): RevenuePlugin | undefined;
280
- /**
281
- * Get all registered plugins
282
- */
283
- list(): RevenuePlugin[];
284
- /**
285
- * Destroy all plugins
286
- */
287
- destroy(): Promise<void>;
288
- }
289
- /**
290
- * Logging plugin - logs all operations
291
- */
292
- declare function loggingPlugin(options?: {
293
- level?: 'debug' | 'info';
294
- }): RevenuePlugin;
295
- /**
296
- * Audit plugin - records all operations for compliance
297
- */
298
- declare function auditPlugin(options?: {
299
- store?: (entry: AuditEntry) => Promise<void>;
300
- }): RevenuePlugin;
301
- interface AuditEntry {
302
- action: string;
303
- requestId: string;
304
- timestamp: Date;
305
- input: Record<string, unknown>;
306
- output: Record<string, unknown>;
307
- idempotencyKey?: string;
308
- }
309
- /**
310
- * Metrics plugin - collects operation metrics
311
- */
312
- declare function metricsPlugin(options?: {
313
- onMetric?: (metric: Metric) => void;
314
- }): RevenuePlugin;
315
- interface Metric {
316
- name: string;
317
- duration: number;
318
- success: boolean;
319
- error?: string;
320
- [key: string]: unknown;
321
- }
322
- /**
323
- * Create a custom plugin
324
- */
325
- declare function definePlugin(plugin: RevenuePlugin): RevenuePlugin;
326
- //#endregion
327
- export { PluginManager as a, definePlugin as c, PluginLogger as i, loggingPlugin as l, PluginContext as n, RevenuePlugin as o, PluginHooks as r, auditPlugin as s, HookFn as t, metricsPlugin as u };
@@ -1,210 +0,0 @@
1
- //#region src/core/plugin.ts
2
- /**
3
- * Plugin manager - handles registration and execution
4
- */
5
- var PluginManager = class {
6
- plugins = /* @__PURE__ */ new Map();
7
- hooks = /* @__PURE__ */ new Map();
8
- initialized = false;
9
- /**
10
- * Register a plugin
11
- */
12
- register(plugin) {
13
- if (this.plugins.has(plugin.name)) throw new Error(`Plugin "${plugin.name}" is already registered`);
14
- if (plugin.dependencies) {
15
- for (const dep of plugin.dependencies) if (!this.plugins.has(dep)) throw new Error(`Plugin "${plugin.name}" requires "${dep}" to be registered first`);
16
- }
17
- this.plugins.set(plugin.name, plugin);
18
- if (plugin.hooks) for (const [hookName, hookFn] of Object.entries(plugin.hooks)) {
19
- if (!this.hooks.has(hookName)) this.hooks.set(hookName, []);
20
- this.hooks.get(hookName).push(hookFn);
21
- }
22
- return this;
23
- }
24
- /**
25
- * Initialize all plugins
26
- */
27
- async init(ctx) {
28
- if (this.initialized) return;
29
- for (const plugin of this.plugins.values()) {
30
- if (plugin.init) await plugin.init(ctx);
31
- if (plugin.events) for (const [event, handler] of Object.entries(plugin.events)) ctx.events.on(event, handler);
32
- }
33
- this.initialized = true;
34
- }
35
- /**
36
- * Execute a hook chain
37
- */
38
- async executeHook(hookName, ctx, input, execute) {
39
- const hooks = this.hooks.get(hookName) ?? [];
40
- if (hooks.length === 0) return execute();
41
- let index = 0;
42
- const next = async () => {
43
- if (index >= hooks.length) return execute();
44
- const hook = hooks[index++];
45
- return hook(ctx, input, next);
46
- };
47
- return next();
48
- }
49
- /**
50
- * Check if plugin is registered
51
- */
52
- has(name) {
53
- return this.plugins.has(name);
54
- }
55
- /**
56
- * Get a plugin by name
57
- */
58
- get(name) {
59
- return this.plugins.get(name);
60
- }
61
- /**
62
- * Get all registered plugins
63
- */
64
- list() {
65
- return Array.from(this.plugins.values());
66
- }
67
- /**
68
- * Destroy all plugins
69
- */
70
- async destroy() {
71
- for (const plugin of this.plugins.values()) if (plugin.destroy) await plugin.destroy();
72
- this.plugins.clear();
73
- this.hooks.clear();
74
- this.initialized = false;
75
- }
76
- };
77
- /**
78
- * Logging plugin - logs all operations
79
- */
80
- function loggingPlugin(options = {}) {
81
- const level = options.level ?? "info";
82
- return {
83
- name: "logging",
84
- version: "1.0.0",
85
- description: "Logs all revenue operations",
86
- hooks: {
87
- "payment.create.after": async (ctx, input, next) => {
88
- ctx.logger[level]("Creating payment", {
89
- amount: input.amount,
90
- currency: input.currency
91
- });
92
- const result = await next();
93
- ctx.logger[level]("Payment created", { paymentIntentId: result?.paymentIntentId });
94
- return result;
95
- },
96
- "payment.verify.after": async (ctx, input, next) => {
97
- ctx.logger[level]("Verifying payment", { id: input.id });
98
- const result = await next();
99
- ctx.logger[level]("Payment verified", { verified: result?.verified });
100
- return result;
101
- },
102
- "payment.refund.after": async (ctx, input, next) => {
103
- ctx.logger[level]("Processing refund", {
104
- transactionId: input.transactionId,
105
- amount: input.amount
106
- });
107
- const result = await next();
108
- ctx.logger[level]("Refund processed", { refundId: result?.refundId });
109
- return result;
110
- }
111
- }
112
- };
113
- }
114
- /**
115
- * Audit plugin - records all operations for compliance
116
- */
117
- function auditPlugin(options = {}) {
118
- const entries = [];
119
- const store = options.store ?? (async (entry) => {
120
- entries.push(entry);
121
- });
122
- return {
123
- name: "audit",
124
- version: "1.0.0",
125
- description: "Audit trail for all operations",
126
- hooks: {
127
- "payment.create.after": async (ctx, input, next) => {
128
- const result = await next();
129
- await store({
130
- action: "payment.create",
131
- requestId: ctx.meta.requestId,
132
- timestamp: ctx.meta.timestamp,
133
- input: sanitizeInput(input),
134
- output: sanitizeOutput(result),
135
- idempotencyKey: ctx.meta.idempotencyKey
136
- });
137
- return result;
138
- },
139
- "payment.refund.after": async (ctx, input, next) => {
140
- const result = await next();
141
- await store({
142
- action: "payment.refund",
143
- requestId: ctx.meta.requestId,
144
- timestamp: ctx.meta.timestamp,
145
- input: sanitizeInput(input),
146
- output: sanitizeOutput(result),
147
- idempotencyKey: ctx.meta.idempotencyKey
148
- });
149
- return result;
150
- }
151
- }
152
- };
153
- }
154
- function sanitizeInput(input) {
155
- if (typeof input !== "object" || !input) return {};
156
- const sanitized = { ...input };
157
- delete sanitized.apiKey;
158
- delete sanitized.secretKey;
159
- delete sanitized.password;
160
- return sanitized;
161
- }
162
- function sanitizeOutput(output) {
163
- if (typeof output !== "object" || !output) return {};
164
- return { ...output };
165
- }
166
- /**
167
- * Metrics plugin - collects operation metrics
168
- */
169
- function metricsPlugin(options = {}) {
170
- const metrics = [];
171
- const record = options.onMetric ?? ((metric) => {
172
- metrics.push(metric);
173
- });
174
- return {
175
- name: "metrics",
176
- version: "1.0.0",
177
- description: "Collects operation metrics",
178
- hooks: { "payment.create.before": async (_ctx, input, next) => {
179
- const start = Date.now();
180
- try {
181
- const result = await next();
182
- record({
183
- name: "payment.create",
184
- duration: Date.now() - start,
185
- success: true,
186
- amount: input.amount,
187
- currency: input.currency
188
- });
189
- return result;
190
- } catch (error) {
191
- record({
192
- name: "payment.create",
193
- duration: Date.now() - start,
194
- success: false,
195
- error: error.message
196
- });
197
- throw error;
198
- }
199
- } }
200
- };
201
- }
202
- /**
203
- * Create a custom plugin
204
- */
205
- function definePlugin(plugin) {
206
- return plugin;
207
- }
208
-
209
- //#endregion
210
- export { metricsPlugin as a, loggingPlugin as i, auditPlugin as n, definePlugin as r, PluginManager as t };