@djangocfg/ext-payments 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1688 @@
1
+ import { initializeExtensionAPI, createExtensionAPI } from '@djangocfg/ext-base/api';
2
+ import { createConsola, consola } from 'consola';
3
+ import pRetry, { AbortError } from 'p-retry';
4
+ import { z } from 'zod';
5
+ import useSWR, { useSWRConfig } from 'swr';
6
+
7
+ // src/api/generated/ext_payments/ext_payments__payments/client.ts
8
+ var ExtPaymentsPayments = class {
9
+ client;
10
+ constructor(client) {
11
+ this.client = client;
12
+ }
13
+ /**
14
+ * Get user balance
15
+ *
16
+ * Get current user balance and transaction statistics
17
+ */
18
+ async balanceRetrieve() {
19
+ const response = await this.client.request("GET", "/cfg/payments/balance/");
20
+ return response;
21
+ }
22
+ /**
23
+ * Get available currencies
24
+ *
25
+ * Returns list of available currencies with token+network info, popular
26
+ * first
27
+ */
28
+ async currenciesList() {
29
+ const response = await this.client.request("GET", "/cfg/payments/currencies/");
30
+ return response;
31
+ }
32
+ /**
33
+ * Get currency estimate
34
+ *
35
+ * Get estimated crypto amount for a given USD amount, including min amount
36
+ */
37
+ async currenciesEstimateRetrieve(...args) {
38
+ const code = args[0];
39
+ const isParamsObject = args.length === 2 && typeof args[1] === "object" && args[1] !== null && !Array.isArray(args[1]);
40
+ let params;
41
+ if (isParamsObject) {
42
+ params = args[1];
43
+ } else {
44
+ params = { amount: args[1] };
45
+ }
46
+ const response = await this.client.request("GET", `/cfg/payments/currencies/${code}/estimate/`, { params });
47
+ return response;
48
+ }
49
+ /**
50
+ * Get withdrawal estimate
51
+ *
52
+ * Get estimated crypto amount for withdrawal with fee breakdown
53
+ */
54
+ async currenciesWithdrawalEstimateRetrieve(...args) {
55
+ const code = args[0];
56
+ const isParamsObject = args.length === 2 && typeof args[1] === "object" && args[1] !== null && !Array.isArray(args[1]);
57
+ let params;
58
+ if (isParamsObject) {
59
+ params = args[1];
60
+ } else {
61
+ params = { amount: args[1] };
62
+ }
63
+ const response = await this.client.request("GET", `/cfg/payments/currencies/${code}/withdrawal-estimate/`, { params });
64
+ return response;
65
+ }
66
+ /**
67
+ * ViewSet for payment operations. Endpoints: - GET /payments/ - List
68
+ * user's payments - GET /payments/{id}/ - Get payment details - POST
69
+ * /payments/create/ - Create new payment - GET /payments/{id}/status/ -
70
+ * Check payment status - POST /payments/{id}/confirm/ - Confirm payment
71
+ */
72
+ async paymentsList(...args) {
73
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
74
+ let params;
75
+ if (isParamsObject) {
76
+ params = args[0];
77
+ } else {
78
+ params = { page: args[0], page_size: args[1] };
79
+ }
80
+ const response = await this.client.request("GET", "/cfg/payments/payments/", { params });
81
+ return response;
82
+ }
83
+ /**
84
+ * ViewSet for payment operations. Endpoints: - GET /payments/ - List
85
+ * user's payments - GET /payments/{id}/ - Get payment details - POST
86
+ * /payments/create/ - Create new payment - GET /payments/{id}/status/ -
87
+ * Check payment status - POST /payments/{id}/confirm/ - Confirm payment
88
+ */
89
+ async paymentsRetrieve(id) {
90
+ const response = await this.client.request("GET", `/cfg/payments/payments/${id}/`);
91
+ return response;
92
+ }
93
+ /**
94
+ * POST /api/v1/payments/{id}/confirm/ Confirm payment (user clicked "I
95
+ * have paid"). Checks status with provider and creates transaction if
96
+ * completed.
97
+ */
98
+ async paymentsConfirmCreate(id) {
99
+ const response = await this.client.request("POST", `/cfg/payments/payments/${id}/confirm/`);
100
+ return response;
101
+ }
102
+ /**
103
+ * GET /api/v1/payments/{id}/status/?refresh=true Check payment status
104
+ * (with optional refresh from provider). Query params: - refresh: boolean
105
+ * (default: false) - Force refresh from provider
106
+ */
107
+ async paymentsStatusRetrieve(id) {
108
+ const response = await this.client.request("GET", `/cfg/payments/payments/${id}/status/`);
109
+ return response.results || response;
110
+ }
111
+ /**
112
+ * Create payment
113
+ *
114
+ * Create a new payment with specified amount and currency
115
+ */
116
+ async paymentsCreateCreate(data) {
117
+ const response = await this.client.request("POST", "/cfg/payments/payments/create/", { body: data });
118
+ return response;
119
+ }
120
+ /**
121
+ * Get user transactions
122
+ *
123
+ * Get user transactions with pagination and filtering
124
+ */
125
+ async transactionsList(...args) {
126
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
127
+ let params;
128
+ if (isParamsObject) {
129
+ params = args[0];
130
+ } else {
131
+ params = { limit: args[0], offset: args[1], type: args[2] };
132
+ }
133
+ const response = await this.client.request("GET", "/cfg/payments/transactions/", { params });
134
+ return response;
135
+ }
136
+ /**
137
+ * ViewSet for withdrawal operations. Endpoints: - GET /withdrawals/ - List
138
+ * user's withdrawal requests - GET /withdrawals/{id}/ - Get withdrawal
139
+ * details - POST /withdrawals/create/ - Create withdrawal request - POST
140
+ * /withdrawals/{id}/cancel/ - Cancel pending withdrawal
141
+ */
142
+ async withdrawalsList(...args) {
143
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
144
+ let params;
145
+ if (isParamsObject) {
146
+ params = args[0];
147
+ } else {
148
+ params = { page: args[0], page_size: args[1] };
149
+ }
150
+ const response = await this.client.request("GET", "/cfg/payments/withdrawals/", { params });
151
+ return response;
152
+ }
153
+ /**
154
+ * ViewSet for withdrawal operations. Endpoints: - GET /withdrawals/ - List
155
+ * user's withdrawal requests - GET /withdrawals/{id}/ - Get withdrawal
156
+ * details - POST /withdrawals/create/ - Create withdrawal request - POST
157
+ * /withdrawals/{id}/cancel/ - Cancel pending withdrawal
158
+ */
159
+ async withdrawalsRetrieve(id) {
160
+ const response = await this.client.request("GET", `/cfg/payments/withdrawals/${id}/`);
161
+ return response;
162
+ }
163
+ /**
164
+ * Cancel withdrawal request
165
+ *
166
+ * Cancel a pending withdrawal request
167
+ */
168
+ async withdrawalsCancelCreate(id) {
169
+ const response = await this.client.request("POST", `/cfg/payments/withdrawals/${id}/cancel/`);
170
+ return response;
171
+ }
172
+ /**
173
+ * Create withdrawal request
174
+ *
175
+ * Create a new withdrawal request (requires admin approval)
176
+ */
177
+ async withdrawalsCreateCreate(data) {
178
+ const response = await this.client.request("POST", "/cfg/payments/withdrawals/create/", { body: data });
179
+ return response;
180
+ }
181
+ };
182
+
183
+ // src/api/generated/ext_payments/http.ts
184
+ var FetchAdapter = class {
185
+ async request(request) {
186
+ const { method, url, headers, body, params, formData, binaryBody } = request;
187
+ let finalUrl = url;
188
+ if (params) {
189
+ const searchParams = new URLSearchParams();
190
+ Object.entries(params).forEach(([key, value]) => {
191
+ if (value !== null && value !== void 0) {
192
+ searchParams.append(key, String(value));
193
+ }
194
+ });
195
+ const queryString = searchParams.toString();
196
+ if (queryString) {
197
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
198
+ }
199
+ }
200
+ const finalHeaders = { ...headers };
201
+ let requestBody;
202
+ if (formData) {
203
+ requestBody = formData;
204
+ } else if (binaryBody) {
205
+ finalHeaders["Content-Type"] = "application/octet-stream";
206
+ requestBody = binaryBody;
207
+ } else if (body) {
208
+ finalHeaders["Content-Type"] = "application/json";
209
+ requestBody = JSON.stringify(body);
210
+ }
211
+ const response = await fetch(finalUrl, {
212
+ method,
213
+ headers: finalHeaders,
214
+ body: requestBody,
215
+ credentials: "include"
216
+ // Include Django session cookies
217
+ });
218
+ let data = null;
219
+ const contentType = response.headers.get("content-type");
220
+ if (response.status !== 204 && contentType?.includes("application/json")) {
221
+ data = await response.json();
222
+ } else if (response.status !== 204) {
223
+ data = await response.text();
224
+ }
225
+ const responseHeaders = {};
226
+ response.headers.forEach((value, key) => {
227
+ responseHeaders[key] = value;
228
+ });
229
+ return {
230
+ data,
231
+ status: response.status,
232
+ statusText: response.statusText,
233
+ headers: responseHeaders
234
+ };
235
+ }
236
+ };
237
+
238
+ // src/api/generated/ext_payments/errors.ts
239
+ var APIError = class extends Error {
240
+ constructor(statusCode, statusText, response, url, message) {
241
+ super(message || `HTTP ${statusCode}: ${statusText}`);
242
+ this.statusCode = statusCode;
243
+ this.statusText = statusText;
244
+ this.response = response;
245
+ this.url = url;
246
+ this.name = "APIError";
247
+ }
248
+ /**
249
+ * Get error details from response.
250
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
251
+ */
252
+ get details() {
253
+ if (typeof this.response === "object" && this.response !== null) {
254
+ return this.response;
255
+ }
256
+ return null;
257
+ }
258
+ /**
259
+ * Get field-specific validation errors from DRF.
260
+ * Returns: { "field_name": ["error1", "error2"], ... }
261
+ */
262
+ get fieldErrors() {
263
+ const details = this.details;
264
+ if (!details) return null;
265
+ const fieldErrors = {};
266
+ for (const [key, value] of Object.entries(details)) {
267
+ if (Array.isArray(value)) {
268
+ fieldErrors[key] = value;
269
+ }
270
+ }
271
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
272
+ }
273
+ /**
274
+ * Get single error message from DRF.
275
+ * Checks for "detail", "message", or first field error.
276
+ */
277
+ get errorMessage() {
278
+ const details = this.details;
279
+ if (!details) return this.message;
280
+ if (details.detail) {
281
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
282
+ }
283
+ if (details.message) {
284
+ return String(details.message);
285
+ }
286
+ const fieldErrors = this.fieldErrors;
287
+ if (fieldErrors) {
288
+ const firstField = Object.keys(fieldErrors)[0];
289
+ if (firstField) {
290
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
291
+ }
292
+ }
293
+ return this.message;
294
+ }
295
+ // Helper methods for common HTTP status codes
296
+ get isValidationError() {
297
+ return this.statusCode === 400;
298
+ }
299
+ get isAuthError() {
300
+ return this.statusCode === 401;
301
+ }
302
+ get isPermissionError() {
303
+ return this.statusCode === 403;
304
+ }
305
+ get isNotFoundError() {
306
+ return this.statusCode === 404;
307
+ }
308
+ get isServerError() {
309
+ return this.statusCode >= 500 && this.statusCode < 600;
310
+ }
311
+ };
312
+ var NetworkError = class extends Error {
313
+ constructor(message, url, originalError) {
314
+ super(message);
315
+ this.url = url;
316
+ this.originalError = originalError;
317
+ this.name = "NetworkError";
318
+ }
319
+ };
320
+ var DEFAULT_CONFIG = {
321
+ enabled: process.env.NODE_ENV !== "production",
322
+ logRequests: true,
323
+ logResponses: true,
324
+ logErrors: true,
325
+ logBodies: true,
326
+ logHeaders: false
327
+ };
328
+ var SENSITIVE_HEADERS = [
329
+ "authorization",
330
+ "cookie",
331
+ "set-cookie",
332
+ "x-api-key",
333
+ "x-csrf-token"
334
+ ];
335
+ var APILogger = class {
336
+ config;
337
+ consola;
338
+ constructor(config = {}) {
339
+ this.config = { ...DEFAULT_CONFIG, ...config };
340
+ this.consola = config.consola || createConsola({
341
+ level: this.config.enabled ? 4 : 0
342
+ });
343
+ }
344
+ /**
345
+ * Enable logging
346
+ */
347
+ enable() {
348
+ this.config.enabled = true;
349
+ }
350
+ /**
351
+ * Disable logging
352
+ */
353
+ disable() {
354
+ this.config.enabled = false;
355
+ }
356
+ /**
357
+ * Update configuration
358
+ */
359
+ setConfig(config) {
360
+ this.config = { ...this.config, ...config };
361
+ }
362
+ /**
363
+ * Filter sensitive headers
364
+ */
365
+ filterHeaders(headers) {
366
+ if (!headers) return {};
367
+ const filtered = {};
368
+ Object.keys(headers).forEach((key) => {
369
+ const lowerKey = key.toLowerCase();
370
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
371
+ filtered[key] = "***";
372
+ } else {
373
+ filtered[key] = headers[key] || "";
374
+ }
375
+ });
376
+ return filtered;
377
+ }
378
+ /**
379
+ * Log request
380
+ */
381
+ logRequest(request) {
382
+ if (!this.config.enabled || !this.config.logRequests) return;
383
+ const { method, url, headers, body } = request;
384
+ this.consola.start(`${method} ${url}`);
385
+ if (this.config.logHeaders && headers) {
386
+ this.consola.debug("Headers:", this.filterHeaders(headers));
387
+ }
388
+ if (this.config.logBodies && body) {
389
+ this.consola.debug("Body:", body);
390
+ }
391
+ }
392
+ /**
393
+ * Log response
394
+ */
395
+ logResponse(request, response) {
396
+ if (!this.config.enabled || !this.config.logResponses) return;
397
+ const { method, url } = request;
398
+ const { status, statusText, data, duration } = response;
399
+ this.consola.success(
400
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
401
+ );
402
+ if (this.config.logBodies && data) {
403
+ this.consola.debug("Response:", data);
404
+ }
405
+ }
406
+ /**
407
+ * Log error
408
+ */
409
+ logError(request, error) {
410
+ if (!this.config.enabled || !this.config.logErrors) return;
411
+ const { method, url } = request;
412
+ const { message, statusCode, fieldErrors, duration } = error;
413
+ this.consola.error(
414
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
415
+ );
416
+ this.consola.error("Message:", message);
417
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
418
+ this.consola.error("Field Errors:");
419
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
420
+ errors.forEach((err) => {
421
+ this.consola.error(` \u2022 ${field}: ${err}`);
422
+ });
423
+ });
424
+ }
425
+ }
426
+ /**
427
+ * Log general info
428
+ */
429
+ info(message, ...args) {
430
+ if (!this.config.enabled) return;
431
+ this.consola.info(message, ...args);
432
+ }
433
+ /**
434
+ * Log warning
435
+ */
436
+ warn(message, ...args) {
437
+ if (!this.config.enabled) return;
438
+ this.consola.warn(message, ...args);
439
+ }
440
+ /**
441
+ * Log error
442
+ */
443
+ error(message, ...args) {
444
+ if (!this.config.enabled) return;
445
+ this.consola.error(message, ...args);
446
+ }
447
+ /**
448
+ * Log debug
449
+ */
450
+ debug(message, ...args) {
451
+ if (!this.config.enabled) return;
452
+ this.consola.debug(message, ...args);
453
+ }
454
+ /**
455
+ * Log success
456
+ */
457
+ success(message, ...args) {
458
+ if (!this.config.enabled) return;
459
+ this.consola.success(message, ...args);
460
+ }
461
+ /**
462
+ * Create a sub-logger with prefix
463
+ */
464
+ withTag(tag) {
465
+ return this.consola.withTag(tag);
466
+ }
467
+ };
468
+ new APILogger();
469
+ var DEFAULT_RETRY_CONFIG = {
470
+ retries: 3,
471
+ factor: 2,
472
+ minTimeout: 1e3,
473
+ maxTimeout: 6e4,
474
+ randomize: true,
475
+ onFailedAttempt: () => {
476
+ }
477
+ };
478
+ function shouldRetry(error) {
479
+ if (error instanceof NetworkError) {
480
+ return true;
481
+ }
482
+ if (error instanceof APIError) {
483
+ const status = error.statusCode;
484
+ if (status >= 500 && status < 600) {
485
+ return true;
486
+ }
487
+ if (status === 429) {
488
+ return true;
489
+ }
490
+ return false;
491
+ }
492
+ return true;
493
+ }
494
+ async function withRetry(fn, config) {
495
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
496
+ return pRetry(
497
+ async () => {
498
+ try {
499
+ return await fn();
500
+ } catch (error) {
501
+ if (!shouldRetry(error)) {
502
+ throw new AbortError(error);
503
+ }
504
+ throw error;
505
+ }
506
+ },
507
+ {
508
+ retries: finalConfig.retries,
509
+ factor: finalConfig.factor,
510
+ minTimeout: finalConfig.minTimeout,
511
+ maxTimeout: finalConfig.maxTimeout,
512
+ randomize: finalConfig.randomize,
513
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
514
+ const pRetryError = error;
515
+ finalConfig.onFailedAttempt({
516
+ error: pRetryError,
517
+ attemptNumber: pRetryError.attemptNumber,
518
+ retriesLeft: pRetryError.retriesLeft
519
+ });
520
+ } : void 0
521
+ }
522
+ );
523
+ }
524
+
525
+ // src/api/generated/ext_payments/client.ts
526
+ var APIClient = class {
527
+ baseUrl;
528
+ httpClient;
529
+ logger = null;
530
+ retryConfig = null;
531
+ tokenGetter = null;
532
+ // Sub-clients
533
+ ext_payments_payments;
534
+ constructor(baseUrl, options) {
535
+ this.baseUrl = baseUrl.replace(/\/$/, "");
536
+ this.httpClient = options?.httpClient || new FetchAdapter();
537
+ this.tokenGetter = options?.tokenGetter || null;
538
+ if (options?.loggerConfig !== void 0) {
539
+ this.logger = new APILogger(options.loggerConfig);
540
+ }
541
+ if (options?.retryConfig !== void 0) {
542
+ this.retryConfig = options.retryConfig;
543
+ }
544
+ this.ext_payments_payments = new ExtPaymentsPayments(this);
545
+ }
546
+ /**
547
+ * Get CSRF token from cookies (for SessionAuthentication).
548
+ *
549
+ * Returns null if cookie doesn't exist (JWT-only auth).
550
+ */
551
+ getCsrfToken() {
552
+ const name = "csrftoken";
553
+ const value = `; ${document.cookie}`;
554
+ const parts = value.split(`; ${name}=`);
555
+ if (parts.length === 2) {
556
+ return parts.pop()?.split(";").shift() || null;
557
+ }
558
+ return null;
559
+ }
560
+ /**
561
+ * Get the base URL for building streaming/download URLs.
562
+ */
563
+ getBaseUrl() {
564
+ return this.baseUrl;
565
+ }
566
+ /**
567
+ * Get JWT token for URL authentication (used in streaming endpoints).
568
+ * Returns null if no token getter is configured or no token is available.
569
+ */
570
+ getToken() {
571
+ return this.tokenGetter ? this.tokenGetter() : null;
572
+ }
573
+ /**
574
+ * Make HTTP request with Django CSRF and session handling.
575
+ * Automatically retries on network errors and 5xx server errors.
576
+ */
577
+ async request(method, path, options) {
578
+ if (this.retryConfig) {
579
+ return withRetry(() => this._makeRequest(method, path, options), {
580
+ ...this.retryConfig,
581
+ onFailedAttempt: (info) => {
582
+ if (this.logger) {
583
+ this.logger.warn(
584
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
585
+ );
586
+ }
587
+ this.retryConfig?.onFailedAttempt?.(info);
588
+ }
589
+ });
590
+ }
591
+ return this._makeRequest(method, path, options);
592
+ }
593
+ /**
594
+ * Internal request method (without retry wrapper).
595
+ * Used by request() method with optional retry logic.
596
+ */
597
+ async _makeRequest(method, path, options) {
598
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
599
+ const startTime = Date.now();
600
+ const headers = {
601
+ ...options?.headers || {}
602
+ };
603
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
604
+ headers["Content-Type"] = "application/json";
605
+ }
606
+ if (this.logger) {
607
+ this.logger.logRequest({
608
+ method,
609
+ url,
610
+ headers,
611
+ body: options?.formData || options?.body,
612
+ timestamp: startTime
613
+ });
614
+ }
615
+ try {
616
+ const response = await this.httpClient.request({
617
+ method,
618
+ url,
619
+ headers,
620
+ params: options?.params,
621
+ body: options?.body,
622
+ formData: options?.formData,
623
+ binaryBody: options?.binaryBody
624
+ });
625
+ const duration = Date.now() - startTime;
626
+ if (response.status >= 400) {
627
+ const error = new APIError(
628
+ response.status,
629
+ response.statusText,
630
+ response.data,
631
+ url
632
+ );
633
+ if (this.logger) {
634
+ this.logger.logError(
635
+ {
636
+ method,
637
+ url,
638
+ headers,
639
+ body: options?.formData || options?.body,
640
+ timestamp: startTime
641
+ },
642
+ {
643
+ message: error.message,
644
+ statusCode: response.status,
645
+ duration,
646
+ timestamp: Date.now()
647
+ }
648
+ );
649
+ }
650
+ throw error;
651
+ }
652
+ if (this.logger) {
653
+ this.logger.logResponse(
654
+ {
655
+ method,
656
+ url,
657
+ headers,
658
+ body: options?.formData || options?.body,
659
+ timestamp: startTime
660
+ },
661
+ {
662
+ status: response.status,
663
+ statusText: response.statusText,
664
+ data: response.data,
665
+ duration,
666
+ timestamp: Date.now()
667
+ }
668
+ );
669
+ }
670
+ return response.data;
671
+ } catch (error) {
672
+ const duration = Date.now() - startTime;
673
+ if (error instanceof APIError) {
674
+ throw error;
675
+ }
676
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
677
+ if (this.logger) {
678
+ if (isCORSError) {
679
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
680
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
681
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
682
+ } else {
683
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
684
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
685
+ }
686
+ }
687
+ if (typeof window !== "undefined") {
688
+ try {
689
+ if (isCORSError) {
690
+ window.dispatchEvent(new CustomEvent("cors-error", {
691
+ detail: {
692
+ url,
693
+ method,
694
+ error: error instanceof Error ? error.message : String(error),
695
+ timestamp: /* @__PURE__ */ new Date()
696
+ },
697
+ bubbles: true,
698
+ cancelable: false
699
+ }));
700
+ } else {
701
+ window.dispatchEvent(new CustomEvent("network-error", {
702
+ detail: {
703
+ url,
704
+ method,
705
+ error: error instanceof Error ? error.message : String(error),
706
+ timestamp: /* @__PURE__ */ new Date()
707
+ },
708
+ bubbles: true,
709
+ cancelable: false
710
+ }));
711
+ }
712
+ } catch (eventError) {
713
+ }
714
+ }
715
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
716
+ if (this.logger) {
717
+ this.logger.logError(
718
+ {
719
+ method,
720
+ url,
721
+ headers,
722
+ body: options?.formData || options?.body,
723
+ timestamp: startTime
724
+ },
725
+ {
726
+ message: networkError.message,
727
+ duration,
728
+ timestamp: Date.now()
729
+ }
730
+ );
731
+ }
732
+ throw networkError;
733
+ }
734
+ }
735
+ };
736
+
737
+ // src/api/generated/ext_payments/storage.ts
738
+ var LocalStorageAdapter = class {
739
+ logger;
740
+ constructor(logger) {
741
+ this.logger = logger;
742
+ }
743
+ getItem(key) {
744
+ try {
745
+ if (typeof window !== "undefined" && window.localStorage) {
746
+ const value = localStorage.getItem(key);
747
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
748
+ return value;
749
+ }
750
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
751
+ } catch (error) {
752
+ this.logger?.error("LocalStorage.getItem failed:", error);
753
+ }
754
+ return null;
755
+ }
756
+ setItem(key, value) {
757
+ try {
758
+ if (typeof window !== "undefined" && window.localStorage) {
759
+ localStorage.setItem(key, value);
760
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
761
+ } else {
762
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
763
+ }
764
+ } catch (error) {
765
+ this.logger?.error("LocalStorage.setItem failed:", error);
766
+ }
767
+ }
768
+ removeItem(key) {
769
+ try {
770
+ if (typeof window !== "undefined" && window.localStorage) {
771
+ localStorage.removeItem(key);
772
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
773
+ } else {
774
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
775
+ }
776
+ } catch (error) {
777
+ this.logger?.error("LocalStorage.removeItem failed:", error);
778
+ }
779
+ }
780
+ };
781
+
782
+ // src/api/generated/ext_payments/enums.ts
783
+ var PaymentDetailStatus = /* @__PURE__ */ ((PaymentDetailStatus2) => {
784
+ PaymentDetailStatus2["PENDING"] = "pending";
785
+ PaymentDetailStatus2["CONFIRMING"] = "confirming";
786
+ PaymentDetailStatus2["CONFIRMED"] = "confirmed";
787
+ PaymentDetailStatus2["COMPLETED"] = "completed";
788
+ PaymentDetailStatus2["PARTIALLY_PAID"] = "partially_paid";
789
+ PaymentDetailStatus2["FAILED"] = "failed";
790
+ PaymentDetailStatus2["EXPIRED"] = "expired";
791
+ PaymentDetailStatus2["CANCELLED"] = "cancelled";
792
+ return PaymentDetailStatus2;
793
+ })(PaymentDetailStatus || {});
794
+ var PaymentListStatus = /* @__PURE__ */ ((PaymentListStatus2) => {
795
+ PaymentListStatus2["PENDING"] = "pending";
796
+ PaymentListStatus2["CONFIRMING"] = "confirming";
797
+ PaymentListStatus2["CONFIRMED"] = "confirmed";
798
+ PaymentListStatus2["COMPLETED"] = "completed";
799
+ PaymentListStatus2["PARTIALLY_PAID"] = "partially_paid";
800
+ PaymentListStatus2["FAILED"] = "failed";
801
+ PaymentListStatus2["EXPIRED"] = "expired";
802
+ PaymentListStatus2["CANCELLED"] = "cancelled";
803
+ return PaymentListStatus2;
804
+ })(PaymentListStatus || {});
805
+ var TransactionTransactionType = /* @__PURE__ */ ((TransactionTransactionType2) => {
806
+ TransactionTransactionType2["DEPOSIT"] = "deposit";
807
+ TransactionTransactionType2["WITHDRAWAL"] = "withdrawal";
808
+ TransactionTransactionType2["PAYMENT"] = "payment";
809
+ TransactionTransactionType2["REFUND"] = "refund";
810
+ TransactionTransactionType2["FEE"] = "fee";
811
+ TransactionTransactionType2["BONUS"] = "bonus";
812
+ TransactionTransactionType2["ADJUSTMENT"] = "adjustment";
813
+ return TransactionTransactionType2;
814
+ })(TransactionTransactionType || {});
815
+ var WithdrawalDetailStatus = /* @__PURE__ */ ((WithdrawalDetailStatus2) => {
816
+ WithdrawalDetailStatus2["PENDING"] = "pending";
817
+ WithdrawalDetailStatus2["APPROVED"] = "approved";
818
+ WithdrawalDetailStatus2["PROCESSING"] = "processing";
819
+ WithdrawalDetailStatus2["COMPLETED"] = "completed";
820
+ WithdrawalDetailStatus2["REJECTED"] = "rejected";
821
+ WithdrawalDetailStatus2["CANCELLED"] = "cancelled";
822
+ return WithdrawalDetailStatus2;
823
+ })(WithdrawalDetailStatus || {});
824
+ var WithdrawalListStatus = /* @__PURE__ */ ((WithdrawalListStatus2) => {
825
+ WithdrawalListStatus2["PENDING"] = "pending";
826
+ WithdrawalListStatus2["APPROVED"] = "approved";
827
+ WithdrawalListStatus2["PROCESSING"] = "processing";
828
+ WithdrawalListStatus2["COMPLETED"] = "completed";
829
+ WithdrawalListStatus2["REJECTED"] = "rejected";
830
+ WithdrawalListStatus2["CANCELLED"] = "cancelled";
831
+ return WithdrawalListStatus2;
832
+ })(WithdrawalListStatus || {});
833
+ var BalanceSchema = z.object({
834
+ balance_usd: z.string(),
835
+ balance_display: z.string(),
836
+ total_deposited: z.string(),
837
+ total_withdrawn: z.string(),
838
+ last_transaction_at: z.string().datetime({ offset: true }).nullable()
839
+ });
840
+ var CurrencySchema = z.object({
841
+ code: z.string(),
842
+ name: z.string(),
843
+ token: z.string(),
844
+ network: z.string().nullable(),
845
+ display_name: z.string(),
846
+ symbol: z.string(),
847
+ decimal_places: z.int(),
848
+ is_active: z.boolean(),
849
+ min_amount_usd: z.string(),
850
+ sort_order: z.int()
851
+ });
852
+ var PaymentListSchema = z.object({
853
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
854
+ internal_payment_id: z.string(),
855
+ amount_usd: z.string(),
856
+ currency_code: z.string(),
857
+ currency_token: z.string(),
858
+ status: z.nativeEnum(PaymentListStatus),
859
+ status_display: z.string(),
860
+ created_at: z.string().datetime({ offset: true }),
861
+ completed_at: z.string().datetime({ offset: true }).nullable()
862
+ });
863
+
864
+ // src/api/generated/ext_payments/_utils/schemas/PaginatedPaymentListList.schema.ts
865
+ var PaginatedPaymentListListSchema = z.object({
866
+ count: z.int(),
867
+ page: z.int(),
868
+ pages: z.int(),
869
+ page_size: z.int(),
870
+ has_next: z.boolean(),
871
+ has_previous: z.boolean(),
872
+ next_page: z.int().nullable().optional(),
873
+ previous_page: z.int().nullable().optional(),
874
+ results: z.array(PaymentListSchema)
875
+ });
876
+ var WithdrawalListSchema = z.object({
877
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
878
+ internal_withdrawal_id: z.string(),
879
+ amount_usd: z.string(),
880
+ final_amount_usd: z.string(),
881
+ currency_code: z.string(),
882
+ currency_token: z.string(),
883
+ status: z.nativeEnum(WithdrawalListStatus),
884
+ status_display: z.string(),
885
+ created_at: z.string().datetime({ offset: true }),
886
+ completed_at: z.string().datetime({ offset: true }).nullable()
887
+ });
888
+
889
+ // src/api/generated/ext_payments/_utils/schemas/PaginatedWithdrawalListList.schema.ts
890
+ var PaginatedWithdrawalListListSchema = z.object({
891
+ count: z.int(),
892
+ page: z.int(),
893
+ pages: z.int(),
894
+ page_size: z.int(),
895
+ has_next: z.boolean(),
896
+ has_previous: z.boolean(),
897
+ next_page: z.int().nullable().optional(),
898
+ previous_page: z.int().nullable().optional(),
899
+ results: z.array(WithdrawalListSchema)
900
+ });
901
+ var PaymentCreateRequestSchema = z.object({
902
+ amount_usd: z.string(),
903
+ currency_code: z.string().min(1).max(20),
904
+ description: z.string().max(500).optional()
905
+ });
906
+ var PaymentDetailSchema = z.object({
907
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
908
+ internal_payment_id: z.string(),
909
+ amount_usd: z.string(),
910
+ currency_code: z.string(),
911
+ currency_name: z.string(),
912
+ currency_token: z.string(),
913
+ currency_network: z.string(),
914
+ pay_amount: z.string().nullable(),
915
+ actual_amount: z.string().nullable(),
916
+ actual_amount_usd: z.string().nullable(),
917
+ status: z.nativeEnum(PaymentDetailStatus),
918
+ status_display: z.string(),
919
+ pay_address: z.string().nullable(),
920
+ qr_code_url: z.string().nullable(),
921
+ payment_url: z.union([z.url(), z.literal("")]).nullable(),
922
+ transaction_hash: z.string().nullable(),
923
+ explorer_link: z.string().nullable(),
924
+ confirmations_count: z.int(),
925
+ expires_at: z.string().datetime({ offset: true }).nullable(),
926
+ completed_at: z.string().datetime({ offset: true }).nullable(),
927
+ created_at: z.string().datetime({ offset: true }),
928
+ is_completed: z.boolean(),
929
+ is_failed: z.boolean(),
930
+ is_expired: z.boolean(),
931
+ description: z.string()
932
+ });
933
+
934
+ // src/api/generated/ext_payments/_utils/schemas/PaymentCreateResponse.schema.ts
935
+ var PaymentCreateResponseSchema = z.object({
936
+ success: z.boolean(),
937
+ payment: PaymentDetailSchema,
938
+ qr_code_url: z.union([z.url(), z.literal("")]).nullable()
939
+ });
940
+ var TransactionSchema = z.object({
941
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
942
+ transaction_type: z.nativeEnum(TransactionTransactionType),
943
+ type_display: z.string(),
944
+ amount_usd: z.string(),
945
+ amount_display: z.string(),
946
+ balance_after: z.string(),
947
+ payment_id: z.string().nullable(),
948
+ description: z.string(),
949
+ created_at: z.string().datetime({ offset: true })
950
+ });
951
+ var WithdrawalDetailSchema = z.object({
952
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
953
+ internal_withdrawal_id: z.string(),
954
+ amount_usd: z.string(),
955
+ currency_code: z.string(),
956
+ currency_name: z.string(),
957
+ currency_token: z.string(),
958
+ currency_network: z.string(),
959
+ wallet_address: z.string(),
960
+ network_fee_usd: z.string(),
961
+ service_fee_usd: z.string(),
962
+ total_fee_usd: z.string(),
963
+ final_amount_usd: z.string(),
964
+ crypto_amount: z.string().nullable(),
965
+ status: z.nativeEnum(WithdrawalDetailStatus),
966
+ status_display: z.string(),
967
+ transaction_hash: z.string().nullable(),
968
+ explorer_link: z.string().nullable(),
969
+ admin_notes: z.string(),
970
+ created_at: z.string().datetime({ offset: true }),
971
+ approved_at: z.string().datetime({ offset: true }).nullable(),
972
+ completed_at: z.string().datetime({ offset: true }).nullable(),
973
+ rejected_at: z.string().datetime({ offset: true }).nullable(),
974
+ cancelled_at: z.string().datetime({ offset: true }).nullable()
975
+ });
976
+
977
+ // src/api/generated/ext_payments/_utils/schemas/WithdrawalCancelResponse.schema.ts
978
+ var WithdrawalCancelResponseSchema = z.object({
979
+ success: z.boolean(),
980
+ withdrawal: WithdrawalDetailSchema,
981
+ message: z.string()
982
+ });
983
+ var WithdrawalCreateRequestSchema = z.object({
984
+ amount_usd: z.string(),
985
+ currency_code: z.string().min(1).max(20),
986
+ wallet_address: z.string().min(1).max(255)
987
+ });
988
+ var WithdrawalCreateResponseSchema = z.object({
989
+ success: z.boolean(),
990
+ withdrawal: WithdrawalDetailSchema,
991
+ message: z.string()
992
+ });
993
+
994
+ // src/api/generated/ext_payments/api-instance.ts
995
+ var globalAPI = null;
996
+ var autoConfigAttempted = false;
997
+ function tryAutoConfigureFromEnv() {
998
+ if (autoConfigAttempted) return;
999
+ autoConfigAttempted = true;
1000
+ if (globalAPI) return;
1001
+ if (typeof process === "undefined" || !process.env) return;
1002
+ const baseUrl = process.env.NEXT_PUBLIC_API_URL || process.env.VITE_API_URL || process.env.REACT_APP_API_URL || process.env.API_URL;
1003
+ if (baseUrl) {
1004
+ globalAPI = new API(baseUrl);
1005
+ }
1006
+ }
1007
+ function getAPIInstance() {
1008
+ tryAutoConfigureFromEnv();
1009
+ if (!globalAPI) {
1010
+ throw new Error(
1011
+ 'API not configured. Call configureAPI() with your base URL before using fetchers or hooks.\n\nExample:\n import { configureAPI } from "./api-instance"\n configureAPI({ baseUrl: "https://api.example.com" })\n\nOr set environment variable: NEXT_PUBLIC_API_URL, VITE_API_URL, or REACT_APP_API_URL'
1012
+ );
1013
+ }
1014
+ return globalAPI;
1015
+ }
1016
+ function configureAPI(config) {
1017
+ globalAPI = new API(config.baseUrl, config.options);
1018
+ if (config.token) {
1019
+ globalAPI.setToken(config.token, config.refreshToken);
1020
+ }
1021
+ return globalAPI;
1022
+ }
1023
+
1024
+ // src/api/generated/ext_payments/_utils/fetchers/ext_payments__payments.ts
1025
+ async function getPaymentsBalanceRetrieve(client) {
1026
+ const api = client || getAPIInstance();
1027
+ const response = await api.ext_payments_payments.balanceRetrieve();
1028
+ try {
1029
+ return BalanceSchema.parse(response);
1030
+ } catch (error) {
1031
+ consola.error("\u274C Zod Validation Failed");
1032
+ consola.box(`getPaymentsBalanceRetrieve
1033
+ Path: /cfg/payments/balance/
1034
+ Method: GET`);
1035
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1036
+ consola.error("Validation Issues:");
1037
+ error.issues.forEach((issue, index) => {
1038
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1039
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1040
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1041
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1042
+ });
1043
+ }
1044
+ consola.error("Response data:", response);
1045
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1046
+ try {
1047
+ const event = new CustomEvent("zod-validation-error", {
1048
+ detail: {
1049
+ operation: "getPaymentsBalanceRetrieve",
1050
+ path: "/cfg/payments/balance/",
1051
+ method: "GET",
1052
+ error,
1053
+ response,
1054
+ timestamp: /* @__PURE__ */ new Date()
1055
+ },
1056
+ bubbles: true,
1057
+ cancelable: false
1058
+ });
1059
+ window.dispatchEvent(event);
1060
+ } catch (eventError) {
1061
+ consola.warn("Failed to dispatch validation error event:", eventError);
1062
+ }
1063
+ }
1064
+ throw error;
1065
+ }
1066
+ }
1067
+ async function getPaymentsCurrenciesList(client) {
1068
+ const api = client || getAPIInstance();
1069
+ const response = await api.ext_payments_payments.currenciesList();
1070
+ return response;
1071
+ }
1072
+ async function getPaymentsCurrenciesEstimateRetrieve(code, params, client) {
1073
+ const api = client || getAPIInstance();
1074
+ const response = await api.ext_payments_payments.currenciesEstimateRetrieve(code, params?.amount);
1075
+ return response;
1076
+ }
1077
+ async function getPaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client) {
1078
+ const api = client || getAPIInstance();
1079
+ const response = await api.ext_payments_payments.currenciesWithdrawalEstimateRetrieve(code, params?.amount);
1080
+ return response;
1081
+ }
1082
+ async function getPaymentsPaymentsList(params, client) {
1083
+ const api = client || getAPIInstance();
1084
+ const response = await api.ext_payments_payments.paymentsList(params?.page, params?.page_size);
1085
+ try {
1086
+ return PaginatedPaymentListListSchema.parse(response);
1087
+ } catch (error) {
1088
+ consola.error("\u274C Zod Validation Failed");
1089
+ consola.box(`getPaymentsPaymentsList
1090
+ Path: /cfg/payments/payments/
1091
+ Method: GET`);
1092
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1093
+ consola.error("Validation Issues:");
1094
+ error.issues.forEach((issue, index) => {
1095
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1096
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1097
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1098
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1099
+ });
1100
+ }
1101
+ consola.error("Response data:", response);
1102
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1103
+ try {
1104
+ const event = new CustomEvent("zod-validation-error", {
1105
+ detail: {
1106
+ operation: "getPaymentsPaymentsList",
1107
+ path: "/cfg/payments/payments/",
1108
+ method: "GET",
1109
+ error,
1110
+ response,
1111
+ timestamp: /* @__PURE__ */ new Date()
1112
+ },
1113
+ bubbles: true,
1114
+ cancelable: false
1115
+ });
1116
+ window.dispatchEvent(event);
1117
+ } catch (eventError) {
1118
+ consola.warn("Failed to dispatch validation error event:", eventError);
1119
+ }
1120
+ }
1121
+ throw error;
1122
+ }
1123
+ }
1124
+ async function getPaymentsPaymentsRetrieve(id, client) {
1125
+ const api = client || getAPIInstance();
1126
+ const response = await api.ext_payments_payments.paymentsRetrieve(id);
1127
+ try {
1128
+ return PaymentDetailSchema.parse(response);
1129
+ } catch (error) {
1130
+ consola.error("\u274C Zod Validation Failed");
1131
+ consola.box(`getPaymentsPaymentsRetrieve
1132
+ Path: /cfg/payments/payments/{id}/
1133
+ Method: GET`);
1134
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1135
+ consola.error("Validation Issues:");
1136
+ error.issues.forEach((issue, index) => {
1137
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1138
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1139
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1140
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1141
+ });
1142
+ }
1143
+ consola.error("Response data:", response);
1144
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1145
+ try {
1146
+ const event = new CustomEvent("zod-validation-error", {
1147
+ detail: {
1148
+ operation: "getPaymentsPaymentsRetrieve",
1149
+ path: "/cfg/payments/payments/{id}/",
1150
+ method: "GET",
1151
+ error,
1152
+ response,
1153
+ timestamp: /* @__PURE__ */ new Date()
1154
+ },
1155
+ bubbles: true,
1156
+ cancelable: false
1157
+ });
1158
+ window.dispatchEvent(event);
1159
+ } catch (eventError) {
1160
+ consola.warn("Failed to dispatch validation error event:", eventError);
1161
+ }
1162
+ }
1163
+ throw error;
1164
+ }
1165
+ }
1166
+ async function createPaymentsPaymentsConfirmCreate(id, client) {
1167
+ const api = client || getAPIInstance();
1168
+ const response = await api.ext_payments_payments.paymentsConfirmCreate(id);
1169
+ try {
1170
+ return PaymentListSchema.parse(response);
1171
+ } catch (error) {
1172
+ consola.error("\u274C Zod Validation Failed");
1173
+ consola.box(`createPaymentsPaymentsConfirmCreate
1174
+ Path: /cfg/payments/payments/{id}/confirm/
1175
+ Method: POST`);
1176
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1177
+ consola.error("Validation Issues:");
1178
+ error.issues.forEach((issue, index) => {
1179
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1180
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1181
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1182
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1183
+ });
1184
+ }
1185
+ consola.error("Response data:", response);
1186
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1187
+ try {
1188
+ const event = new CustomEvent("zod-validation-error", {
1189
+ detail: {
1190
+ operation: "createPaymentsPaymentsConfirmCreate",
1191
+ path: "/cfg/payments/payments/{id}/confirm/",
1192
+ method: "POST",
1193
+ error,
1194
+ response,
1195
+ timestamp: /* @__PURE__ */ new Date()
1196
+ },
1197
+ bubbles: true,
1198
+ cancelable: false
1199
+ });
1200
+ window.dispatchEvent(event);
1201
+ } catch (eventError) {
1202
+ consola.warn("Failed to dispatch validation error event:", eventError);
1203
+ }
1204
+ }
1205
+ throw error;
1206
+ }
1207
+ }
1208
+ async function getPaymentsPaymentsStatusRetrieve(id, client) {
1209
+ const api = client || getAPIInstance();
1210
+ const response = await api.ext_payments_payments.paymentsStatusRetrieve(id);
1211
+ try {
1212
+ return PaymentListSchema.parse(response);
1213
+ } catch (error) {
1214
+ consola.error("\u274C Zod Validation Failed");
1215
+ consola.box(`getPaymentsPaymentsStatusRetrieve
1216
+ Path: /cfg/payments/payments/{id}/status/
1217
+ Method: GET`);
1218
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1219
+ consola.error("Validation Issues:");
1220
+ error.issues.forEach((issue, index) => {
1221
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1222
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1223
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1224
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1225
+ });
1226
+ }
1227
+ consola.error("Response data:", response);
1228
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1229
+ try {
1230
+ const event = new CustomEvent("zod-validation-error", {
1231
+ detail: {
1232
+ operation: "getPaymentsPaymentsStatusRetrieve",
1233
+ path: "/cfg/payments/payments/{id}/status/",
1234
+ method: "GET",
1235
+ error,
1236
+ response,
1237
+ timestamp: /* @__PURE__ */ new Date()
1238
+ },
1239
+ bubbles: true,
1240
+ cancelable: false
1241
+ });
1242
+ window.dispatchEvent(event);
1243
+ } catch (eventError) {
1244
+ consola.warn("Failed to dispatch validation error event:", eventError);
1245
+ }
1246
+ }
1247
+ throw error;
1248
+ }
1249
+ }
1250
+ async function createPaymentsPaymentsCreateCreate(data, client) {
1251
+ const api = client || getAPIInstance();
1252
+ const response = await api.ext_payments_payments.paymentsCreateCreate(data);
1253
+ try {
1254
+ return PaymentCreateResponseSchema.parse(response);
1255
+ } catch (error) {
1256
+ consola.error("\u274C Zod Validation Failed");
1257
+ consola.box(`createPaymentsPaymentsCreateCreate
1258
+ Path: /cfg/payments/payments/create/
1259
+ Method: POST`);
1260
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1261
+ consola.error("Validation Issues:");
1262
+ error.issues.forEach((issue, index) => {
1263
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1264
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1265
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1266
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1267
+ });
1268
+ }
1269
+ consola.error("Response data:", response);
1270
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1271
+ try {
1272
+ const event = new CustomEvent("zod-validation-error", {
1273
+ detail: {
1274
+ operation: "createPaymentsPaymentsCreateCreate",
1275
+ path: "/cfg/payments/payments/create/",
1276
+ method: "POST",
1277
+ error,
1278
+ response,
1279
+ timestamp: /* @__PURE__ */ new Date()
1280
+ },
1281
+ bubbles: true,
1282
+ cancelable: false
1283
+ });
1284
+ window.dispatchEvent(event);
1285
+ } catch (eventError) {
1286
+ consola.warn("Failed to dispatch validation error event:", eventError);
1287
+ }
1288
+ }
1289
+ throw error;
1290
+ }
1291
+ }
1292
+ async function getPaymentsTransactionsList(params, client) {
1293
+ const api = client || getAPIInstance();
1294
+ const response = await api.ext_payments_payments.transactionsList(params?.limit, params?.offset, params?.type);
1295
+ return response;
1296
+ }
1297
+ async function getPaymentsWithdrawalsList(params, client) {
1298
+ const api = client || getAPIInstance();
1299
+ const response = await api.ext_payments_payments.withdrawalsList(params?.page, params?.page_size);
1300
+ try {
1301
+ return PaginatedWithdrawalListListSchema.parse(response);
1302
+ } catch (error) {
1303
+ consola.error("\u274C Zod Validation Failed");
1304
+ consola.box(`getPaymentsWithdrawalsList
1305
+ Path: /cfg/payments/withdrawals/
1306
+ Method: GET`);
1307
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1308
+ consola.error("Validation Issues:");
1309
+ error.issues.forEach((issue, index) => {
1310
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1311
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1312
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1313
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1314
+ });
1315
+ }
1316
+ consola.error("Response data:", response);
1317
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1318
+ try {
1319
+ const event = new CustomEvent("zod-validation-error", {
1320
+ detail: {
1321
+ operation: "getPaymentsWithdrawalsList",
1322
+ path: "/cfg/payments/withdrawals/",
1323
+ method: "GET",
1324
+ error,
1325
+ response,
1326
+ timestamp: /* @__PURE__ */ new Date()
1327
+ },
1328
+ bubbles: true,
1329
+ cancelable: false
1330
+ });
1331
+ window.dispatchEvent(event);
1332
+ } catch (eventError) {
1333
+ consola.warn("Failed to dispatch validation error event:", eventError);
1334
+ }
1335
+ }
1336
+ throw error;
1337
+ }
1338
+ }
1339
+ async function getPaymentsWithdrawalsRetrieve(id, client) {
1340
+ const api = client || getAPIInstance();
1341
+ const response = await api.ext_payments_payments.withdrawalsRetrieve(id);
1342
+ try {
1343
+ return WithdrawalDetailSchema.parse(response);
1344
+ } catch (error) {
1345
+ consola.error("\u274C Zod Validation Failed");
1346
+ consola.box(`getPaymentsWithdrawalsRetrieve
1347
+ Path: /cfg/payments/withdrawals/{id}/
1348
+ Method: GET`);
1349
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1350
+ consola.error("Validation Issues:");
1351
+ error.issues.forEach((issue, index) => {
1352
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1353
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1354
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1355
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1356
+ });
1357
+ }
1358
+ consola.error("Response data:", response);
1359
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1360
+ try {
1361
+ const event = new CustomEvent("zod-validation-error", {
1362
+ detail: {
1363
+ operation: "getPaymentsWithdrawalsRetrieve",
1364
+ path: "/cfg/payments/withdrawals/{id}/",
1365
+ method: "GET",
1366
+ error,
1367
+ response,
1368
+ timestamp: /* @__PURE__ */ new Date()
1369
+ },
1370
+ bubbles: true,
1371
+ cancelable: false
1372
+ });
1373
+ window.dispatchEvent(event);
1374
+ } catch (eventError) {
1375
+ consola.warn("Failed to dispatch validation error event:", eventError);
1376
+ }
1377
+ }
1378
+ throw error;
1379
+ }
1380
+ }
1381
+ async function createPaymentsWithdrawalsCancelCreate(id, client) {
1382
+ const api = client || getAPIInstance();
1383
+ const response = await api.ext_payments_payments.withdrawalsCancelCreate(id);
1384
+ try {
1385
+ return WithdrawalCancelResponseSchema.parse(response);
1386
+ } catch (error) {
1387
+ consola.error("\u274C Zod Validation Failed");
1388
+ consola.box(`createPaymentsWithdrawalsCancelCreate
1389
+ Path: /cfg/payments/withdrawals/{id}/cancel/
1390
+ Method: POST`);
1391
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1392
+ consola.error("Validation Issues:");
1393
+ error.issues.forEach((issue, index) => {
1394
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1395
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1396
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1397
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1398
+ });
1399
+ }
1400
+ consola.error("Response data:", response);
1401
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1402
+ try {
1403
+ const event = new CustomEvent("zod-validation-error", {
1404
+ detail: {
1405
+ operation: "createPaymentsWithdrawalsCancelCreate",
1406
+ path: "/cfg/payments/withdrawals/{id}/cancel/",
1407
+ method: "POST",
1408
+ error,
1409
+ response,
1410
+ timestamp: /* @__PURE__ */ new Date()
1411
+ },
1412
+ bubbles: true,
1413
+ cancelable: false
1414
+ });
1415
+ window.dispatchEvent(event);
1416
+ } catch (eventError) {
1417
+ consola.warn("Failed to dispatch validation error event:", eventError);
1418
+ }
1419
+ }
1420
+ throw error;
1421
+ }
1422
+ }
1423
+ async function createPaymentsWithdrawalsCreateCreate(data, client) {
1424
+ const api = client || getAPIInstance();
1425
+ const response = await api.ext_payments_payments.withdrawalsCreateCreate(data);
1426
+ try {
1427
+ return WithdrawalCreateResponseSchema.parse(response);
1428
+ } catch (error) {
1429
+ consola.error("\u274C Zod Validation Failed");
1430
+ consola.box(`createPaymentsWithdrawalsCreateCreate
1431
+ Path: /cfg/payments/withdrawals/create/
1432
+ Method: POST`);
1433
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1434
+ consola.error("Validation Issues:");
1435
+ error.issues.forEach((issue, index) => {
1436
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1437
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1438
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1439
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1440
+ });
1441
+ }
1442
+ consola.error("Response data:", response);
1443
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1444
+ try {
1445
+ const event = new CustomEvent("zod-validation-error", {
1446
+ detail: {
1447
+ operation: "createPaymentsWithdrawalsCreateCreate",
1448
+ path: "/cfg/payments/withdrawals/create/",
1449
+ method: "POST",
1450
+ error,
1451
+ response,
1452
+ timestamp: /* @__PURE__ */ new Date()
1453
+ },
1454
+ bubbles: true,
1455
+ cancelable: false
1456
+ });
1457
+ window.dispatchEvent(event);
1458
+ } catch (eventError) {
1459
+ consola.warn("Failed to dispatch validation error event:", eventError);
1460
+ }
1461
+ }
1462
+ throw error;
1463
+ }
1464
+ }
1465
+
1466
+ // src/api/generated/ext_payments/index.ts
1467
+ var TOKEN_KEY = "auth_token";
1468
+ var REFRESH_TOKEN_KEY = "refresh_token";
1469
+ var API = class {
1470
+ baseUrl;
1471
+ _client;
1472
+ _token = null;
1473
+ _refreshToken = null;
1474
+ storage;
1475
+ options;
1476
+ // Sub-clients
1477
+ ext_payments_payments;
1478
+ constructor(baseUrl, options) {
1479
+ this.baseUrl = baseUrl;
1480
+ this.options = options;
1481
+ const logger = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
1482
+ this.storage = options?.storage || new LocalStorageAdapter(logger);
1483
+ this._loadTokensFromStorage();
1484
+ this._client = new APIClient(this.baseUrl, {
1485
+ retryConfig: this.options?.retryConfig,
1486
+ loggerConfig: this.options?.loggerConfig,
1487
+ tokenGetter: () => this.getToken()
1488
+ });
1489
+ this._injectAuthHeader();
1490
+ this.ext_payments_payments = this._client.ext_payments_payments;
1491
+ }
1492
+ _loadTokensFromStorage() {
1493
+ this._token = this.storage.getItem(TOKEN_KEY);
1494
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
1495
+ }
1496
+ _reinitClients() {
1497
+ this._client = new APIClient(this.baseUrl, {
1498
+ retryConfig: this.options?.retryConfig,
1499
+ loggerConfig: this.options?.loggerConfig,
1500
+ tokenGetter: () => this.getToken()
1501
+ });
1502
+ this._injectAuthHeader();
1503
+ this.ext_payments_payments = this._client.ext_payments_payments;
1504
+ }
1505
+ _injectAuthHeader() {
1506
+ const originalRequest = this._client.request.bind(this._client);
1507
+ this._client.request = async (method, path, options) => {
1508
+ const token = this.getToken();
1509
+ const mergedOptions = {
1510
+ ...options,
1511
+ headers: {
1512
+ ...options?.headers || {},
1513
+ ...token ? { "Authorization": `Bearer ${token}` } : {}
1514
+ }
1515
+ };
1516
+ return originalRequest(method, path, mergedOptions);
1517
+ };
1518
+ }
1519
+ /**
1520
+ * Get current JWT token
1521
+ */
1522
+ getToken() {
1523
+ return this.storage.getItem(TOKEN_KEY);
1524
+ }
1525
+ /**
1526
+ * Get current refresh token
1527
+ */
1528
+ getRefreshToken() {
1529
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
1530
+ }
1531
+ /**
1532
+ * Set JWT token and refresh token
1533
+ * @param token - JWT access token
1534
+ * @param refreshToken - JWT refresh token (optional)
1535
+ */
1536
+ setToken(token, refreshToken) {
1537
+ this._token = token;
1538
+ this.storage.setItem(TOKEN_KEY, token);
1539
+ if (refreshToken) {
1540
+ this._refreshToken = refreshToken;
1541
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
1542
+ }
1543
+ this._reinitClients();
1544
+ }
1545
+ /**
1546
+ * Clear all tokens
1547
+ */
1548
+ clearTokens() {
1549
+ this._token = null;
1550
+ this._refreshToken = null;
1551
+ this.storage.removeItem(TOKEN_KEY);
1552
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
1553
+ this._reinitClients();
1554
+ }
1555
+ /**
1556
+ * Check if user is authenticated
1557
+ */
1558
+ isAuthenticated() {
1559
+ return !!this.getToken();
1560
+ }
1561
+ /**
1562
+ * Update base URL and reinitialize clients
1563
+ * @param url - New base URL
1564
+ */
1565
+ setBaseUrl(url) {
1566
+ this.baseUrl = url;
1567
+ this._reinitClients();
1568
+ }
1569
+ /**
1570
+ * Get current base URL
1571
+ */
1572
+ getBaseUrl() {
1573
+ return this.baseUrl;
1574
+ }
1575
+ /**
1576
+ * Get OpenAPI schema path
1577
+ * @returns Path to the OpenAPI schema JSON file
1578
+ *
1579
+ * Note: The OpenAPI schema is available in the schema.json file.
1580
+ * You can load it dynamically using:
1581
+ * ```typescript
1582
+ * const schema = await fetch('./schema.json').then(r => r.json());
1583
+ * // or using fs in Node.js:
1584
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
1585
+ * ```
1586
+ */
1587
+ getSchemaPath() {
1588
+ return "./schema.json";
1589
+ }
1590
+ };
1591
+ function usePaymentsBalanceRetrieve(client) {
1592
+ return useSWR(
1593
+ "cfg-payments-balance",
1594
+ () => getPaymentsBalanceRetrieve(client)
1595
+ );
1596
+ }
1597
+ function usePaymentsCurrenciesList(client) {
1598
+ return useSWR(
1599
+ "cfg-payments-currencies",
1600
+ () => getPaymentsCurrenciesList(client)
1601
+ );
1602
+ }
1603
+ function usePaymentsCurrenciesEstimateRetrieve(code, params, client) {
1604
+ return useSWR(
1605
+ ["cfg-payments-currencies-estimate", code],
1606
+ () => getPaymentsCurrenciesEstimateRetrieve(code, params, client)
1607
+ );
1608
+ }
1609
+ function usePaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client) {
1610
+ return useSWR(
1611
+ ["cfg-payments-currencies-withdrawal-estimate", code],
1612
+ () => getPaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client)
1613
+ );
1614
+ }
1615
+ function usePaymentsPaymentsList(params, client) {
1616
+ return useSWR(
1617
+ params ? ["cfg-payments-payments", params] : "cfg-payments-payments",
1618
+ () => getPaymentsPaymentsList(params, client)
1619
+ );
1620
+ }
1621
+ function usePaymentsPaymentsRetrieve(id, client) {
1622
+ return useSWR(
1623
+ ["cfg-payments-payment", id],
1624
+ () => getPaymentsPaymentsRetrieve(id, client)
1625
+ );
1626
+ }
1627
+ function useCreatePaymentsPaymentsConfirmCreate() {
1628
+ const { mutate } = useSWRConfig();
1629
+ return async (id, client) => {
1630
+ const result = await createPaymentsPaymentsConfirmCreate(id, client);
1631
+ mutate("cfg-payments-payments-confirm");
1632
+ return result;
1633
+ };
1634
+ }
1635
+ function usePaymentsPaymentsStatusRetrieve(id, client) {
1636
+ return useSWR(
1637
+ ["cfg-payments-payments-statu", id],
1638
+ () => getPaymentsPaymentsStatusRetrieve(id, client)
1639
+ );
1640
+ }
1641
+ function useCreatePaymentsPaymentsCreateCreate() {
1642
+ const { mutate } = useSWRConfig();
1643
+ return async (data, client) => {
1644
+ const result = await createPaymentsPaymentsCreateCreate(data, client);
1645
+ mutate("cfg-payments-payments");
1646
+ return result;
1647
+ };
1648
+ }
1649
+ function usePaymentsTransactionsList(params, client) {
1650
+ return useSWR(
1651
+ params ? ["cfg-payments-transactions", params] : "cfg-payments-transactions",
1652
+ () => getPaymentsTransactionsList(params, client)
1653
+ );
1654
+ }
1655
+ function usePaymentsWithdrawalsList(params, client) {
1656
+ return useSWR(
1657
+ params ? ["cfg-payments-withdrawals", params] : "cfg-payments-withdrawals",
1658
+ () => getPaymentsWithdrawalsList(params, client)
1659
+ );
1660
+ }
1661
+ function usePaymentsWithdrawalsRetrieve(id, client) {
1662
+ return useSWR(
1663
+ ["cfg-payments-withdrawal", id],
1664
+ () => getPaymentsWithdrawalsRetrieve(id, client)
1665
+ );
1666
+ }
1667
+ function useCreatePaymentsWithdrawalsCancelCreate() {
1668
+ const { mutate } = useSWRConfig();
1669
+ return async (id, client) => {
1670
+ const result = await createPaymentsWithdrawalsCancelCreate(id, client);
1671
+ mutate("cfg-payments-withdrawals-cancel");
1672
+ return result;
1673
+ };
1674
+ }
1675
+ function useCreatePaymentsWithdrawalsCreateCreate() {
1676
+ const { mutate } = useSWRConfig();
1677
+ return async (data, client) => {
1678
+ const result = await createPaymentsWithdrawalsCreateCreate(data, client);
1679
+ mutate("cfg-payments-withdrawals");
1680
+ return result;
1681
+ };
1682
+ }
1683
+
1684
+ // src/api/index.ts
1685
+ initializeExtensionAPI(configureAPI);
1686
+ var apiPayments = createExtensionAPI(API);
1687
+
1688
+ export { API, BalanceSchema, CurrencySchema, PaginatedPaymentListListSchema, PaginatedWithdrawalListListSchema, PaymentCreateRequestSchema, PaymentCreateResponseSchema, PaymentDetailSchema, PaymentListSchema, TransactionSchema, WithdrawalCancelResponseSchema, WithdrawalCreateRequestSchema, WithdrawalCreateResponseSchema, WithdrawalDetailSchema, WithdrawalListSchema, apiPayments, createPaymentsPaymentsConfirmCreate, createPaymentsPaymentsCreateCreate, createPaymentsWithdrawalsCancelCreate, createPaymentsWithdrawalsCreateCreate, getPaymentsBalanceRetrieve, getPaymentsCurrenciesEstimateRetrieve, getPaymentsCurrenciesList, getPaymentsCurrenciesWithdrawalEstimateRetrieve, getPaymentsPaymentsList, getPaymentsPaymentsRetrieve, getPaymentsPaymentsStatusRetrieve, getPaymentsTransactionsList, getPaymentsWithdrawalsList, getPaymentsWithdrawalsRetrieve, useCreatePaymentsPaymentsConfirmCreate, useCreatePaymentsPaymentsCreateCreate, useCreatePaymentsWithdrawalsCancelCreate, useCreatePaymentsWithdrawalsCreateCreate, usePaymentsBalanceRetrieve, usePaymentsCurrenciesEstimateRetrieve, usePaymentsCurrenciesList, usePaymentsCurrenciesWithdrawalEstimateRetrieve, usePaymentsPaymentsList, usePaymentsPaymentsRetrieve, usePaymentsPaymentsStatusRetrieve, usePaymentsTransactionsList, usePaymentsWithdrawalsList, usePaymentsWithdrawalsRetrieve };