-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patheslint.json
More file actions
1598 lines (1598 loc) · 153 KB
/
eslint.json
File metadata and controls
1598 lines (1598 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/client.ts",
"messages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 214,
"column": 14,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 214,
"endColumn": 17,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [6148, 6151], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [6148, 6151], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 217,
"column": 15,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 217,
"endColumn": 18,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [6205, 6208], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [6205, 6208], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
}
],
"suppressedMessages": [],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 2,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"source": "import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { BetterFetchResponse, BetterFetchOption, BetterFetch } from \"@better-fetch/fetch\";\n\nimport type { PaystackProduct, PaystackTransaction, Subscription } from \"./types\";\n\nimport type { paystack } from \"./index\";\n\nexport const paystackClient = <\n\tO extends {\n\t\tsubscription: boolean;\n\t},\n>(\n\t\t_options?: O,\n\t) => {\n\treturn {\n\t\tid: \"paystack\",\n\t\t$InferServerPlugin: {} as ReturnType<typeof paystack>,\n\t\tgetActions: ($fetch: BetterFetch) => {\n\t\t\tconst initializeTransaction = async (data: {\n\t\t\t\tplan?: string;\n\t\t\t\temail?: string;\n\t\t\t\tamount?: number;\n\t\t\t\treference?: string;\n\t\t\t\tmetadata?: Record<string, unknown>;\n\t\t\t\tcallbackUrl?: string;\n\t\t\t\tcallbackURL?: string;\n\t\t\t\tcurrency?: string;\n\t\t\t\tquantity?: number;\n\t\t\t\treferenceId?: string;\n\t\t\t\tproduct?: string;\n\t\t\t}, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\turl: string;\n\t\t\t\treference: string;\n\t\t\t\taccessCode: string;\n\t\t\t\tredirect: boolean;\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\turl: string;\n\t\t\t\t\treference: string;\n\t\t\t\t\taccessCode: string;\n\t\t\t\t\tredirect: boolean;\n\t\t\t\t}>(\"paystack/initialize-transaction\", {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tbody: data,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst verifyTransaction = async (data: { reference: string }, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\tstatus: string;\n\t\t\t\treference: string;\n\t\t\t\tdata: unknown;\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\tstatus: string;\n\t\t\t\t\treference: string;\n\t\t\t\t\tdata: unknown;\n\t\t\t\t}>(\"paystack/verify-transaction\", {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tbody: data,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst listTransactions = async (data: { query?: Record<string, unknown> } = {}, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\ttransactions: PaystackTransaction[];\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\ttransactions: PaystackTransaction[];\n\t\t\t\t}>(\"paystack/list-transactions\", {\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\tquery: data.query,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst listSubscriptions = async (data: { query?: Record<string, unknown> } = {}, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\tsubscriptions: Subscription[];\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\tsubscriptions: Subscription[];\n\t\t\t\t}>(\"paystack/list-subscriptions\", {\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\tquery: data.query,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst getSubscriptionManageLink = async (data: { subscriptionCode: string }, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\tlink: string;\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\tlink: string;\n\t\t\t\t}>(\"paystack/get-subscription-manage-link\", {\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\tquery: data,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst cancelSubscription = async (data: {\n\t\t\t\tsubscriptionCode: string;\n\t\t\t\temailToken?: string;\n\t\t\t}, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\tstatus: string;\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\tstatus: string;\n\t\t\t\t}>(\"paystack/disable-subscription\", {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tbody: data,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst restoreSubscription = async (data: {\n\t\t\t\tsubscriptionCode: string;\n\t\t\t\temailToken?: string;\n\t\t\t}, options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\tstatus: string;\n\t\t\t}>> => {\n\t\t\t\treturn $fetch<{\n\t\t\t\t\tstatus: string;\n\t\t\t\t}>(\"paystack/enable-subscription\", {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tbody: data,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\tsubscription: {\n\t\t\t\t\t/**\n * Initialize a transaction to upgrade or creating a subscription.\n */\n\t\t\t\t\tupgrade: initializeTransaction,\n\t\t\t\t\t/**\n * Initialize a payment to create a subscription.\n */\n\t\t\t\t\tcreate: initializeTransaction,\n\t\t\t\t\t/**\n * Disable a subscription.\n */\n\t\t\t\t\tcancel: cancelSubscription,\n\t\t\t\t\t/**\n * Enable a subscription.\n */\n\t\t\t\t\trestore: restoreSubscription,\n\t\t\t\t\t/**\n * List subscriptions for the user.\n */\n\t\t\t\t\tlist: listSubscriptions,\n\t\t\t\t\t/**\n * Get a link to manage the subscription on Paystack.\n */\n\t\t\t\t\tbillingPortal: getSubscriptionManageLink,\n\t\t\t\t\t/**\n * Aliases for legacy/demo usage.\n */\n\t\t\t\t\tlistLocal: listSubscriptions,\n\t\t\t\t\tmanageLink: getSubscriptionManageLink,\n\t\t\t\t\tdisable: cancelSubscription,\n\t\t\t\t\tenable: restoreSubscription,\n\t\t\t\t},\n\t\t\t\tpaystack: {\n\t\t\t\t\ttransaction: {\n\t\t\t\t\t\tinitialize: initializeTransaction,\n\t\t\t\t\t\tverify: verifyTransaction,\n\t\t\t\t\t\tlist: listTransactions,\n\t\t\t\t\t},\n\t\t\t\t\tsubscription: {\n\t\t\t\t\t\tcreate: initializeTransaction,\n\t\t\t\t\t\tupgrade: initializeTransaction,\n\t\t\t\t\t\tcancel: cancelSubscription,\n\t\t\t\t\t\trestore: restoreSubscription,\n\t\t\t\t\t\tlist: listSubscriptions,\n\t\t\t\t\t\tbillingPortal: getSubscriptionManageLink,\n\t\t\t\t\t\tlistLocal: listSubscriptions,\n\t\t\t\t\t\tmanageLink: getSubscriptionManageLink,\n\t\t\t\t\t\tdisable: cancelSubscription,\n\t\t\t\t\t\tenable: restoreSubscription,\n\t\t\t\t\t},\n\t\t\t\t\tinitializeTransaction,\n\t\t\t\t\tverifyTransaction,\n\t\t\t\t\tlistTransactions,\n\t\t\t\t\tlistSubscriptions,\n\t\t\t\t\tgetSubscriptionManageLink,\n\t\t\t\t\tgetConfig: async (): Promise<BetterFetchResponse<Record<string, unknown>>> => {\n\t\t\t\t\t\treturn $fetch<Record<string, unknown>>(\"paystack/get-config\", {\n\t\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tsyncProducts: async (): Promise<BetterFetchResponse<{ status: string; count: number }>> => {\n\t\t\t\t\t\treturn $fetch<{ status: string; count: number }>(\"paystack/sync-products\", {\n\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tsyncPlans: async (): Promise<BetterFetchResponse<{ status: string; count: number }>> => {\n\t\t\t\t\t\treturn $fetch<{ status: string; count: number }>(\"paystack/sync-plans\", {\n\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tlistProducts: async (options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\t\t\tproducts: PaystackProduct[];\n\t\t\t\t\t}>> => {\n\t\t\t\t\t\treturn $fetch<{\n\t\t\t\t\t\t\tproducts: PaystackProduct[];\n\t\t\t\t\t\t}>(\"paystack/list-products\", {\n\t\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tlistPlans: async (options?: BetterFetchOption): Promise<BetterFetchResponse<{\n\t\t\t\t\t\tplans: any[];\n\t\t\t\t\t}>> => {\n\t\t\t\t\t\treturn $fetch<{\n\t\t\t\t\t\t\tplans: any[];\n\t\t\t\t\t\t}>(\"paystack/list-plans\", {\n\t\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t} satisfies BetterAuthClientPlugin;\n};\n",
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/index.ts",
"messages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 94,
"column": 16,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 94,
"endColumn": 19,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [3161, 3164], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [3161, 3164], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 151,
"column": 67,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 151,
"endColumn": 70,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [5304, 5307], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [5304, 5307], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 165,
"column": 42,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 165,
"endColumn": 45,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [5998, 6001], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [5998, 6001], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
}
],
"suppressedMessages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 159,
"column": 42,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 159,
"endColumn": 45,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [5786, 5789], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [5786, 5789], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 228,
"column": 51,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 228,
"endColumn": 54,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [8144, 8147], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [8144, 8147], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 228,
"column": 56,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 228,
"endColumn": 59,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [8149, 8152], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [8149, 8152], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 231,
"column": 41,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 231,
"endColumn": 44,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [8296, 8299], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [8296, 8299], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 231,
"column": 46,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 231,
"endColumn": 49,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [8301, 8304], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [8301, 8304], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
}
],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 3,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"source": "import { defineErrorCodes } from \"@better-auth/core/utils\";\nimport type { AuthContext, GenericEndpointContext } from \"better-auth\";\nimport { defu } from \"defu\";\n\nimport {\n\tdisablePaystackSubscription,\n\tenablePaystackSubscription,\n\tinitializeTransaction,\n\tlistSubscriptions,\n\tlistTransactions,\n\tpaystackWebhook,\n\tverifyTransaction,\n\tgetConfig,\n\tgetSubscriptionManageLink,\n\tPAYSTACK_ERROR_CODES,\n\tcreateSubscription,\n\tupgradeSubscription,\n\tcancelSubscription,\n\trestoreSubscription,\n\tchargeRecurringSubscription,\n\tsyncProducts,\n\tlistProducts,\n\tsyncPlans,\n\tlistPlans,\n} from \"./routes\";\nimport { getSchema } from \"./schema\";\nimport { checkSeatLimit, checkTeamLimit, getOrganizationSubscription } from \"./limits\";\nimport { getPlanByName } from \"./utils\";\nimport type {\n\tPaystackNodeClient,\n\tPaystackClientLike,\n\tPaystackOptions,\n\tPaystackPlan,\n\tSubscription,\n\tSubscriptionOptions,\n\tPaystackProduct,\n\tMember,\n\tUser,\n\tPaystackCustomerResponse,\n} from \"./types\";\nimport { getPaystackOps, unwrapSdkResult } from \"./paystack-sdk\";\n\nconst INTERNAL_ERROR_CODES = defineErrorCodes({\n\t...PAYSTACK_ERROR_CODES,\n});\n\nexport const paystack = <\n TPaystackClient extends PaystackClientLike = PaystackNodeClient,\n TMetadata = Record<string, unknown>,\n TLimits = Record<string, unknown>,\n O extends PaystackOptions<TPaystackClient, TMetadata, TLimits> = PaystackOptions<TPaystackClient, TMetadata, TLimits>,\n>(\n\t\toptions: O,\n\t) => {\n\tconst res = {\n\t\tid: \"paystack\",\n\t\tendpoints: {\n\t\t\tinitializeTransaction: initializeTransaction(options),\n\t\t\tverifyTransaction: verifyTransaction(options),\n\t\t\tlistSubscriptions: listSubscriptions(options),\n\t\t\tpaystackWebhook: paystackWebhook(options),\n\t\t\tlistTransactions: listTransactions(options),\n\t\t\tgetConfig: getConfig(options),\n\t\t\tdisableSubscription: disablePaystackSubscription(options),\n\t\t\tenableSubscription: enablePaystackSubscription(options),\n\t\t\tgetSubscriptionManageLink: getSubscriptionManageLink(options),\n\t\t\tsubscriptionManageLink: getSubscriptionManageLink(options, \"/paystack/subscription/manage-link\"), // Historical alias\n\t\t\tcreateSubscription: createSubscription(options),\n\t\t\tupgradeSubscription: upgradeSubscription(options),\n\t\t\tcancelSubscription: cancelSubscription(options),\n\t\t\trestoreSubscription: restoreSubscription(options),\n\t\t\tchargeRecurringSubscription: chargeRecurringSubscription(options),\n\t\t\tsyncProducts: syncProducts(options),\n\t\t\tlistProducts: listProducts(options),\n\t\t\tsyncPlans: syncPlans(options),\n\t\t\tlistPlans: listPlans(options),\n\t\t},\n\t\tschema: getSchema(options),\n\t\tinit: (ctx: AuthContext) => {\n\t\t\treturn {\n\t\t\t\toptions: {\n\t\t\t\t\tdatabaseHooks: {\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tcreate: {\n\t\t\t\t\t\t\t\tasync after(user: { id: string; email: string; name?: string | null }, hookCtx?: GenericEndpointContext | null) {\n\t\t\t\t\t\t\t\t\tif (hookCtx === undefined || hookCtx === null || options.createCustomerOnSignUp !== true) return;\n\n\t\t\t\t\t\t\t\t\tconst paystackOps = getPaystackOps(options.paystackClient as PaystackClientLike);\n\t\t\t\t\t\t\t\t\tconst raw = await paystackOps.customerCreate({\n\t\t\t\t\t\t\t\t\t\temail: user.email,\n\t\t\t\t\t\t\t\t\t\tfirst_name: user.name ?? undefined,\n\t\t\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t\t\tuserId: user.id,\n\t\t\t\t\t\t\t\t\t\t} as any,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tconst sdkRes = unwrapSdkResult<PaystackCustomerResponse>(raw);\n\t\t\t\t\t\t\t\t\tconst customerCode = (sdkRes?.customer_code as string | undefined)\n\t\t\t\t\t\t\t\t\t\t?? (sdkRes?.data as Record<string, unknown>)?.customer_code as string | undefined;\n\n\t\t\t\t\t\t\t\t\tif (customerCode === undefined || customerCode === null) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait ctx.adapter.update({\n\t\t\t\t\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: user.id }],\n\t\t\t\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\t\t\t\tpaystackCustomerCode: customerCode,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\torganization: options.organization?.enabled === true\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tcreate: {\n\t\t\t\t\t\t\t\t\tasync after(org: { id: string; name: string; email?: string | null }, hookCtx: GenericEndpointContext | null) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tconst extraCreateParams = options.organization?.getCustomerCreateParams\n\t\t\t\t\t\t\t\t\t\t\t\t? await options.organization.getCustomerCreateParams(org, hookCtx!)\n\t\t\t\t\t\t\t\t\t\t\t\t: {};\n\n\t\t\t\t\t\t\t\t\t\t\tlet targetEmail = org.email;\n\t\t\t\t\t\t\t\t\t\t\tif (targetEmail === undefined || targetEmail === null) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst ownerMember = await ctx.adapter.findOne<Member>({\n\t\t\t\t\t\t\t\t\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\t\t\t\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ field: \"organizationId\", value: org.id },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ field: \"role\", value: \"owner\" }\n\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\tif (ownerMember !== null && ownerMember !== undefined) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst ownerUser = await ctx.adapter.findOne<User>({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: ownerMember.userId }]\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\ttargetEmail = ownerUser?.email;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (targetEmail === undefined || targetEmail === null) return;\n\n\t\t\t\t\t\t\t\t\t\t\tconst params = defu(\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\temail: targetEmail,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfirst_name: org.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmetadata: { organizationId: org.id },\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\textraCreateParams,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tconst paystackOps = getPaystackOps(options.paystackClient as PaystackClientLike);\n\t\t\t\t\t\t\t\t\t\t\tconst raw = await paystackOps.customerCreate(params as any);\n\t\t\t\t\t\t\t\t\t\t\tconst sdkRes = unwrapSdkResult<PaystackCustomerResponse>(raw);\n\t\t\t\t\t\t\t\t\t\t\tconst customerCode = (sdkRes?.customer_code as string | undefined)\n ?? (sdkRes?.data as Record<string, unknown>)?.customer_code as string | undefined;\n\n\t\t\t\t\t\t\t\t\t\t\tif (customerCode === undefined || customerCode === null) return;\n\n\t\t\t\t\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\t\t\t\t\t\t\t\tawait (ctx.internalAdapter as any).updateOrganization(org.id, {\n\t\t\t\t\t\t\t\t\t\t\t\tpaystackCustomerCode: customerCode,\n\t\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\t\t\tawait options.organization?.onCustomerCreate?.(\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tpaystackCustomer: sdkRes as any,\n\t\t\t\t\t\t\t\t\t\t\t\t\torganization: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t...org,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpaystackCustomerCode: customerCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n hookCtx!,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\t\t\t\t\t(ctx as unknown as AuthContext).logger.error(\"Failed to create Paystack customer for organization\", error);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t},\n\t\t\t\t\tmember: {\n\t\t\t\t\t\tcreate: {\n\t\t\t\t\t\t\tbefore: async (member: { organizationId: string }, ctx: GenericEndpointContext | null | undefined) => {\n\t\t\t\t\t\t\t\tif (options.subscription?.enabled === true && member.organizationId && ctx !== null && ctx !== undefined) {\n\t\t\t\t\t\t\t\t\tawait checkSeatLimit(ctx, member.organizationId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tinvitation: {\n\t\t\t\t\t\tcreate: {\n\t\t\t\t\t\t\tbefore: async (invitation: { organizationId: string }, ctx: GenericEndpointContext | null | undefined) => {\n\t\t\t\t\t\t\t\tif (options.subscription?.enabled === true && invitation.organizationId && ctx !== null && ctx !== undefined) {\n\t\t\t\t\t\t\t\t\tawait checkSeatLimit(ctx, invitation.organizationId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tteam: {\n\t\t\t\t\t\tcreate: {\n\t\t\t\t\t\t\tbefore: async (team: { organizationId: string }, ctx: GenericEndpointContext | null | undefined) => {\n\t\t\t\t\t\t\t\tif (options.subscription?.enabled === true && team.organizationId && ctx !== null && ctx !== undefined) {\n\t\t\t\t\t\t\t\t\tconst subscription = await getOrganizationSubscription(ctx, team.organizationId);\n\t\t\t\t\t\t\t\t\tif (subscription !== null && subscription !== undefined) {\n\t\t\t\t\t\t\t\t\t\tconst plan = await getPlanByName(options, subscription.plan);\n\t\t\t\t\t\t\t\t\t\tconst limits = plan?.limits;\n\t\t\t\t\t\t\t\t\t\tconst maxTeams = limits?.teams as number | undefined;\n\n\t\t\t\t\t\t\t\t\t\tif (typeof maxTeams === \"number\") {\n\t\t\t\t\t\t\t\t\t\t\tawait checkTeamLimit(ctx, team.organizationId, maxTeams);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t$ERROR_CODES: INTERNAL_ERROR_CODES,\n\t};\n\n\treturn res;\n};\n\nexport type PaystackPlugin<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n O extends PaystackOptions<PaystackClientLike, any, any> = PaystackOptions,\n> = ReturnType<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof paystack<PaystackClientLike, any, any, O>\n>;\n\nexport type { Subscription, SubscriptionOptions, PaystackPlan, PaystackOptions, PaystackProduct };\n",
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/limits.ts",
"messages": [],
"suppressedMessages": [],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 0,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/middleware.ts",
"messages": [],
"suppressedMessages": [],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 0,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/paystack-sdk.ts",
"messages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 59,
"column": 61,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 59,
"endColumn": 64,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [1721, 1724], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [1721, 1724], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 67,
"column": 22,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 67,
"endColumn": 25,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [2022, 2025], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [2022, 2025], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
}
],
"suppressedMessages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 151,
"column": 20,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 151,
"endColumn": 23,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [5204, 5207], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [5204, 5207], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 155,
"column": 70,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 155,
"endColumn": 73,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [5408, 5411], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [5408, 5411], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
}
],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 2,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"source": "import type {\n\tPaystackClientLike,\n\tPaystackCustomerCreateInput,\n\tPaystackCustomerUpdateInput,\n\tPaystackNodeClient,\n\tPaystackOpenApiFetchResponse,\n\tPaystackSubscriptionFetchInit,\n\tPaystackSubscriptionCreateInput,\n\tPaystackSubscriptionToggleInput,\n\tPaystackTransactionInitializeInput,\n\tPaystackTransactionChargeAuthorizationInput,\n} from \"./types\";\n\nfunction isOpenApiFetchResponse(\n\tvalue: unknown,\n): value is PaystackOpenApiFetchResponse {\n\treturn (\n\t\tvalue !== null &&\n\t\tvalue !== undefined &&\n typeof value === \"object\" &&\n (\"data\" in value || \"error\" in value || \"response\" in value)\n\t);\n}\n\nexport function unwrapSdkResult<T = unknown>(result: unknown): T {\n\tif (isOpenApiFetchResponse(result)) {\n\t\tif (result.error !== undefined && result.error !== null) {\n\t\t\tthrow new Error(typeof result.error === \"string\" ? result.error : JSON.stringify(result.error));\n\t\t}\n\t\treturn (result.data as T) ?? (result as T);\n\t}\n\tif (result !== null && result !== undefined && typeof result === \"object\" && \"data\" in result) {\n\t\tconst data = (result as { data: unknown }).data;\n\t\t// If data is also an object with a data property, unwrap it (legacy SDK style)\n\t\tif (data !== null && typeof data === \"object\" && \"data\" in data) {\n\t\t\treturn (data as { data: T }).data;\n\t\t}\n\t\treturn data as T;\n\t}\n\treturn result as T;\n}\n\n\n\n\n\ntype TransactionInitializeBody = Parameters<PaystackNodeClient[\"transaction_initialize\"]>[0] extends {\n\tbody?: infer B;\n}\n\t? B\n\t: never;\n\nexport function getPaystackOps(\n\tpaystackClient: PaystackClientLike,\n) {\n\treturn {\n\t\tcustomerCreate: (params: PaystackCustomerCreateInput) => {\n\t\t\tif (paystackClient?.customer_create !== undefined) {\n\t\t\t\treturn paystackClient.customer_create({ body: params as any });\n\t\t\t}\n\t\t\treturn paystackClient?.customer?.create?.(params);\n\t\t},\n\t\tcustomerUpdate: (code: string, params: PaystackCustomerUpdateInput) => {\n\t\t\tif (paystackClient?.customer_update !== undefined) {\n\t\t\t\treturn paystackClient.customer_update({\n\t\t\t\t\tparams: { path: { code } },\n\t\t\t\t\tbody: params as any,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.customer?.update?.(code, params);\n\t\t},\n\t\ttransactionInitialize: (body: PaystackTransactionInitializeInput) => {\n\t\t\tif (paystackClient?.transaction_initialize !== undefined) {\n\t\t\t\treturn paystackClient.transaction_initialize({\n\t\t\t\t\tbody: body as TransactionInitializeBody,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.transaction?.initialize?.(body);\n\t\t},\n\t\ttransactionVerify: (reference: string) => {\n\t\t\tif (paystackClient?.transaction_verify !== undefined) {\n\t\t\t\treturn paystackClient.transaction_verify({\n\t\t\t\t\tparams: { path: { reference } },\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.transaction?.verify?.(reference);\n\t\t},\n\t\tsubscriptionCreate: (body: PaystackSubscriptionCreateInput) => {\n\t\t\tif (paystackClient?.subscription_create !== undefined) {\n\t\t\t\treturn paystackClient.subscription_create({ body });\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.create?.(body);\n\t\t},\n\t\tsubscriptionDisable: (body: PaystackSubscriptionToggleInput) => {\n\t\t\tif (paystackClient?.subscription_disable !== undefined) {\n\t\t\t\treturn paystackClient.subscription_disable({ body });\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.disable?.(body);\n\t\t},\n\t\tsubscriptionEnable: (body: PaystackSubscriptionToggleInput) => {\n\t\t\tif (paystackClient?.subscription_enable !== undefined) {\n\t\t\t\treturn paystackClient.subscription_enable({ body });\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.enable?.(body);\n\t\t},\n\t\tsubscriptionFetch: async (idOrCode: string) => {\n\t\t\tif (paystackClient?.subscription_fetch !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await paystackClient.subscription_fetch({\n\t\t\t\t\t\tparams: { path: { code: idOrCode } },\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\tconst compatFetch = paystackClient.subscription_fetch as unknown as (\n init: PaystackSubscriptionFetchInit,\n ) => Promise<unknown>;\n\t\t\t\t\treturn compatFetch({\n\t\t\t\t\t\tparams: { path: { id_or_code: idOrCode } },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.fetch?.(idOrCode);\n\t\t},\n\t\tsubscriptionManageLink: (code: string) => {\n\t\t\tif (paystackClient?.subscription_manageLink !== undefined) {\n\t\t\t\treturn paystackClient.subscription_manageLink({\n\t\t\t\t\tparams: { path: { code } },\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Fallback for snake_case if older SDK version or different generator\n\t\t\tif (paystackClient?.subscription_manage_link !== undefined) {\n\t\t\t\treturn paystackClient.subscription_manage_link({\n\t\t\t\t\tparams: { path: { code } },\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.manage?.link?.(code);\n\t\t},\n\t\tsubscriptionManageEmail: (code: string, email: string) => {\n\t\t\tif (paystackClient?.subscription_manageEmail !== undefined) {\n\t\t\t\treturn paystackClient.subscription_manageEmail({\n\t\t\t\t\tparams: { path: { code } },\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.subscription?.manage?.email?.(code, email);\n\t\t},\n\t\ttransactionChargeAuthorization: (body: PaystackTransactionChargeAuthorizationInput) => {\n\t\t\tif (paystackClient?.transaction_chargeAuthorization !== undefined) {\n\t\t\t\treturn paystackClient.transaction_chargeAuthorization({\n\t\t\t\t\t \n\t\t\t\t\t// casting to avoid deep type issues with metadata\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\t\tbody: body as any, // casting to avoid deep type issues with metadata\n\t\t\t\t});\n\t\t\t}\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\treturn paystackClient?.transaction?.chargeAuthorization?.(body as any);\n\t\t},\n\t\tproductList: () => {\n\t\t\tif (paystackClient?.product_list !== undefined) {\n\t\t\t\treturn paystackClient.product_list();\n\t\t\t}\n\t\t\treturn paystackClient?.product?.list?.();\n\t\t},\n\t\tproductFetch: (idOrCode: string) => {\n\t\t\tif (paystackClient?.product_fetch !== undefined) {\n\t\t\t\treturn paystackClient.product_fetch({\n\t\t\t\t\tparams: { path: { id_or_code: idOrCode } },\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.product?.fetch?.(idOrCode);\n\t\t},\n\t\tproductCreate: (params: Record<string, unknown>) => {\n\t\t\tif (paystackClient?.product_create !== undefined) {\n\t\t\t\treturn paystackClient.product_create({ body: params });\n\t\t\t}\n\t\t\treturn paystackClient?.product?.create?.(params);\n\t\t},\n\t\tproductUpdate: (idOrCode: string, params: Record<string, unknown>) => {\n\t\t\tif (paystackClient?.product_update !== undefined) {\n\t\t\t\treturn paystackClient.product_update({\n\t\t\t\t\tparams: { path: { id_or_code: idOrCode } },\n\t\t\t\t\tbody: params,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.product?.update?.(idOrCode, params);\n\t\t},\n\t\tproductDelete: (idOrCode: string) => {\n\t\t\tif (paystackClient?.product_delete !== undefined) {\n\t\t\t\treturn paystackClient.product_delete({\n\t\t\t\t\tparams: { path: { id_or_code: idOrCode } },\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn paystackClient?.product?.delete?.(idOrCode);\n\t\t},\n\t\tplanList: () => {\n\t\t\tif (paystackClient?.plan_list !== undefined) {\n\t\t\t\treturn paystackClient.plan_list();\n\t\t\t}\n\t\t\treturn paystackClient?.plan?.list?.();\n\t\t},\n\t};\n}\n",
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/paystack.test.ts",
"messages": [],
"suppressedMessages": [],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 0,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/routes.ts",
"messages": [
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly.",
"line": 153,
"column": 11,
"nodeType": "ChainExpression",
"messageId": "conditionErrorNullableString",
"endLine": 153,
"endColumn": 31,
"suggestions": [
{
"messageId": "conditionFixCompareNullish",
"fix": { "range": [5573, 5593], "text": "(transaction?.product) != null" },
"desc": "Change condition to check for null/undefined (`value != null`)"
},
{
"messageId": "conditionFixDefaultEmptyString",
"fix": { "range": [5573, 5593], "text": "(transaction?.product) ?? \"\"" },
"desc": "Explicitly treat nullish value the same as an empty string (`value ?? \"\"`)"
},
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [5573, 5593], "text": "Boolean((transaction?.product))" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly.",
"line": 285,
"column": 26,
"nodeType": "Identifier",
"messageId": "conditionErrorNullableString",
"endLine": 285,
"endColumn": 41,
"suggestions": [
{
"messageId": "conditionFixCompareNullish",
"fix": { "range": [11796, 11811], "text": "(nextPaymentDate != null)" },
"desc": "Change condition to check for null/undefined (`value != null`)"
},
{
"messageId": "conditionFixDefaultEmptyString",
"fix": { "range": [11796, 11811], "text": "(nextPaymentDate ?? \"\")" },
"desc": "Explicitly treat nullish value the same as an empty string (`value ?? \"\"`)"
},
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [11796, 11811], "text": "(Boolean(nextPaymentDate))" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly.",
"line": 807,
"column": 10,
"nodeType": "ChainExpression",
"messageId": "conditionErrorNullableString",
"endLine": 807,
"endColumn": 30,
"suggestions": [
{
"messageId": "conditionFixCompareNullish",
"fix": { "range": [32699, 32719], "text": "(transaction?.product) != null" },
"desc": "Change condition to check for null/undefined (`value != null`)"
},
{
"messageId": "conditionFixDefaultEmptyString",
"fix": { "range": [32699, 32719], "text": "(transaction?.product) ?? \"\"" },
"desc": "Explicitly treat nullish value the same as an empty string (`value ?? \"\"`)"
},
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [32699, 32719], "text": "Boolean((transaction?.product))" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected any value in conditional. An explicit comparison or type conversion is required.",
"line": 1241,
"column": 7,
"nodeType": "CallExpression",
"messageId": "conditionErrorAny",
"endLine": 1241,
"endColumn": 42,
"suggestions": [
{
"messageId": "conditionFixCastBoolean",
"fix": {
"range": [50575, 50610],
"text": "(Boolean(subscriptionCode.startsWith(\"LOC_\")))"
},
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected any value in conditional. An explicit comparison or type conversion is required.",
"line": 1241,
"column": 46,
"nodeType": "CallExpression",
"messageId": "conditionErrorAny",
"endLine": 1241,
"endColumn": 87,
"suggestions": [
{
"messageId": "conditionFixCastBoolean",
"fix": {
"range": [50614, 50655],
"text": "(Boolean(subscriptionCode.startsWith(\"sub_local_\")))"
},
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "no-console",
"severity": 1,
"message": "Unexpected console statement.",
"line": 1288,
"column": 4,
"nodeType": "MemberExpression",
"messageId": "unexpected",
"endLine": 1288,
"endColumn": 17,
"suggestions": [
{
"fix": { "range": [51994, 52045], "text": "" },
"messageId": "removeConsole",
"data": { "propertyName": "error" },
"desc": "Remove the console.error()."
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected any value in conditional. An explicit comparison or type conversion is required.",
"line": 1316,
"column": 17,
"nodeType": "MemberExpression",
"messageId": "conditionErrorAny",
"endLine": 1316,
"endColumn": 33,
"suggestions": [
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [53176, 53192], "text": "(Boolean(product.metadata))" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1394,
"column": 57,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1394,
"endColumn": 60,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [55350, 55353], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [55350, 55353], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected any value in conditional. An explicit comparison or type conversion is required.",
"line": 1407,
"column": 17,
"nodeType": "MemberExpression",
"messageId": "conditionErrorAny",
"endLine": 1407,
"endColumn": 30,
"suggestions": [
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [55694, 55707], "text": "(Boolean(plan.metadata))" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/strict-boolean-expressions",
"severity": 1,
"message": "Unexpected any value in conditional. An explicit comparison or type conversion is required.",
"line": 1411,
"column": 10,
"nodeType": "Identifier",
"messageId": "conditionErrorAny",
"endLine": 1411,
"endColumn": 18,
"suggestions": [
{
"messageId": "conditionFixCastBoolean",
"fix": { "range": [55800, 55808], "text": "Boolean(existing)" },
"desc": "Explicitly convert value to a boolean (`Boolean(value)`)"
}
]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1451,
"column": 54,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1451,
"endColumn": 57,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [56745, 56748], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [56745, 56748], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
]
}
],
"suppressedMessages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 28,
"column": 63,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 28,
"endColumn": 66,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [1101, 1104], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [1101, 1104], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 28,
"column": 68,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 28,
"endColumn": 71,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [1106, 1109], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [1106, 1109], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "no-restricted-globals",
"severity": 2,
"message": "Unexpected use of 'Buffer'. Buffer is deprecated. Use `Uint8Array` instead.",
"line": 1020,
"column": 9,
"nodeType": "Identifier",
"messageId": "customMessage",
"endLine": 1020,
"endColumn": 15,
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1294,
"column": 129,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1294,
"endColumn": 132,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [52419, 52422], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [52419, 52422], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1294,
"column": 165,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1294,
"endColumn": 168,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [52455, 52458], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [52455, 52458], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1386,
"column": 126,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1386,
"endColumn": 129,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [55061, 55064], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [55061, 55064], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1386,
"column": 162,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1386,
"endColumn": 165,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [55097, 55100], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [55097, 55100], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
},
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 1574,
"column": 32,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 1574,
"endColumn": 35,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [60757, 60760], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [60757, 60760], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."
}
],
"suppressions": [{ "kind": "directive", "justification": "" }]
}
],
"errorCount": 0,
"fatalErrorCount": 0,
"warningCount": 11,
"fixableErrorCount": 0,
"fixableWarningCount": 0,
"source": "import { createAuthEndpoint } from \"@better-auth/core/api\";\nimport { defineErrorCodes } from \"@better-auth/core/utils\";\nimport { HIDE_METADATA } from \"better-auth\";\nimport {\n\tAPIError,\n\tgetSessionFromCtx,\n\toriginCheck,\n\tsessionMiddleware,\n} from \"better-auth/api\";\nimport * as z from \"zod/v4\";\nimport type { GenericEndpointContext } from \"better-auth\";\n\nimport type { InputPaystackTransaction, InputPaystackProduct, InputSubscription, PaystackOptions, PaystackTransaction, Subscription, Organization, Member, User, PaystackClientLike, PaystackWebhookPayload } from \"./types\";\nimport {\n\tsyncProductQuantityFromPaystack,\n\tgetPlanByName,\n\tgetPlans,\n\tgetProductByName,\n\tgetProducts,\n\tvalidateMinAmount,\n\tgetNextPeriodEnd,\n} from \"./utils\";\nimport type { PaystackPlan, PaystackProduct, PaystackSubscriptionResponse, PaystackTransactionResponse } from \"./types\";\nimport { referenceMiddleware } from \"./middleware\";\nimport { getPaystackOps, unwrapSdkResult } from \"./paystack-sdk\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyPaystackOptions = PaystackOptions<PaystackClientLike, any, any>;\n\nconst PAYSTACK_ERROR_CODES = defineErrorCodes({\n\tSUBSCRIPTION_NOT_FOUND: \"Subscription not found\",\n\tSUBSCRIPTION_PLAN_NOT_FOUND: \"Subscription plan not found\",\n\tUNABLE_TO_CREATE_CUSTOMER: \"Unable to create customer\",\n\tFAILED_TO_INITIALIZE_TRANSACTION: \"Failed to initialize transaction\",\n\tFAILED_TO_VERIFY_TRANSACTION: \"Failed to verify transaction\",\n\tFAILED_TO_DISABLE_SUBSCRIPTION: \"Failed to disable subscription\",\n\tFAILED_TO_ENABLE_SUBSCRIPTION: \"Failed to enable subscription\",\n\tEMAIL_VERIFICATION_REQUIRED:\n \"Email verification is required before you can subscribe to a plan\",\n});\n\nasync function hmacSha512Hex(secret: string, message: string): Promise<string> {\n\tconst encoder = new TextEncoder();\n\tconst keyData = encoder.encode(secret);\n\tconst msgData = encoder.encode(message);\n\n\tconst crypto = globalThis.crypto;\n\tif (crypto !== undefined && crypto !== null && \"subtle\" in crypto) {\n\t\tconst subtle = crypto.subtle;\n\t\tconst key = await subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tkeyData,\n\t\t\t{ name: \"HMAC\", hash: \"SHA-512\" },\n\t\t\tfalse,\n\t\t\t[\"sign\"],\n\t\t);\n\t\tconst signature = await subtle.sign(\"HMAC\", key, msgData);\n\t\treturn Array.from(new Uint8Array(signature))\n\t\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t\t.join(\"\");\n\t}\n\n\tconst { createHmac } = await import(\"node:crypto\");\n\treturn createHmac(\"sha512\", secret).update(message).digest(\"hex\");\n}\n\nexport const paystackWebhook = (options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/webhook\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tmetadata: {\n\t\t\t\t...HIDE_METADATA,\n\t\t\t\topenapi: {\n\t\t\t\t\toperationId: \"handlePaystackWebhook\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tcloneRequest: true,\n\t\t\tdisableBody: true,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst request = (ctx as GenericEndpointContext & { requestClone?: Request }).requestClone ?? ctx.request;\n\t\t\tif (!request) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Request object is missing from context\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst payload = await request.text();\n\t\t\tconst headers = (ctx as GenericEndpointContext & { headers?: Headers }).headers ?? (ctx.request as unknown as { headers: Headers })?.headers;\n\t\t\tconst signature = headers?.get(\"x-paystack-signature\") as\n | string\n | null\n | undefined;\n\n\t\t\tif (signature === undefined || signature === null || signature === \"\") {\n\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\tmessage: \"Missing x-paystack-signature header\",\n\t\t\t\t\tstatus: 401,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst expected = await hmacSha512Hex(options.paystackWebhookSecret, payload);\n\t\t\tif (expected !== signature) {\n\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\tmessage: \"Invalid Paystack webhook signature\",\n\t\t\t\t\tstatus: 401,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tinterface WebhookData {\n\t\t\t\tsubscription_code?: string;\n\t\t\t\tcustomer_code?: string;\n\t\t\t\tcode?: string;\n\t\t\t\tplan_code?: string;\n\t\t\t\tplan?: string | { plan_code?: string };\n\t\t\t\tcustomer?: { customer_code?: string; code?: string; email?: string };\n\t\t\t\tsubscription?: { subscription_code?: string };\n\t\t\t\tnext_payment_date?: string;\n\t\t\t\tmetadata?: unknown;\n\t\t\t\t[key: string]: unknown;\n\t\t\t}\n\n\t\t\tconst event = JSON.parse(payload) as PaystackWebhookPayload<WebhookData>;\n\t\t\tconst eventName = event.event;\n\t\t\tconst data = event.data;\n\n\t\t\t// Core Transaction Status Sync (Applies to both one-time and recurring)\n\t\t\tif (eventName === \"charge.success\") {\n\t\t\t\tconst reference = (data as Record<string, unknown> | undefined)?.reference as string | undefined;\n\t\t\t\tconst paystackId = (data as Record<string, unknown> | undefined)?.id !== undefined && (data as Record<string, unknown> | undefined)?.id !== null ? String((data as Record<string, unknown>).id) : undefined;\n\t\t\t\tif (reference !== undefined && reference !== null && reference !== \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\t\t\t\tpaystackId,\n\t\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// Transaction record might not exist yet (e.g. webhook arrives before local record)\n\t\t\t\t\t\tctx.context.logger.warn(\"Failed to update transaction status for charge.success\", e);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Sync product quantity from Paystack after successful charge\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst transaction = await ctx.context.adapter.findOne<PaystackTransaction>({\n\t\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (transaction?.product) {\n\t\t\t\t\t\t\tawait syncProductQuantityFromPaystack(ctx as GenericEndpointContext, transaction.product, options.paystackClient);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.context.logger.warn(\"Failed to sync product quantity\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (eventName === \"charge.failure\") {\n\t\t\t\tconst reference = (data as Record<string, unknown> | undefined)?.reference as string | undefined;\n\t\t\t\tif (reference !== undefined && reference !== null && reference !== \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.context.logger.warn(\"Failed to update transaction status for charge.failure\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Best-effort local state sync for subscription lifecycle.\n\t\t\tif (options.subscription?.enabled === true) {\n\t\t\t\ttry {\n\n\t\t\t\t\tif (eventName === \"subscription.create\") {\n\t\t\t\t\t\tconst subscriptionCode =\n data?.subscription_code ??\n data?.subscription?.subscription_code ??\n data?.code;\n\t\t\t\t\t\tconst customerCode =\n data?.customer?.customer_code ??\n data?.customer_code ??\n data?.customer?.code;\n\t\t\t\t\t\tconst planCode =\n (typeof data?.plan === \"object\" ? data.plan?.plan_code : undefined) ?? data?.plan_code ?? (typeof data?.plan === \"string\" ? data.plan : undefined);\n\n\t\t\t\t\t\tlet metadata: unknown = data?.metadata;\n\t\t\t\t\t\tif (typeof metadata === \"string\") {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tmetadata = JSON.parse(metadata);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// ignore\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst referenceIdFromMetadata =\n typeof metadata === \"object\" && metadata !== null\n \t? ((metadata as Record<string, unknown>).referenceId as string | undefined)\n \t: undefined;\n\n\t\t\t\t\t\tlet planNameFromMetadata =\n typeof metadata === \"object\" && metadata !== null\n \t? ((metadata as Record<string, unknown>).plan as string | undefined)\n \t: undefined;\n\t\t\t\t\t\tif (typeof planNameFromMetadata === \"string\") {\n\t\t\t\t\t\t\tplanNameFromMetadata = planNameFromMetadata.toLowerCase();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst plans = await getPlans(options.subscription);\n\t\t\t\t\t\tconst planFromCode = (planCode !== undefined && planCode !== null && planCode !== \"\")\n\t\t\t\t\t\t\t? plans.find((p) => p.planCode !== undefined && p.planCode !== null && p.planCode === planCode)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst planPart = planFromCode?.name ?? planNameFromMetadata;\n\t\t\t\t\t\tconst planName = planPart !== undefined && planPart !== null && planPart !== \"\" ? planPart.toLowerCase() : undefined;\n\n\t\t\t\t\t\tif (subscriptionCode !== undefined && subscriptionCode !== null && subscriptionCode !== \"\") {\n\t\t\t\t\t\t\tconst where: { field: string; value: string | number | boolean | null }[] = [];\n\t\t\t\t\t\t\tif (referenceIdFromMetadata !== undefined && referenceIdFromMetadata !== null && referenceIdFromMetadata !== \"\") {\n\t\t\t\t\t\t\t\twhere.push({ field: \"referenceId\", value: referenceIdFromMetadata });\n\t\t\t\t\t\t\t} else if (customerCode !== undefined && customerCode !== null && customerCode !== \"\") {\n\t\t\t\t\t\t\t\twhere.push({ field: \"paystackCustomerCode\", value: customerCode });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (planName !== undefined && planName !== null && planName !== \"\") {\n\t\t\t\t\t\t\t\twhere.push({ field: \"plan\", value: planName });\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (where.length > 0) {\n\t\t\t\t\t\t\t\tconst matches = await ctx.context.adapter.findMany<Subscription>({\n\t\t\t\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\t\t\t\twhere: where as { field: string; value: string | number | boolean | null }[],\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst subscription = (matches !== undefined && matches !== null) ? matches[0] : undefined;\n\t\t\t\t\t\t\t\tif (subscription !== undefined && subscription !== null) {\n\t\t\t\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\t\t\t\tpaystackSubscriptionCode: subscriptionCode,\n\t\t\t\t\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t\t\t\t\tperiodEnd: (data?.next_payment_date !== undefined && data?.next_payment_date !== null && data?.next_payment_date !== \"\") ? new Date(data.next_payment_date) : undefined,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: subscription.id }],\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\tconst plan = planFromCode ?? (planName !== undefined && planName !== null && planName !== \"\" ? await getPlanByName(options, planName) : undefined);\n\t\t\t\t\t\t\t\t\tif (plan !== undefined && plan !== null) {\n\t\t\t\t\t\t\t\t\t\tawait options.subscription.onSubscriptionComplete?.(\n\t\t\t\t\t\t\t\t\t\t\t{ event, subscription: { ...subscription, paystackSubscriptionCode: subscriptionCode, status: \"active\" }, plan },\n ctx as GenericEndpointContext,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t// Also call onSubscriptionCreated for subscriptions created outside of checkout\n\t\t\t\t\t\t\t\t\t\tawait options.subscription.onSubscriptionCreated?.(\n\t\t\t\t\t\t\t\t\t\t\t{ event, subscription: { ...subscription, paystackSubscriptionCode: subscriptionCode, status: \"active\" }, plan },\n ctx as GenericEndpointContext,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (eventName === \"subscription.disable\" || eventName === \"subscription.not_renew\") {\n\t\t\t\t\t\tconst subscriptionCode =\n data?.subscription_code ??\n data?.subscription?.subscription_code ??\n data?.code;\n\t\t\t\t\t\tif (subscriptionCode !== undefined && subscriptionCode !== null && subscriptionCode !== \"\") {\n\t\t\t\t\t\t\t// Find the subscription first to get full data for the hook\n\t\t\t\t\t\t\tconst existing = await ctx.context.adapter.findOne<Subscription>({\n\t\t\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\t\t\twhere: [{ field: \"paystackSubscriptionCode\", value: subscriptionCode }],\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tlet newStatus = \"canceled\";\n\t\t\t\t\t\t\tconst nextPaymentDate = (data as Record<string, unknown>)?.next_payment_date as string | undefined;\n\t\t\t\t\t\t\tconst periodEnd = nextPaymentDate ? new Date(nextPaymentDate) : (existing?.periodEnd ? new Date(existing.periodEnd) : undefined);\n\n\t\t\t\t\t\t\tif (periodEnd && periodEnd > new Date()) {\n\t\t\t\t\t\t\t\tnewStatus = \"active\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\t\tstatus: newStatus,\n\t\t\t\t\t\t\t\t\tcancelAtPeriodEnd: true,\n\t\t\t\t\t\t\t\t\t...(periodEnd ? { periodEnd } : {}),\n\t\t\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t\t\t{ field: \"paystackSubscriptionCode\", value: subscriptionCode },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t\tawait options.subscription.onSubscriptionCancel?.(\n\t\t\t\t\t\t\t\t\t{ event, subscription: { ...existing, status: \"canceled\" } },\n ctx as GenericEndpointContext,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (_e: unknown) {\n\t\t\t\t\tctx.context.logger.error(\"Failed to sync Paystack webhook event\", _e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait options.onEvent?.(event);\n\t\t\treturn ctx.json({ received: true });\n\t\t},\n\t);\n};\n\n\nconst initializeTransactionBodySchema = z.object({\n\tplan: z.string().optional(),\n\tproduct: z.string().optional(),\n\tamount: z.number().int().positive().optional(), // Amount in smallest currency unit (e.g., kobo)\n\tcurrency: z.string().optional(),\n\temail: z.string().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).optional(),\n\treferenceId: z.string().optional(),\n\tcallbackURL: z.string().optional(),\n\tquantity: z.number().int().positive().optional(),\n});\n\nexport const initializeTransaction = <P extends string = \"/paystack/initialize-transaction\">(options: AnyPaystackOptions, path: P = \"/paystack/initialize-transaction\" as P) => {\n\tconst subscriptionOptions = options.subscription;\n\t// However, for one-time payments, we might not strictly need subscription middleware\n\t// checking for existing subs, but let's keep it consistent for now.\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"initialize-transaction\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: initializeTransactionBodySchema,\n\t\t\tuse: useMiddlewares,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\tconst { plan: planName, product: productName, amount: bodyAmount, currency, email, metadata: extraMetadata, callbackURL, quantity } = ctx.body;\n\n\t\t\t// 1. Validate Callback URL validation (same as before)\n\t\t\tif (callbackURL !== undefined && callbackURL !== null && callbackURL !== \"\") {\n\t\t\t\tconst checkTrusted = () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!callbackURL) return false;\n\t\t\t\t\t\tif (callbackURL.startsWith(\"/\")) return true;\n\t\t\t\t\t\tconst baseUrl =\n ((ctx.context as Record<string, unknown>)?.baseURL as string | undefined) ??\n ((ctx.request as unknown as { url?: string })?.url) ??\n \"\";\n\t\t\t\t\t\tif (!baseUrl) return false;\n\t\t\t\t\t\tconst baseOrigin = new URL(baseUrl).origin;\n\t\t\t\t\t\treturn new URL(callbackURL).origin === baseOrigin;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (!checkTrusted()) {\n\t\t\t\t\tthrow new APIError(\"FORBIDDEN\", {\n\t\t\t\t\t\tmessage: \"callbackURL is not a trusted origin.\",\n\t\t\t\t\t\tstatus: 403,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 2. Get User & Session\n\t\t\tconst session = await getSessionFromCtx(ctx);\n\t\t\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\t\t\tconst user = session.user;\n \n\t\t\t// 3. Email Verification Check (only if subscription options enforce it)\n\t\t\tif (subscriptionOptions?.enabled === true && subscriptionOptions.requireEmailVerification === true && !user.emailVerified) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tcode: \"EMAIL_VERIFICATION_REQUIRED\",\n\t\t\t\t\tmessage: PAYSTACK_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 4. Determine Payment Mode: Subscription (Plan) vs Product vs One-Time (Amount)\n\t\t\tlet plan: PaystackPlan | null | undefined;\n\t\t\tlet product: PaystackProduct | InputPaystackProduct | undefined;\n \n\t\t\tif (planName !== undefined && planName !== null && planName !== \"\") {\n\t\t\t\tif (subscriptionOptions?.enabled !== true) {\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", { message: \"Subscriptions are not enabled.\" });\n\t\t\t\t}\n\t\t\t\tplan = await getPlanByName(options, planName) ?? undefined;\n\t\t\t\tif (!plan) {\n\t\t\t\t\t// Fallback: Check database for synced plans\n\t\t\t\t\tconst nativePlan = await ctx.context.adapter.findOne<PaystackPlan>({\n\t\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t\t\twhere: [{ field: \"name\", value: planName }],\n\t\t\t\t\t});\n\t\t\t\t\tif (nativePlan) {\n\t\t\t\t\t\tplan = nativePlan;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Try checking by planCode as well\n\t\t\t\t\t\tconst nativePlanByCode = await ctx.context.adapter.findOne<PaystackPlan>({\n\t\t\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t\t\t\twhere: [{ field: \"planCode\", value: planName }],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tplan = nativePlanByCode ?? undefined;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!plan) {\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\t\tcode: \"SUBSCRIPTION_PLAN_NOT_FOUND\",\n\t\t\t\t\t\tmessage: PAYSTACK_ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND,\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (productName !== undefined && productName !== null && productName !== \"\") {\n\t\t\t\tif (typeof productName === 'string') {\n\t\t\t\t\tconst fetchedProduct = await getProductByName(options, productName);\n\t\t\t\t\tif (fetchedProduct) {\n\t\t\t\t\t\tproduct ??= fetchedProduct;\n\t\t\t\t\t}\n\t\t\t\t\tif (!product) {\n\t\t\t\t\t\t// Fallback: Check database for synced products\n\t\t\t\t\t\tconst dbProduct = await ctx.context.adapter.findOne<PaystackProduct>({\n\t\t\t\t\t\t\tmodel: \"paystackProduct\",\n\t\t\t\t\t\t\twhere: [{ field: \"name\", value: productName }],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (dbProduct) {\n\t\t\t\t\t\t\tproduct ??= dbProduct;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!product) {\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: `Product '${productName}' not found.`,\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else if (bodyAmount === undefined || bodyAmount === null || bodyAmount === 0) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Either 'plan', 'product', or 'amount' is required to initialize a transaction.\",\n\t\t\t\t\tstatus: 400\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst amount = bodyAmount ?? product?.price;\n\t\t\tconst finalCurrency = currency ?? product?.currency ?? plan?.currency ?? \"NGN\";\n\n\t\t\tlet url: string | undefined;\n\t\t\tlet reference: string | undefined;\n\t\t\tlet accessCode: string | undefined;\n\n\t\t\t// 5. Prepare Payload\n\n\t\t\tconst referenceIdFromCtx = (ctx.context as Record<string, unknown>).referenceId as string | undefined;\n\t\t\tconst referenceId = (ctx.body.referenceId !== undefined && ctx.body.referenceId !== null && ctx.body.referenceId !== \"\")\n\t\t\t\t? ctx.body.referenceId \n\t\t\t\t: (referenceIdFromCtx !== undefined && referenceIdFromCtx !== null && referenceIdFromCtx !== \"\")\n\t\t\t\t\t? referenceIdFromCtx\n\t\t\t\t\t: (session.user as unknown as { id: string }).id;\n\n\t\t\t// Check trial eligibility - prevent trial abuse\n\t\t\tlet trialStart: Date | undefined;\n\t\t\tlet trialEnd: Date | undefined;\n\t\t\tif (plan?.freeTrial?.days !== undefined && plan.freeTrial.days !== null && plan.freeTrial.days > 0) {\n\t\t\t\t// Check if user/referenceId has ever had a trial\n\t\t\t\tconst previousTrials = await ctx.context.adapter.findMany<Subscription>({\n\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\twhere: [{ field: \"referenceId\", value: referenceId }],\n\t\t\t\t});\n\t\t\t\tconst hadTrial = previousTrials?.some(\n\t\t\t\t\t(sub) => (sub.trialStart !== undefined && sub.trialStart !== null) || (sub.trialEnd !== undefined && sub.trialEnd !== null) || sub.status === \"trialing\"\n\t\t\t\t);\n \n\t\t\t\tif (!hadTrial) {\n\t\t\t\t\ttrialStart = new Date();\n\t\t\t\t\ttrialEnd = new Date();\n\t\t\t\t\ttrialEnd.setDate(trialEnd.getDate() + plan.freeTrial.days);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Determine Customer Email & Code (Organization support)\n\t\t\t\tlet targetEmail = (email !== undefined && email !== null && email !== \"\") ? email : user.email;\n\t\t\t\tlet paystackCustomerCode = (user as unknown as { paystackCustomerCode?: string }).paystackCustomerCode;\n\n\t\t\t\tif (options.organization?.enabled === true && referenceId !== undefined && referenceId !== null && referenceId !== \"\" && referenceId !== user.id) {\n\t\t\t\t\tconst org = await ctx.context.adapter.findOne<Organization>({\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\twhere: [{ field: \"id\", value: referenceId }],\n\t\t\t\t\t});\n\t\t\t\t\tif (org !== undefined && org !== null) {\n\t\t\t\t\t\t// Prefer organization's existing Paystack customer code\n\t\t\t\t\t\tif (org.paystackCustomerCode !== undefined && org.paystackCustomerCode !== null && org.paystackCustomerCode !== \"\") {\n\t\t\t\t\t\t\tpaystackCustomerCode = org.paystackCustomerCode;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (org.email !== undefined && org.email !== null && org.email !== \"\") {\n\t\t\t\t\t\t\ttargetEmail = org.email;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Fallback: Use Organization Owner Email\n\t\t\t\t\t\t\tconst ownerMember = await ctx.context.adapter.findOne<Member>({\n\t\t\t\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t\t\t{ field: \"organizationId\", value: referenceId },\n\t\t\t\t\t\t\t\t\t{ field: \"role\", value: \"owner\" }\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tif (ownerMember) {\n\t\t\t\t\t\t\t\tconst ownerUser = await ctx.context.adapter.findOne<User>({\n\t\t\t\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: ownerMember.userId }]\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (ownerUser?.email !== undefined && ownerUser?.email !== null && ownerUser?.email !== \"\") {\n\t\t\t\t\t\t\t\t\ttargetEmail = ownerUser.email;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Construct Metadata\n\t\t\t\tconst metadata = JSON.stringify({\n\t\t\t\t\treferenceId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\tplan: plan?.name.toLowerCase(), // Undefined for one-time\n\t\t\t\t\tproduct: product?.name.toLowerCase(),\n\t\t\t\t\tisTrial: !!trialStart,\n\t\t\t\t\ttrialEnd: trialEnd?.toISOString(),\n\t\t\t\t\t...extraMetadata,\n\t\t\t\t});\n\n\t\t\t\tconst initBody: Record<string, unknown> & { email?: string; amount?: number; plan?: string; invoice_limit?: number } = {\n\t\t\t\t\temail: targetEmail,\n\t\t\t\t\tcallback_url: callbackURL,\n\t\t\t\t\tmetadata,\n\t\t\t\t\t// If plan/product exists, use its currency; otherwise fallback to provided or default\n\t\t\t\t\tcurrency: finalCurrency,\n\t\t\t\t\tquantity,\n\t\t\t\t};\n\n\t\t\t\t// Sync/Update Customer: ensure email matches if code exists\n\t\t\t\tif (paystackCustomerCode !== undefined && paystackCustomerCode !== null && paystackCustomerCode !== \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst ops = getPaystackOps(options.paystackClient);\n\t\t\t\t\t\t// Only update if email is present\n\t\t\t\t\t\tif (initBody.email !== undefined && initBody.email !== null && initBody.email !== \"\") {\n\t\t\t\t\t\t\tawait ops.customerUpdate(paystackCustomerCode, { email: initBody.email });\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (_e: unknown) {\n\t\t\t\t\t\t// Ignore sync errors\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif (plan) {\n\t\t\t\t\t// Subscription Flow\n\t\t\t\t\tif (trialStart) {\n\t\t\t\t\t\t// Trial Flow: Authorize card with minimum amount, don't start sub yet\n\t\t\t\t\t\tinitBody.amount = 5000; // 50 NGN (minimum allowed)\n\t\t\t\t\t\t// Do NOT set initBody.plan\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Standard Flow\n\t\t\t\t\t\tinitBody.plan = plan.planCode;\n\t\t\t\t\t\tinitBody.invoice_limit = plan.invoiceLimit;\n\t\t\t\t\t\t// Paystack requires amount even with planCode (it uses plan's stored amount)\n\t\t\t\t\t\t// For local plans without planCode, use finalAmount; for planCode plans, use plan.amount or minimum\n\t\t\t\t\t\tconst planAmount = amount ?? plan.amount ?? 50000; // 500 NGN minimum fallback\n\t\t\t\t\t\tinitBody.amount = Math.max(Math.round(planAmount), 50000);\n\t\t\t\t\t\tif (quantity !== undefined && quantity !== null && quantity > 0) {\n\t\t\t\t\t\t\tinitBody.amount = initBody.amount * quantity;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// One-Time Payment Flow\n\t\t\t\t\tif (amount === undefined || amount === null || amount === 0) throw new APIError(\"BAD_REQUEST\", { message: \"Amount is required for one-time payments\" });\n\t\t\t\t\tinitBody.amount = Math.round(amount);\n\t\t\t\t}\n\n\t\t\t\tconst initRaw = await paystack.transactionInitialize(initBody as unknown as Parameters<typeof paystack.transactionInitialize>[0]);\n\t\t\t\tconst initRes = unwrapSdkResult<PaystackTransactionResponse>(initRaw);\n\t\t\t\tlet data =\n (initRes !== undefined && initRes !== null && typeof initRes === \"object\" && \"status\" in initRes && \"data\" in initRes)\n \t? (initRes).data\n \t: (initRes as PaystackTransactionResponse | undefined)?.data ?? initRes;\n \n\t\t\t\tif (data !== undefined && data !== null && typeof data === \"object\" && \"status\" in data && \"data\" in data) {\n\t\t\t\t\tdata = (data as Record<string, unknown>).data;\n\t\t\t\t}\n\t\t\t\turl = (data as PaystackTransactionResponse)?.authorization_url;\n\t\t\t\treference = (data as PaystackTransactionResponse)?.reference as string | undefined;\n\t\t\t\taccessCode = (data as PaystackTransactionResponse)?.access_code;\n\t\t\t} catch (error: unknown) {\n\t\t\t\t(ctx as unknown as { context: { logger: { error: (msg: string, err: unknown) => void } } }).context.logger.error(\"Failed to initialize Paystack transaction\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tcode: \"FAILED_TO_INITIALIZE_TRANSACTION\",\n\t\t\t\t\tmessage: (error as Error)?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 6. Record Transaction & Subscription\n\t\t\tawait ctx.context.adapter.create<InputPaystackTransaction, PaystackTransaction>({\n\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\tdata: {\n\t\t\t\t\treference: reference!,\n\t\t\t\t\treferenceId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\tamount: amount ?? 0,\n\t\t\t\t\tcurrency: plan?.currency ?? currency ?? \"NGN\",\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tplan: plan?.name.toLowerCase(),\n\t\t\t\t\tproduct: product?.name.toLowerCase(),\n\t\t\t\t\tmetadata: (extraMetadata !== undefined && extraMetadata !== null) ? JSON.stringify(extraMetadata) : undefined,\n\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (plan !== undefined && plan !== null) {\n\t\t\t\t// Re-fetch customer code if it wasn't available before (though we didn't force-create it here)\n\t\t\t\t// For now, use what we have (user's or org's)\n\t\t\t\tlet storedCustomerCode = (user as unknown as { paystackCustomerCode?: string }).paystackCustomerCode;\n\t\t\t\tif (options.organization?.enabled === true && referenceId !== user.id) {\n\t\t\t\t\tconst org = await ctx.context.adapter.findOne<Organization>({\n\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\twhere: [{ field: \"id\", value: referenceId }],\n\t\t\t\t\t});\n\t\t\t\t\tif (org?.paystackCustomerCode !== undefined && org?.paystackCustomerCode !== null && org.paystackCustomerCode !== \"\") {\n\t\t\t\t\t\tstoredCustomerCode = org.paystackCustomerCode;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newSubscription = await ctx.context.adapter.create<InputSubscription, Subscription>({\n\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tplan: plan.name.toLowerCase(),\n\t\t\t\t\t\treferenceId,\n\t\t\t\t\t\tpaystackCustomerCode: storedCustomerCode,\n\t\t\t\t\t\tpaystackTransactionReference: reference,\n\t\t\t\t\t\tstatus: (trialStart !== undefined && trialStart !== null) ? \"trialing\" : \"incomplete\",\n\t\t\t\t\t\tseats: quantity,\n\t\t\t\t\t\ttrialStart,\n\t\t\t\t\t\ttrialEnd,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Call trial start hook if trial was granted\n\t\t\t\tif ((trialStart !== undefined && trialStart !== null) && newSubscription !== null && plan.freeTrial?.onTrialStart !== undefined && plan.freeTrial?.onTrialStart !== null) {\n\t\t\t\t\tawait plan.freeTrial.onTrialStart(newSubscription);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ctx.json({\n\t\t\t\turl,\n\t\t\t\treference,\n\t\t\t\taccessCode,\n\t\t\t\tredirect: true,\n\t\t\t});\n\t\t},\n\t);\n};\n\n// Aliases for Client DX Parity\nexport const createSubscription = (options: AnyPaystackOptions) =>\n\tinitializeTransaction(options, \"/paystack/create-subscription\");\nexport const upgradeSubscription = (options: AnyPaystackOptions) =>\n\tinitializeTransaction(options, \"/paystack/upgrade-subscription\");\nexport const restoreSubscription = (options: AnyPaystackOptions) => {\n\t// Alias for enable\n\treturn enablePaystackSubscription(options, \"/paystack/restore-subscription\");\n};\nexport const cancelSubscription = (options: AnyPaystackOptions) => {\n\t// Alias for disable\n\treturn disablePaystackSubscription(options, \"/paystack/cancel-subscription\");\n};\n\n\nexport const verifyTransaction = <P extends string = \"/paystack/verify-transaction\">(options: AnyPaystackOptions, path: P = \"/paystack/verify-transaction\" as P) => {\n\tconst verifyBodySchema = z.object({\n\t\treference: z.string(),\n\t});\n\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"verify-transaction\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: verifyBodySchema,\n\t\t\tuse: useMiddlewares,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\tlet verifyRes: PaystackTransactionResponse | undefined;\n\t\t\ttry {\n\t\t\t\tconst verifyRaw = await paystack.transactionVerify(ctx.body.reference);\n\t\t\t\tverifyRes = unwrapSdkResult<PaystackTransactionResponse>(verifyRaw);\n\t\t\t} catch (error: unknown) {\n\t\t\t\tctx.context.logger.error(\"Failed to verify Paystack transaction\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tcode: \"FAILED_TO_VERIFY_TRANSACTION\",\n\t\t\t\t\tmessage:\n (error as Error)?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_VERIFY_TRANSACTION,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst data = verifyRes;\n\t\t\tconst status = (data)?.status as string | undefined;\n\t\t\tconst reference = ((data)?.reference as string | undefined) ?? ctx.body.reference;\n\t\t\tconst paystackId = (data)?.id !== undefined && (data)?.id !== null ? String((data as { id: string | number }).id) : undefined;\n\t\t\tconst authorizationCode = ((data)?.authorization as Record<string, unknown>)?.authorization_code as string | undefined;\n\n\t\t\tif (status === \"success\") {\n\t\t\t\tconst session = await getSessionFromCtx(ctx);\n\n\t\t\t\t// Get the local transaction record to know the intended referenceId (Org or User)\n\t\t\t\tconst txRecord = await ctx.context.adapter.findOne<Record<string, unknown> & { referenceId?: string }>({\n\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t});\n\n\t\t\t\t// Trust the referenceId from the record, fallback to session user if missing\n\t\t\t\tconst referenceId = txRecord?.referenceId ?? (session?.user as unknown as { id: string })?.id;\n\n\t\t\t\t// Authorization check: ensure the current user has access to this referenceId\n\t\t\t\tif (session !== null && session !== undefined && referenceId !== session.user.id) {\n\t\t\t\t\tconst authRef = (subscriptionOptions as unknown as { authorizeReference: (data: unknown, ctx: unknown) => Promise<boolean> })?.authorizeReference;\n\t\t\t\t\tlet authorized = false;\n\t\t\t\t\tif (authRef !== undefined && authRef !== null) {\n\t\t\t\t\t\tauthorized = await authRef({\n\t\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\treferenceId,\n\t\t\t\t\t\t\taction: \"verify-transaction\"\n\t\t\t\t\t\t}, ctx);\n\t\t\t\t\t} else if (options.organization?.enabled === true) {\n\t\t\t\t\t\tconst member = await ctx.context.adapter.findOne({\n\t\t\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t\t{ field: \"userId\", value: session.user.id },\n\t\t\t\t\t\t\t\t{ field: \"organizationId\", value: referenceId }\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (member !== null && member !== undefined) authorized = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!authorized) {\n\t\t\t\t\t\tthrow new APIError(\"UNAUTHORIZED\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttry {\n\n\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\t\t\tpaystackId,\n\t\t\t\t\t\t\t// Update with actual amount/currency from Paystack (for planCode subscriptions)\n\t\t\t\t\t\t\t...((data)?.amount !== undefined && (data)?.amount !== null ? { amount: (data).amount } : {}),\n\t\t\t\t\t\t\t...((data)?.currency !== undefined && (data)?.currency !== null ? { currency: (data).currency } : {}),\n\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t});\n\n\t\t\t\t\tconst customer = (data)?.customer;\n\t\t\t\t\tconst paystackCustomerCodeFromPaystack = (customer !== undefined && customer !== null && typeof customer === \"object\")\n\t\t\t\t\t\t? (customer as Record<string, unknown>).customer_code as string | undefined\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tif (paystackCustomerCodeFromPaystack !== undefined && paystackCustomerCodeFromPaystack !== null && paystackCustomerCodeFromPaystack !== \"\" && referenceId !== undefined && referenceId !== null && referenceId !== \"\") {\n\t\t\t\t\t\tconst isOrg = options.organization?.enabled === true && ((referenceId.startsWith(\"org_\")) || (await ctx.context.adapter.findOne({ model: \"organization\", where: [{ field: \"id\", value: referenceId }] }) !== null));\n\n\t\t\t\t\t\tif (isOrg === true) {\n\t\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\t\tmodel: \"organization\",\n\t\t\t\t\t\t\t\tupdate: { paystackCustomerCode: paystackCustomerCodeFromPaystack },\n\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: referenceId }],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\t\t\tupdate: { paystackCustomerCode: paystackCustomerCodeFromPaystack },\n\t\t\t\t\t\t\t\twhere: [{ field: \"id\", value: referenceId }],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Decrement product quantity if applicable\n\t\t\t\t\tconst transaction = await ctx.context.adapter.findOne<PaystackTransaction>({\n\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t});\n\t\t\t\t\tif (transaction?.product) {\n\t\t\t\t\t\tawait syncProductQuantityFromPaystack(ctx as GenericEndpointContext, transaction.product, options.paystackClient);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Check for trial activation\n\t\t\t\t\tlet isTrial = false;\n\t\t\t\t\tlet trialEnd: string | undefined;\n\t\t\t\t\tlet targetPlan: string | undefined;\n\n\t\t\t\t\tif ((data)?.metadata !== undefined && (data)?.metadata !== null) {\n\t\t\t\t\t\tconst metaRaw = (data).metadata;\n\t\t\t\t\t\tconst meta = typeof metaRaw === \"string\" ? JSON.parse(metaRaw) : metaRaw as Record<string, unknown>;\n\t\t\t\t\t\tisTrial = meta.isTrial === true || meta.isTrial === \"true\";\n\t\t\t\t\t\t \n\t\t\t\t\t\ttrialEnd = meta.trialEnd as string | undefined;\n\t\t\t\t\t\t \n\t\t\t\t\t\ttargetPlan = meta.plan as string | undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet paystackSubscriptionCode: string | undefined;\n\n\t\t\t\t\tif (isTrial === true && (targetPlan !== undefined && targetPlan !== null && targetPlan !== \"\") && (trialEnd !== undefined && trialEnd !== null && trialEnd !== \"\")) {\n\t\t\t\t\t\t// Trial Flow: Create subscription with future start date using auth code\n\t\t\t\t\t\tconst email = ((data)?.customer as Record<string, unknown>)?.email as string | undefined;\n \n\t\t\t\t\t\t// We need the planCode. We have the plan NAME in metadata (lowercased).\n\t\t\t\t\t\tconst plans = await getPlans(subscriptionOptions);\n\t\t\t\t\t\tconst planConfig = plans.find(p => p.name.toLowerCase() === targetPlan?.toLowerCase());\n\n\t\t\t\t\t\t// For local plans (no planCode), generate a local subscription code\n\t\t\t\t\t\tif (planConfig !== undefined && (planConfig.planCode === undefined || planConfig.planCode === null || planConfig.planCode === \"\")) {\n\t\t\t\t\t\t\tpaystackSubscriptionCode = `LOC_${reference}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ((authorizationCode !== undefined && authorizationCode !== null && authorizationCode !== \"\") && (email !== undefined && email !== null && email !== \"\") && (planConfig?.planCode !== undefined && planConfig?.planCode !== null && planConfig?.planCode !== \"\")) {\n\t\t\t\t\t\t\tconst subRes = await paystack.subscriptionCreate({\n\t\t\t\t\t\t\t\tcustomer: email,\n\t\t\t\t\t\t\t\tplan: planConfig.planCode,\n\t\t\t\t\t\t\t\tauthorization: authorizationCode,\n\t\t\t\t\t\t\t\tstart_date: trialEnd\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst subData = unwrapSdkResult<PaystackSubscriptionResponse>(subRes);\n\t\t\t\t\t\t\tconst cleanSubData = (subData as { data?: PaystackSubscriptionResponse })?.data ?? subData;\n\n\t\t\t\t\t\t\tpaystackSubscriptionCode = (cleanSubData)?.subscription_code as string | undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isTrial !== true) {\n\t\t\t\t\t\tconst planFromPaystack = (data)?.plan as Record<string, unknown> | undefined;\n\t\t\t\t\t\tconst planCodeFromPaystack = planFromPaystack?.plan_code as string | undefined;\n\n\t\t\t\t\t\tif (planCodeFromPaystack === undefined || planCodeFromPaystack === null || planCodeFromPaystack === \"\") {\n\t\t\t\t\t\t\t// Local Plan\n\t\t\t\t\t\t\tpaystackSubscriptionCode = `LOC_${reference}`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Native Paystack subscription (if created during charge)\n\t\t\t\t\t\t\tpaystackSubscriptionCode = ((data)?.subscription as Record<string, unknown> | undefined)?.subscription_code as string | undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\tconst updatedSubscription = await ctx.context.adapter.update<Subscription>({\n\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\tstatus: isTrial === true ? \"trialing\" : \"active\",\n\t\t\t\t\t\t\tperiodStart: new Date(),\n\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t...(isTrial === true && (trialEnd !== undefined && trialEnd !== null && trialEnd !== \"\") ? {\n\t\t\t\t\t\t\t\ttrialStart: new Date(),\n\t\t\t\t\t\t\t\ttrialEnd: new Date(trialEnd),\n\t\t\t\t\t\t\t\tperiodEnd: new Date(trialEnd),\n\t\t\t\t\t\t\t} : {}),\n\t\t\t\t\t\t\t...(paystackSubscriptionCode !== undefined && paystackSubscriptionCode !== null && paystackSubscriptionCode !== \"\" ? { paystackSubscriptionCode } : {}),\n\t\t\t\t\t\t\t...(authorizationCode !== undefined && authorizationCode !== null && authorizationCode !== \"\" ? { paystackAuthorizationCode: authorizationCode } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t{ field: \"paystackTransactionReference\", value: reference },\n\t\t\t\t\t\t\t...(referenceId !== undefined && referenceId !== null && referenceId !== \"\" ? [{ field: \"referenceId\", value: referenceId }] : []),\n\t\t\t\t\t\t],\n\t\t\t\t\t});\n\n\t\t\t\t\tif (updatedSubscription && subscriptionOptions?.enabled === true && \"onSubscriptionComplete\" in subscriptionOptions && typeof (subscriptionOptions as unknown as Record<string, unknown>).onSubscriptionComplete === \"function\") {\n\t\t\t\t\t\tconst subOpts = subscriptionOptions;\n\t\t\t\t\t\tconst plans = await getPlans(subOpts);\n\t\t\t\t\t\tconst plan = plans.find(p => p.name.toLowerCase() === updatedSubscription.plan.toLowerCase());\n\t\t\t\t\t\tif (plan) {\n\t\t\t\t\t\t\tawait (subscriptionOptions as unknown as { onSubscriptionComplete: (data: unknown, ctx: unknown) => Promise<void> }).onSubscriptionComplete({\n\t\t\t\t\t\t\t\tevent: data,\n\t\t\t\t\t\t\t\tsubscription: updatedSubscription,\n\t\t\t\t\t\t\t\tplan\n\t\t\t\t\t\t\t}, ctx);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tctx.context.logger.error(\n\t\t\t\t\t\t\"Failed to update transaction/subscription after verification\",\n\t\t\t\t\t\te,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (status === \"failed\" || status === \"abandoned\") {\n\t\t\t\ttry {\n\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\twhere: [{ field: \"reference\", value: reference }],\n\t\t\t\t\t});\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tctx.context.logger.error(\"Failed to update transaction status\", e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ctx.json({\n\t\t\t\tstatus,\n\t\t\t\treference,\n\t\t\t\tdata,\n\t\t\t});\n\t\t},\n\t);\n};\n\nexport const listSubscriptions = (options: AnyPaystackOptions) => {\n\tconst listQuerySchema = z.object({\n\t\treferenceId: z.string().optional(),\n\t});\n\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"list-subscriptions\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\t\"/paystack/list-subscriptions\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tquery: listQuerySchema,\n\t\t\tuse: useMiddlewares,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tif (subscriptionOptions?.enabled !== true) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Subscriptions are not enabled in the Paystack options.\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst session = await getSessionFromCtx(ctx);\n\t\t\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\t\t\tconst referenceIdPart = (ctx.context as Record<string, unknown>).referenceId as string | undefined;\n\t\t\tconst queryRefId = ctx.query?.referenceId;\n\t\t\tconst referenceId = (referenceIdPart !== undefined && referenceIdPart !== null && referenceIdPart !== \"\")\n\t\t\t\t? referenceIdPart\n\t\t\t\t: (queryRefId !== undefined && queryRefId !== null && queryRefId !== \"\")\n\t\t\t\t\t? queryRefId\n\t\t\t\t\t: (session.user as unknown as { id: string }).id;\n\t\t\tconst res = await ctx.context.adapter.findMany<Subscription>({\n\t\t\t\tmodel: \"subscription\",\n\t\t\t\twhere: [{ field: \"referenceId\", value: referenceId }],\n\t\t\t});\n\t\t\treturn ctx.json({ subscriptions: res });\n\t\t},\n\t);\n};\n\nexport const listTransactions = <P extends string = \"/paystack/list-transactions\">(options: AnyPaystackOptions, path: P = \"/paystack/list-transactions\" as P) => {\n\tconst listQuerySchema = z.object({\n\t\treferenceId: z.string().optional(),\n\t});\n\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"list-transactions\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tquery: listQuerySchema,\n\t\t\tuse: useMiddlewares,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst session = await getSessionFromCtx(ctx);\n\t\t\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\t\t\tconst referenceId =\n ((ctx.context as Record<string, unknown>).referenceId as string | undefined) ??\n (ctx.query?.referenceId) ??\n ((session.user as unknown as { id: string }).id);\n\t\t\tconst res = await ctx.context.adapter.findMany<PaystackTransaction>({\n\t\t\t\tmodel: \"paystackTransaction\",\n\t\t\t\twhere: [{ field: \"referenceId\", value: referenceId }],\n\t\t\t});\n\t\t\t// Sort by createdAt desc locally if adapter doesn't support it well, \n\t\t\t// but Better Auth adapters usually return in insertion order.\n\t\t\t// Let's sort to be sure.\n\t\t\tconst sorted = res.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\t\t\treturn ctx.json({ transactions: sorted });\n\t\t},\n\t);\n};\n\nconst enableDisableBodySchema = z.object({\n\treferenceId: z.string().optional(),\n\tsubscriptionCode: z.string(),\n\temailToken: z.string().optional(),\n});\n\nfunction decodeBase64UrlToString(value: string): string {\n\tconst normalized = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padded = normalized + \"===\".slice((normalized.length + 3) % 4);\n\tif (typeof (globalThis as unknown as { atob: unknown }).atob === \"function\") {\n\t\treturn ((globalThis as unknown as { atob: (v: string) => string }).atob)(padded);\n\t}\n\t// eslint-disable-next-line no-restricted-globals\n\treturn Buffer.from(padded, \"base64\").toString(\"utf8\");\n}\n\nfunction tryGetEmailTokenFromSubscriptionManageLink(link: string): string | undefined {\n\ttry {\n\t\tconst url = new URL(link);\n\t\tconst subscriptionToken = url.searchParams.get(\"subscription_token\");\n\t\tif (subscriptionToken === undefined || subscriptionToken === null || subscriptionToken === \"\") return undefined;\n\t\tconst parts = subscriptionToken.split(\".\");\n\t\tif (parts.length < 2) return undefined;\n\t\tconst payloadJson = decodeBase64UrlToString(parts[1]);\n\t\tconst payload = JSON.parse(payloadJson);\n\t\treturn typeof payload?.email_token === \"string\" ? payload.email_token : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport const disablePaystackSubscription = <P extends string = \"/paystack/disable-subscription\">(options: AnyPaystackOptions, path: P = \"/paystack/disable-subscription\" as P) => {\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"disable-subscription\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{ method: \"POST\", body: enableDisableBodySchema, use: useMiddlewares },\n\t\tasync (ctx) => {\n\t\t\tconst { subscriptionCode } = ctx.body;\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\ttry {\n\t\t\t\tif (subscriptionCode.startsWith(\"LOC_\")) {\n\t\t\t\t\tconst sub = await ctx.context.adapter.findOne<Subscription>({\n\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\twhere: [{ field: \"paystackSubscriptionCode\", value: subscriptionCode }],\n\t\t\t\t\t});\n\n\t\t\t\t\tif (sub) {\n\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\t\t\tcancelAtPeriodEnd: true,\n\t\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\twhere: [{ field: \"id\", value: sub.id }],\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn ctx.json({ status: \"success\" });\n\t\t\t\t\t}\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", { message: \"Subscription not found\" });\n\t\t\t\t}\n\n\t\t\t\tlet emailToken = ctx.body.emailToken;\n\t\t\t\tlet nextPaymentDate: string | undefined;\n\n\t\t\t\t// Always fetch subscription to get next_payment_date even if we have emailToken (unless passed? no, next_payment_date comes from paystack)\n\t\t\t\t// We need next_payment_date for cancelAtPeriodEnd logic\n\t\t\t\ttry {\n\t\t\t\t\tconst raw = await paystack.subscriptionFetch(subscriptionCode);\n\t\t\t\t\tconst fetchRes = unwrapSdkResult<PaystackSubscriptionResponse>(raw);\n\t\t\t\t\tconst data = fetchRes;\n\t\t\t\t\t\n\t\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\t\temailToken = (data)?.email_token as string | undefined;\n\t\t\t\t\t}\n\t\t\t\t\tnextPaymentDate = (data)?.next_payment_date as string | undefined;\n\t\t\t\t} catch {\n\t\t\t\t\t// ignore fetch failure? If we can't fetch, we might miss next_payment_date.\n\t\t\t\t}\n\n\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst raw = await paystack.subscriptionManageLink(subscriptionCode);\n\t\t\t\t\t\tconst linkRes = unwrapSdkResult<Record<string, unknown>>(raw);\n\t\t\t\t\t\tconst data =\n linkRes !== null && linkRes !== undefined && typeof linkRes === \"object\" && \"status\" in linkRes && \"data\" in linkRes\n \t? (linkRes).data\n \t: linkRes?.data !== undefined ? linkRes.data : linkRes;\n\t\t\t\t\t\tconst link = typeof data === \"string\" ? data : (data as Record<string, unknown>)?.link as string | undefined;\n \n\t\t\t\t\t\tif (link !== undefined && link !== null && link !== \"\") {\n\t\t\t\t\t\t\temailToken = tryGetEmailTokenFromSubscriptionManageLink(link);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// ignore\n\t\t\t\t\t}\n\t\t\t\t}\n \n\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\tthrow new Error(\"Could not retrieve email_token for subscription disable.\");\n\t\t\t\t}\n\n\t\t\t\tawait paystack.subscriptionDisable({ code: subscriptionCode, token: emailToken });\n \n\t\t\t\t// Implement Cancel at Period End logic\n\t\t\t\t// Paystack \"disable\" stops future charges.\n\t\t\t\t// We keep status as \"active\" but set cancelAtPeriodEnd = true\n\t\t\t\t\n\t\t\t\t// Duplicate removed\n\n\t\t\t\tconst periodEnd = (nextPaymentDate !== undefined && nextPaymentDate !== null && nextPaymentDate !== \"\") ? new Date(nextPaymentDate) : undefined;\n\t\t\t\t\n\t\t\t\tconst sub = await ctx.context.adapter.findOne<Subscription>({\n\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\twhere: [{ field: \"paystackSubscriptionCode\", value: subscriptionCode }],\n\t\t\t\t});\n\n\t\t\t\tif (sub) {\n\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\t\tupdate: {\n\t\t\t\t\t\t\tstatus: \"active\", // Keep active until period end\n\t\t\t\t\t\t\tcancelAtPeriodEnd: true,\n\t\t\t\t\t\t\tperiodEnd,\n\t\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\twhere: [{ field: \"id\", value: sub.id }],\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// This is unexpected if we are disabling a subscription that should exist\n\t\t\t\t\tctx.context.logger.warn(`Could not find subscription with code ${subscriptionCode} to disable`);\n\t\t\t\t}\n\n\t\t\t\treturn ctx.json({ status: \"success\" });\n\t\t\t} catch (error: unknown) {\n\t\t\t\t(ctx as unknown as { context: { logger: { error: (msg: string, err: unknown) => void } } }).context.logger.error(\"Failed to disable subscription\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tcode: \"FAILED_TO_DISABLE_SUBSCRIPTION\",\n\t\t\t\t\tmessage:\n (error as Error)?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t);\n};\n\nexport const enablePaystackSubscription = <P extends string = \"/paystack/enable-subscription\">(options: AnyPaystackOptions, path: P = \"/paystack/enable-subscription\" as P) => {\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"enable-subscription\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{ method: \"POST\", body: enableDisableBodySchema, use: useMiddlewares },\n\t\tasync (ctx) => {\n\t\t\tconst { subscriptionCode } = ctx.body;\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\ttry {\n\t\t\t\tlet emailToken = ctx.body.emailToken;\n\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst raw = await paystack.subscriptionFetch(subscriptionCode);\n\t\t\t\t\t\tconst fetchRes = unwrapSdkResult<PaystackSubscriptionResponse>(raw);\n\t\t\t\t\t\tconst data = fetchRes;\n\t\t\t\t\t\temailToken = (data)?.email_token as string | undefined;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// ignore; try manage-link fallback below\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst raw = await paystack.subscriptionManageLink(subscriptionCode);\n\t\t\t\t\t\tconst linkRes = unwrapSdkResult<Record<string, unknown>>(raw);\n\t\t\t\t\t\tconst data =\n linkRes !== null && linkRes !== undefined && \"status\" in linkRes && \"data\" in linkRes\n \t? (linkRes).data\n \t: linkRes?.data !== undefined ? linkRes.data : linkRes;\n\t\t\t\t\t\tconst link = typeof data === \"string\" ? data : (data as Record<string, unknown>)?.link as string | undefined;\n \n\t\t\t\t\t\tif (link !== undefined && link !== null && link !== \"\") {\n\t\t\t\t\t\t\temailToken = tryGetEmailTokenFromSubscriptionManageLink(link);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// ignore\n\t\t\t\t\t}\n\t\t\t\t}\n \n\t\t\t\tif (emailToken === undefined || emailToken === null || emailToken === \"\") {\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", { message: \"Could not retrieve email_token for subscription enable.\" });\n\t\t\t\t}\n\n\t\t\t\tawait paystack.subscriptionEnable({ code: subscriptionCode, token: emailToken });\n\n\t\t\t\t// Update local status immediately\n\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\tupdate: {\n\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\twhere: [{ field: \"paystackSubscriptionCode\", value: subscriptionCode }],\n\t\t\t\t});\n\n\t\t\t\treturn ctx.json({ status: \"success\" });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tctx.context.logger.error(\"Failed to enable subscription\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tcode: \"FAILED_TO_ENABLE_SUBSCRIPTION\",\n\t\t\t\t\tmessage:\n (error as Error)?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t);\n};\n\nexport const getSubscriptionManageLink = <P extends string = \"/paystack/get-subscription-manage-link\">(options: AnyPaystackOptions, path: P = \"/paystack/get-subscription-manage-link\" as P) => {\n\tconst manageLinkQuerySchema = z.object({\n\t\tsubscriptionCode: z.string(),\n\t});\n\tconst subscriptionOptions = options.subscription;\n\tconst useMiddlewares = subscriptionOptions?.enabled === true\n\t\t? [sessionMiddleware, originCheck, referenceMiddleware(options, \"get-subscription-manage-link\")]\n\t\t: [sessionMiddleware, originCheck];\n\n\tconst handler = async (ctx: GenericEndpointContext) => {\n\t\tconst { subscriptionCode } = ctx.query;\n\t\t\n\t\t// If it's a local mock subscription, return null link instead of error\n\t\tif (subscriptionCode.startsWith(\"LOC_\") || subscriptionCode.startsWith(\"sub_local_\")) {\n\t\t\treturn ctx.json({ link: null, message: \"Local subscriptions cannot be managed on Paystack\" });\n\t\t}\n\n\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\ttry {\n\t\t\tconst raw = await paystack.subscriptionManageLink(subscriptionCode);\n\t\t\tconst res = unwrapSdkResult<Record<string, unknown>>(raw);\n\t\t\tconst data =\n (res !== null && res !== undefined && typeof res === \"object\" && \"status\" in res && \"data\" in res)\n \t? (res).data\n \t: res?.data !== undefined ? res.data : res;\n\t\t\t\n\t\t\tconst link = typeof data === \"string\" ? data : (data as Record<string, unknown>)?.link as string | undefined;\n \n\t\t\treturn ctx.json({ link });\n\t\t} catch (error: unknown) {\n\t\t\tctx.context.logger.error(\"Failed to get subscription manage link\", error);\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: (error as Error)?.message ?? \"Failed to get subscription manage link\",\n\t\t\t});\n\t\t}\n\t};\n\n\treturn createAuthEndpoint(\n\t\tpath,\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tquery: manageLinkQuerySchema,\n\t\t\tuse: useMiddlewares,\n\t\t},\n\t\thandler,\n\t);\n};\n\nexport const syncProducts = (options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/sync-products\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tmetadata: {\n\t\t\t\t...HIDE_METADATA,\n\t\t\t},\n\t\t\tdisableBody: true,\n\t\t\tuse: [sessionMiddleware],\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconsole.error(\"DEBUG: syncProducts endpoint hit!\");\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\ttry {\n\t\t\t\tconst raw = await paystack.productList();\n\t\t\t\tconst res = unwrapSdkResult<Record<string, unknown>>(raw);\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\tconst productsData = (res !== null && typeof res === \"object\" && \"status\" in res && \"data\" in res) ? (res as Record<string, any>).data : (res as Record<string, any>)?.data ?? res;\n\n\t\t\t\tif (!Array.isArray(productsData)) {\n\t\t\t\t\treturn ctx.json({ status: \"success\", count: 0 });\n\t\t\t\t}\n\n\t\t\t\tfor (const product of productsData) {\n\t\t\t\t\tconst paystackId = String(product.id);\n\t\t\t\t\tconst existing = await ctx.context.adapter.findOne<PaystackProduct>({\n\t\t\t\t\t\tmodel: \"paystackProduct\",\n\t\t\t\t\t\twhere: [{ field: \"paystackId\", value: paystackId }],\n\t\t\t\t\t});\n\n\t\t\t\t\tconst productData = {\n\t\t\t\t\t\tname: product.name,\n\t\t\t\t\t\tdescription: product.description,\n\t\t\t\t\t\tprice: product.price,\n\t\t\t\t\t\tcurrency: product.currency,\n\t\t\t\t\t\tquantity: product.quantity,\n\t\t\t\t\t\tunlimited: product.unlimited,\n\t\t\t\t\t\tpaystackId,\n\t\t\t\t\t\tslug: product.slug ?? product.name.toLowerCase().replace(/\\s+/g, \"-\"),\n\t\t\t\t\t\tmetadata: product.metadata ? JSON.stringify(product.metadata) : undefined,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t};\n\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\tmodel: \"paystackProduct\",\n\t\t\t\t\t\t\tupdate: productData,\n\t\t\t\t\t\t\twhere: [{ field: \"id\", value: existing.id }],\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait ctx.context.adapter.create({\n\t\t\t\t\t\t\tmodel: \"paystackProduct\",\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t...productData,\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn ctx.json({ status: \"success\", count: productsData.length });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tctx.context.logger.error(\"Failed to sync products\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: (error as Error)?.message ?? \"Failed to sync products\",\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t);\n};\n\nexport const listProducts = (_options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/list-products\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tmetadata: {\n\t\t\t\topenapi: {\n\t\t\t\t\toperationId: \"listPaystackProducts\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst res = await ctx.context.adapter.findMany<PaystackProduct>({\n\t\t\t\tmodel: \"paystackProduct\",\n\t\t\t});\n\t\t\tconst sorted = res.sort((a, b) => a.name.localeCompare(b.name));\n\t\t\treturn ctx.json({ products: sorted });\n\t\t}\n\t);\n};\n\nexport const syncPlans = (options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/sync-plans\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tmetadata: {\n\t\t\t\t...HIDE_METADATA,\n\t\t\t},\n\t\t\tdisableBody: true,\n\t\t\tuse: [sessionMiddleware],\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\ttry {\n\t\t\t\tconst raw = await paystack.planList();\n\t\t\t\tconst res = unwrapSdkResult<Record<string, unknown>>(raw);\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\tconst plansData = (res !== null && typeof res === \"object\" && \"status\" in res && \"data\" in res) ? (res as Record<string, any>).data : (res as Record<string, any>)?.data ?? res;\n\n\t\t\t\tif (!Array.isArray(plansData)) {\n\t\t\t\t\treturn ctx.json({ status: \"success\", count: 0 });\n\t\t\t\t}\n\n\t\t\t\tfor (const plan of plansData) {\n\t\t\t\t\tconst paystackId = String(plan.id);\n\t\t\t\t\tconst existing = await ctx.context.adapter.findOne<any>({\n\t\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t\t\twhere: [{ field: \"paystackId\", value: paystackId }],\n\t\t\t\t\t});\n\n\t\t\t\t\tconst planData = {\n\t\t\t\t\t\tname: plan.name,\n\t\t\t\t\t\tdescription: plan.description,\n\t\t\t\t\t\tamount: plan.amount,\n\t\t\t\t\t\tcurrency: plan.currency,\n\t\t\t\t\t\tinterval: plan.interval,\n\t\t\t\t\t\tplanCode: plan.plan_code,\n\t\t\t\t\t\tpaystackId,\n\t\t\t\t\t\tmetadata: plan.metadata ? JSON.stringify(plan.metadata) : undefined,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t};\n\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t\t\t\tupdate: planData,\n\t\t\t\t\t\t\twhere: [{ field: \"id\", value: existing.id }],\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait ctx.context.adapter.create({\n\t\t\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\t...planData,\n\t\t\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn ctx.json({ status: \"success\", count: plansData.length });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tctx.context.logger.error(\"Failed to sync plans\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: (error as Error)?.message ?? \"Failed to sync plans\",\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t);\n};\n\nexport const listPlans = (_options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/list-plans\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tmetadata: {\n\t\t\t\t...HIDE_METADATA,\n\t\t\t},\n\t\t\tuse: [sessionMiddleware],\n\t\t},\n\t\tasync (ctx) => {\n\t\t\ttry {\n\t\t\t\tconst plans = await ctx.context.adapter.findMany<any>({\n\t\t\t\t\tmodel: \"paystackPlan\",\n\t\t\t\t});\n\t\t\t\treturn ctx.json({ plans });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tctx.context.logger.error(\"Failed to list plans\", error);\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: (error as Error)?.message ?? \"Failed to list plans\",\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t);\n};\n\nexport const getConfig = (options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/get-config\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tmetadata: {\n\t\t\t\topenapi: {\n\t\t\t\t\toperationId: \"getPaystackConfig\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst plans = options.subscription?.enabled === true\n\t\t\t\t? await getPlans(options.subscription)\n\t\t\t\t: [];\n\t\t\tconst products = await getProducts(options.products);\n\t\t\treturn ctx.json({\n\t\t\t\tplans,\n\t\t\t\tproducts,\n\t\t\t});\n\t\t}\n\t);\n};\n\nexport { PAYSTACK_ERROR_CODES };\nexport const chargeRecurringSubscription = (options: AnyPaystackOptions) => {\n\treturn createAuthEndpoint(\n\t\t\"/paystack/charge-recurring\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: z.object({\n\t\t\t\tsubscriptionId: z.string(),\n\t\t\t\tamount: z.number().optional(),\n\t\t\t}),\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst { subscriptionId, amount: bodyAmount } = ctx.body;\n\t\t\tconst subscription = await ctx.context.adapter.findOne<Subscription>({\n\t\t\t\tmodel: \"subscription\",\n\t\t\t\twhere: [{ field: \"id\", value: subscriptionId }],\n\t\t\t});\n\n\t\t\tif (subscription === null || subscription === undefined) {\n\t\t\t\tthrow new APIError(\"NOT_FOUND\", { message: \"Subscription not found\" });\n\t\t\t}\n\n\t\t\tif (subscription.paystackAuthorizationCode === undefined || subscription.paystackAuthorizationCode === null || subscription.paystackAuthorizationCode === \"\") {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", { message: \"No authorization code found for this subscription\" });\n\t\t\t}\n\n\t\t\tconst plans = await getPlans(options.subscription);\n\t\t\tconst plan = plans.find((p) => p.name.toLowerCase() === subscription.plan.toLowerCase());\n\n\t\t\tif (plan === undefined || plan === null) {\n\t\t\t\tthrow new APIError(\"NOT_FOUND\", { message: \"Plan not found\" });\n\t\t\t}\n\n\t\t\tconst amount = bodyAmount ?? plan.amount;\n\t\t\tif (amount === undefined || amount === null) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", { message: \"Plan amount is not defined\" });\n\t\t\t}\n\n\t\t\tlet email: string | null | undefined;\n\t\t\tif (subscription.referenceId !== undefined && subscription.referenceId !== null && subscription.referenceId !== \"\") {\n\t\t\t\t// Try to find user or org\n\t\t\t\tconst user = await ctx.context.adapter.findOne<User>({\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\twhere: [{ field: \"id\", value: subscription.referenceId }],\n\t\t\t\t});\n\t\t\t\tif (user !== undefined && user !== null) {\n\t\t\t\t\temail = user.email;\n\t\t\t\t} else if (options.organization?.enabled === true) {\n\t\t\t\t\t// Check org owner email if referenceId is organizationId\n\t\t\t\t\tconst ownerMember = await ctx.context.adapter.findOne<Member>({\n\t\t\t\t\t\tmodel: \"member\",\n\t\t\t\t\t\twhere: [\n\t\t\t\t\t\t\t{ field: \"organizationId\", value: subscription.referenceId },\n\t\t\t\t\t\t\t{ field: \"role\", value: \"owner\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t});\n\t\t\t\t\tif (ownerMember !== undefined && ownerMember !== null) {\n\t\t\t\t\t\tconst ownerUser = await ctx.context.adapter.findOne<User>({\n\t\t\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\t\t\twhere: [{ field: \"id\", value: ownerMember.userId }],\n\t\t\t\t\t\t});\n\t\t\t\t\t\temail = ownerUser?.email;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// No fallback needed since referenceId is required and handled above\n\t\t\tif (email === undefined || email === null || email === \"\") {\n\t\t\t\tthrow new APIError(\"NOT_FOUND\", { message: \"User email not found\" });\n\t\t\t}\n\n\t\t\tconst finalCurrency = plan.currency ?? \"NGN\";\n\t\t\tif (!validateMinAmount(amount, finalCurrency)) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: `Amount ${amount} is less than the minimum required for ${finalCurrency}.`,\n\t\t\t\t\tstatus: 400\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst paystack = getPaystackOps(options.paystackClient);\n\t\t\tconst chargeRes = await paystack.transactionChargeAuthorization({\n\t\t\t\temail,\n\t\t\t\tamount,\n\t\t\t\tauthorization_code: subscription.paystackAuthorizationCode,\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\tcurrency: plan.currency as any,\n\t\t\t\tmetadata: {\n\t\t\t\t\tsubscriptionId,\n\t\t\t\t\treferenceId: subscription.referenceId,\n\t\t\t\t\tplan: plan.name,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tconst data = unwrapSdkResult<Record<string, unknown>>(chargeRes);\n\t\t\tconst chargeData = (data as { data?: Record<string, unknown> })?.data ?? data;\n\n\t\t\tif (chargeData?.status === \"success\") {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst nextPeriodEnd = getNextPeriodEnd(now, plan.interval ?? \"monthly\");\n\n\t\t\t\tawait ctx.context.adapter.update({\n\t\t\t\t\tmodel: \"subscription\",\n\t\t\t\t\tupdate: {\n\t\t\t\t\t\tperiodStart: now,\n\t\t\t\t\t\tperiodEnd: nextPeriodEnd,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t\t// Record the last transaction reference if available\n\t\t\t\t\t\tpaystackTransactionReference: chargeData.reference as string | undefined,\n\t\t\t\t\t},\n\t\t\t\t\twhere: [{ field: \"id\", value: subscription.id }],\n\t\t\t\t});\n\n\t\t\t\treturn ctx.json({ status: \"success\", data: chargeData });\n\t\t\t}\n\n\t\t\treturn ctx.json({ status: \"failed\", data: chargeData }, { status: 400 });\n\t\t},\n\t);\n};\n",
"usedDeprecatedRules": [
{
"ruleId": "indent",
"replacedBy": ["@stylistic/indent"],
"info": {
"message": "Formatting rules are being moved out of ESLint core.",
"url": "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
"deprecatedSince": "8.53.0",
"availableUntil": "11.0.0",
"replacedBy": [
{
"message": "ESLint Stylistic now maintains deprecated stylistic core rules.",
"url": "https://eslint.style/guide/migration",
"plugin": { "name": "@stylistic/eslint-plugin", "url": "https://eslint.style" },
"rule": { "name": "indent", "url": "https://eslint.style/rules/indent" }
}
]
}
}
]
},
{
"filePath": "/Users/alexasomba/Documents/GitHub/alexasomba/better-auth-paystack/src/schema.ts",
"messages": [],
"suppressedMessages": [
{
"ruleId": "@typescript-eslint/no-explicit-any",
"severity": 1,
"message": "Unexpected any. Specify a different type.",
"line": 270,
"column": 72,
"nodeType": "TSAnyKeyword",
"messageId": "unexpectedAny",
"endLine": 270,
"endColumn": 75,
"suggestions": [
{
"messageId": "suggestUnknown",
"fix": { "range": [4490, 4493], "text": "unknown" },
"desc": "Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."
},
{
"messageId": "suggestNever",
"fix": { "range": [4490, 4493], "text": "never" },
"desc": "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."