@djangocfg/api 2.1.87 → 2.1.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/auth-server.cjs +1963 -4
  2. package/dist/auth-server.cjs.map +1 -1
  3. package/dist/auth-server.d.cts +35 -1
  4. package/dist/auth-server.d.ts +35 -1
  5. package/dist/auth-server.mjs +1953 -4
  6. package/dist/auth-server.mjs.map +1 -1
  7. package/dist/auth.cjs +692 -497
  8. package/dist/auth.cjs.map +1 -1
  9. package/dist/auth.d.cts +18 -2
  10. package/dist/auth.d.ts +18 -2
  11. package/dist/auth.mjs +655 -460
  12. package/dist/auth.mjs.map +1 -1
  13. package/dist/clients.cjs +460 -383
  14. package/dist/clients.cjs.map +1 -1
  15. package/dist/clients.d.cts +26 -6
  16. package/dist/clients.d.ts +26 -6
  17. package/dist/clients.mjs +460 -383
  18. package/dist/clients.mjs.map +1 -1
  19. package/dist/hooks.cjs +130 -105
  20. package/dist/hooks.cjs.map +1 -1
  21. package/dist/hooks.d.cts +24 -4
  22. package/dist/hooks.d.ts +24 -4
  23. package/dist/hooks.mjs +130 -105
  24. package/dist/hooks.mjs.map +1 -1
  25. package/dist/index.cjs +373 -311
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +54 -8
  28. package/dist/index.d.ts +54 -8
  29. package/dist/index.mjs +373 -311
  30. package/dist/index.mjs.map +1 -1
  31. package/package.json +3 -3
  32. package/src/auth/context/AccountsContext.tsx +3 -3
  33. package/src/auth/context/AuthContext.tsx +56 -10
  34. package/src/auth/hooks/index.ts +3 -0
  35. package/src/auth/hooks/useProfileCache.ts +1 -1
  36. package/src/auth/hooks/useTokenRefresh.ts +161 -0
  37. package/src/auth/middlewares/index.ts +8 -1
  38. package/src/auth/middlewares/tokenRefresh.ts +158 -0
  39. package/src/generated/cfg_accounts/CLAUDE.md +2 -9
  40. package/src/generated/cfg_accounts/_utils/fetchers/accounts__user_profile.ts +2 -1
  41. package/src/generated/cfg_accounts/_utils/hooks/accounts__user_profile.ts +2 -1
  42. package/src/generated/cfg_accounts/_utils/schemas/CfgAccountsProfileAvatarCreateRequest.schema.ts +15 -0
  43. package/src/generated/cfg_accounts/_utils/schemas/index.ts +1 -0
  44. package/src/generated/cfg_accounts/accounts/models.ts +0 -1
  45. package/src/generated/cfg_accounts/accounts__user_profile/client.ts +4 -2
  46. package/src/generated/cfg_accounts/accounts__user_profile/models.ts +9 -1
  47. package/src/generated/cfg_accounts/client.ts +18 -0
  48. package/src/generated/cfg_accounts/index.ts +3 -1
  49. package/src/generated/cfg_accounts/schema.json +2 -2
  50. package/src/generated/cfg_centrifugo/CLAUDE.md +1 -8
  51. package/src/generated/cfg_centrifugo/client.ts +18 -0
  52. package/src/generated/cfg_centrifugo/index.ts +3 -1
  53. package/src/generated/cfg_totp/CLAUDE.md +1 -8
  54. package/src/generated/cfg_totp/client.ts +18 -0
  55. package/src/generated/cfg_totp/index.ts +3 -1
  56. package/src/generated/cfg_totp/totp/models.ts +2 -0
  57. package/src/generated/cfg_webpush/CLAUDE.md +1 -8
  58. package/src/generated/cfg_webpush/client.ts +18 -0
  59. package/src/generated/cfg_webpush/index.ts +3 -1
@@ -1,6 +1,8 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
7
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
8
  var __export = (target, all) => {
@@ -15,13 +17,26 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/auth/server.ts
21
31
  var server_exports = {};
22
32
  __export(server_exports, {
33
+ createAutoRefreshFetch: () => createAutoRefreshFetch,
34
+ isAuthenticationError: () => isAuthenticationError,
35
+ isTokenExpiringSoon: () => isTokenExpiringSoon,
23
36
  proxyMiddleware: () => proxyMiddleware,
24
- proxyMiddlewareConfig: () => proxyMiddlewareConfig
37
+ proxyMiddlewareConfig: () => proxyMiddlewareConfig,
38
+ refreshAccessToken: () => refreshAccessToken,
39
+ refreshIfExpiringSoon: () => refreshIfExpiringSoon
25
40
  });
26
41
  module.exports = __toCommonJS(server_exports);
27
42
 
@@ -29,13 +44,13 @@ module.exports = __toCommonJS(server_exports);
29
44
  var import_server = require("next/server");
30
45
  function proxyMiddleware(request) {
31
46
  const { pathname, search } = request.nextUrl;
32
- const apiUrl = process.env.NEXT_PUBLIC_API_URL;
47
+ const apiUrl2 = process.env.NEXT_PUBLIC_API_URL;
33
48
  if (pathname.startsWith("/media/")) {
34
- const targetUrl = `${apiUrl}${pathname}${search}`;
49
+ const targetUrl = `${apiUrl2}${pathname}${search}`;
35
50
  return import_server.NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
36
51
  }
37
52
  if (pathname.startsWith("/api/")) {
38
- const targetUrl = `${apiUrl}${pathname}${search}`;
53
+ const targetUrl = `${apiUrl2}${pathname}${search}`;
39
54
  return import_server.NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
40
55
  }
41
56
  return import_server.NextResponse.next();
@@ -44,4 +59,1948 @@ __name(proxyMiddleware, "proxyMiddleware");
44
59
  var proxyMiddlewareConfig = {
45
60
  matcher: ["/media/:path*", "/api/:path*"]
46
61
  };
62
+
63
+ // src/generated/cfg_accounts/accounts__auth/client.ts
64
+ var Auth = class {
65
+ static {
66
+ __name(this, "Auth");
67
+ }
68
+ constructor(client) {
69
+ this.client = client;
70
+ }
71
+ /**
72
+ * Refresh JWT token.
73
+ */
74
+ async accountsTokenRefreshCreate(data) {
75
+ const response = await this.client.request("POST", "/cfg/accounts/token/refresh/", { body: data });
76
+ return response;
77
+ }
78
+ };
79
+
80
+ // src/generated/cfg_accounts/accounts__oauth/client.ts
81
+ var Oauth = class {
82
+ static {
83
+ __name(this, "Oauth");
84
+ }
85
+ constructor(client) {
86
+ this.client = client;
87
+ }
88
+ /**
89
+ * List OAuth connections
90
+ *
91
+ * Get all OAuth connections for the current user.
92
+ */
93
+ async accountsOauthConnectionsList() {
94
+ const response = await this.client.request("GET", "/cfg/accounts/oauth/connections/");
95
+ return response;
96
+ }
97
+ /**
98
+ * Disconnect OAuth provider
99
+ *
100
+ * Remove OAuth connection for the specified provider.
101
+ */
102
+ async accountsOauthDisconnectCreate(data) {
103
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/disconnect/", { body: data });
104
+ return response;
105
+ }
106
+ /**
107
+ * Start GitHub OAuth
108
+ *
109
+ * Generate GitHub OAuth authorization URL. Redirect user to this URL to
110
+ * start authentication.
111
+ */
112
+ async accountsOauthGithubAuthorizeCreate(data) {
113
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/github/authorize/", { body: data });
114
+ return response;
115
+ }
116
+ /**
117
+ * Complete GitHub OAuth
118
+ *
119
+ * Exchange authorization code for JWT tokens. Call this after GitHub
120
+ * redirects back with code.
121
+ */
122
+ async accountsOauthGithubCallbackCreate(data) {
123
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/github/callback/", { body: data });
124
+ return response;
125
+ }
126
+ /**
127
+ * List OAuth providers
128
+ *
129
+ * Get list of available OAuth providers for authentication.
130
+ */
131
+ async accountsOauthProvidersRetrieve() {
132
+ const response = await this.client.request("GET", "/cfg/accounts/oauth/providers/");
133
+ return response;
134
+ }
135
+ };
136
+
137
+ // src/generated/cfg_accounts/accounts__user_profile/client.ts
138
+ var UserProfile = class {
139
+ static {
140
+ __name(this, "UserProfile");
141
+ }
142
+ constructor(client) {
143
+ this.client = client;
144
+ }
145
+ /**
146
+ * Get current user profile
147
+ *
148
+ * Retrieve the current authenticated user's profile information.
149
+ */
150
+ async accountsProfileRetrieve() {
151
+ const response = await this.client.request("GET", "/cfg/accounts/profile/");
152
+ return response;
153
+ }
154
+ /**
155
+ * Upload user avatar
156
+ *
157
+ * Upload avatar image for the current authenticated user. Accepts
158
+ * multipart/form-data with 'avatar' field.
159
+ */
160
+ async accountsProfileAvatarCreate(data) {
161
+ const formData = new FormData();
162
+ formData.append("avatar", data.avatar);
163
+ const response = await this.client.request("POST", "/cfg/accounts/profile/avatar/", { formData });
164
+ return response;
165
+ }
166
+ /**
167
+ * Partial update user profile
168
+ *
169
+ * Partially update the current authenticated user's profile information.
170
+ * Supports avatar upload.
171
+ */
172
+ async accountsProfilePartialUpdate(data) {
173
+ const response = await this.client.request("PUT", "/cfg/accounts/profile/partial/", { body: data });
174
+ return response;
175
+ }
176
+ /**
177
+ * Partial update user profile
178
+ *
179
+ * Partially update the current authenticated user's profile information.
180
+ * Supports avatar upload.
181
+ */
182
+ async accountsProfilePartialPartialUpdate(data) {
183
+ const response = await this.client.request("PATCH", "/cfg/accounts/profile/partial/", { body: data });
184
+ return response;
185
+ }
186
+ /**
187
+ * Update user profile
188
+ *
189
+ * Update the current authenticated user's profile information.
190
+ */
191
+ async accountsProfileUpdateUpdate(data) {
192
+ const response = await this.client.request("PUT", "/cfg/accounts/profile/update/", { body: data });
193
+ return response;
194
+ }
195
+ /**
196
+ * Update user profile
197
+ *
198
+ * Update the current authenticated user's profile information.
199
+ */
200
+ async accountsProfileUpdatePartialUpdate(data) {
201
+ const response = await this.client.request("PATCH", "/cfg/accounts/profile/update/", { body: data });
202
+ return response;
203
+ }
204
+ };
205
+
206
+ // src/generated/cfg_accounts/accounts/client.ts
207
+ var Accounts = class {
208
+ static {
209
+ __name(this, "Accounts");
210
+ }
211
+ constructor(client) {
212
+ this.client = client;
213
+ }
214
+ /**
215
+ * Request OTP code to email or phone.
216
+ */
217
+ async otpRequestCreate(data) {
218
+ const response = await this.client.request("POST", "/cfg/accounts/otp/request/", { body: data });
219
+ return response;
220
+ }
221
+ /**
222
+ * Verify OTP code and return JWT tokens or 2FA session. If user has 2FA
223
+ * enabled: - Returns requires_2fa=True with session_id - Client must
224
+ * complete 2FA verification at /cfg/totp/verify/ If user has no 2FA: -
225
+ * Returns JWT tokens and user data directly
226
+ */
227
+ async otpVerifyCreate(data) {
228
+ const response = await this.client.request("POST", "/cfg/accounts/otp/verify/", { body: data });
229
+ return response;
230
+ }
231
+ };
232
+
233
+ // src/generated/cfg_accounts/http.ts
234
+ var FetchAdapter = class {
235
+ static {
236
+ __name(this, "FetchAdapter");
237
+ }
238
+ async request(request) {
239
+ const { method, url, headers, body, params, formData, binaryBody } = request;
240
+ let finalUrl = url;
241
+ if (params) {
242
+ const searchParams = new URLSearchParams();
243
+ Object.entries(params).forEach(([key, value]) => {
244
+ if (value !== null && value !== void 0) {
245
+ searchParams.append(key, String(value));
246
+ }
247
+ });
248
+ const queryString = searchParams.toString();
249
+ if (queryString) {
250
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
251
+ }
252
+ }
253
+ const finalHeaders = { ...headers };
254
+ let requestBody;
255
+ if (formData) {
256
+ requestBody = formData;
257
+ } else if (binaryBody) {
258
+ finalHeaders["Content-Type"] = "application/octet-stream";
259
+ requestBody = binaryBody;
260
+ } else if (body) {
261
+ finalHeaders["Content-Type"] = "application/json";
262
+ requestBody = JSON.stringify(body);
263
+ }
264
+ const response = await fetch(finalUrl, {
265
+ method,
266
+ headers: finalHeaders,
267
+ body: requestBody,
268
+ credentials: "include"
269
+ // Include Django session cookies
270
+ });
271
+ let data = null;
272
+ const contentType = response.headers.get("content-type");
273
+ if (response.status !== 204 && contentType?.includes("application/json")) {
274
+ data = await response.json();
275
+ } else if (response.status !== 204) {
276
+ data = await response.text();
277
+ }
278
+ const responseHeaders = {};
279
+ response.headers.forEach((value, key) => {
280
+ responseHeaders[key] = value;
281
+ });
282
+ return {
283
+ data,
284
+ status: response.status,
285
+ statusText: response.statusText,
286
+ headers: responseHeaders
287
+ };
288
+ }
289
+ };
290
+
291
+ // src/generated/cfg_accounts/errors.ts
292
+ var APIError = class extends Error {
293
+ constructor(statusCode, statusText, response, url, message) {
294
+ super(message || `HTTP ${statusCode}: ${statusText}`);
295
+ this.statusCode = statusCode;
296
+ this.statusText = statusText;
297
+ this.response = response;
298
+ this.url = url;
299
+ this.name = "APIError";
300
+ }
301
+ static {
302
+ __name(this, "APIError");
303
+ }
304
+ /**
305
+ * Get error details from response.
306
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
307
+ */
308
+ get details() {
309
+ if (typeof this.response === "object" && this.response !== null) {
310
+ return this.response;
311
+ }
312
+ return null;
313
+ }
314
+ /**
315
+ * Get field-specific validation errors from DRF.
316
+ * Returns: { "field_name": ["error1", "error2"], ... }
317
+ */
318
+ get fieldErrors() {
319
+ const details = this.details;
320
+ if (!details) return null;
321
+ const fieldErrors = {};
322
+ for (const [key, value] of Object.entries(details)) {
323
+ if (Array.isArray(value)) {
324
+ fieldErrors[key] = value;
325
+ }
326
+ }
327
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
328
+ }
329
+ /**
330
+ * Get single error message from DRF.
331
+ * Checks for "detail", "message", or first field error.
332
+ */
333
+ get errorMessage() {
334
+ const details = this.details;
335
+ if (!details) return this.message;
336
+ if (details.detail) {
337
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
338
+ }
339
+ if (details.message) {
340
+ return String(details.message);
341
+ }
342
+ const fieldErrors = this.fieldErrors;
343
+ if (fieldErrors) {
344
+ const firstField = Object.keys(fieldErrors)[0];
345
+ if (firstField) {
346
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
347
+ }
348
+ }
349
+ return this.message;
350
+ }
351
+ // Helper methods for common HTTP status codes
352
+ get isValidationError() {
353
+ return this.statusCode === 400;
354
+ }
355
+ get isAuthError() {
356
+ return this.statusCode === 401;
357
+ }
358
+ get isPermissionError() {
359
+ return this.statusCode === 403;
360
+ }
361
+ get isNotFoundError() {
362
+ return this.statusCode === 404;
363
+ }
364
+ get isServerError() {
365
+ return this.statusCode >= 500 && this.statusCode < 600;
366
+ }
367
+ };
368
+ var NetworkError = class extends Error {
369
+ constructor(message, url, originalError) {
370
+ super(message);
371
+ this.url = url;
372
+ this.originalError = originalError;
373
+ this.name = "NetworkError";
374
+ }
375
+ static {
376
+ __name(this, "NetworkError");
377
+ }
378
+ };
379
+
380
+ // src/generated/cfg_accounts/logger.ts
381
+ var import_consola = require("consola");
382
+ var DEFAULT_CONFIG = {
383
+ enabled: process.env.NODE_ENV !== "production",
384
+ logRequests: true,
385
+ logResponses: true,
386
+ logErrors: true,
387
+ logBodies: true,
388
+ logHeaders: false
389
+ };
390
+ var SENSITIVE_HEADERS = [
391
+ "authorization",
392
+ "cookie",
393
+ "set-cookie",
394
+ "x-api-key",
395
+ "x-csrf-token"
396
+ ];
397
+ var APILogger = class {
398
+ static {
399
+ __name(this, "APILogger");
400
+ }
401
+ constructor(config = {}) {
402
+ this.config = { ...DEFAULT_CONFIG, ...config };
403
+ this.consola = config.consola || (0, import_consola.createConsola)({
404
+ level: this.config.enabled ? 4 : 0
405
+ });
406
+ }
407
+ /**
408
+ * Enable logging
409
+ */
410
+ enable() {
411
+ this.config.enabled = true;
412
+ }
413
+ /**
414
+ * Disable logging
415
+ */
416
+ disable() {
417
+ this.config.enabled = false;
418
+ }
419
+ /**
420
+ * Update configuration
421
+ */
422
+ setConfig(config) {
423
+ this.config = { ...this.config, ...config };
424
+ }
425
+ /**
426
+ * Filter sensitive headers
427
+ */
428
+ filterHeaders(headers) {
429
+ if (!headers) return {};
430
+ const filtered = {};
431
+ Object.keys(headers).forEach((key) => {
432
+ const lowerKey = key.toLowerCase();
433
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
434
+ filtered[key] = "***";
435
+ } else {
436
+ filtered[key] = headers[key] || "";
437
+ }
438
+ });
439
+ return filtered;
440
+ }
441
+ /**
442
+ * Log request
443
+ */
444
+ logRequest(request) {
445
+ if (!this.config.enabled || !this.config.logRequests) return;
446
+ const { method, url, headers, body } = request;
447
+ this.consola.start(`${method} ${url}`);
448
+ if (this.config.logHeaders && headers) {
449
+ this.consola.debug("Headers:", this.filterHeaders(headers));
450
+ }
451
+ if (this.config.logBodies && body) {
452
+ this.consola.debug("Body:", body);
453
+ }
454
+ }
455
+ /**
456
+ * Log response
457
+ */
458
+ logResponse(request, response) {
459
+ if (!this.config.enabled || !this.config.logResponses) return;
460
+ const { method, url } = request;
461
+ const { status, statusText, data, duration } = response;
462
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
463
+ this.consola.success(
464
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
465
+ );
466
+ if (this.config.logBodies && data) {
467
+ this.consola.debug("Response:", data);
468
+ }
469
+ }
470
+ /**
471
+ * Log error
472
+ */
473
+ logError(request, error) {
474
+ if (!this.config.enabled || !this.config.logErrors) return;
475
+ const { method, url } = request;
476
+ const { message, statusCode, fieldErrors, duration } = error;
477
+ this.consola.error(
478
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
479
+ );
480
+ this.consola.error("Message:", message);
481
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
482
+ this.consola.error("Field Errors:");
483
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
484
+ errors.forEach((err) => {
485
+ this.consola.error(` \u2022 ${field}: ${err}`);
486
+ });
487
+ });
488
+ }
489
+ }
490
+ /**
491
+ * Log general info
492
+ */
493
+ info(message, ...args) {
494
+ if (!this.config.enabled) return;
495
+ this.consola.info(message, ...args);
496
+ }
497
+ /**
498
+ * Log warning
499
+ */
500
+ warn(message, ...args) {
501
+ if (!this.config.enabled) return;
502
+ this.consola.warn(message, ...args);
503
+ }
504
+ /**
505
+ * Log error
506
+ */
507
+ error(message, ...args) {
508
+ if (!this.config.enabled) return;
509
+ this.consola.error(message, ...args);
510
+ }
511
+ /**
512
+ * Log debug
513
+ */
514
+ debug(message, ...args) {
515
+ if (!this.config.enabled) return;
516
+ this.consola.debug(message, ...args);
517
+ }
518
+ /**
519
+ * Log success
520
+ */
521
+ success(message, ...args) {
522
+ if (!this.config.enabled) return;
523
+ this.consola.success(message, ...args);
524
+ }
525
+ /**
526
+ * Create a sub-logger with prefix
527
+ */
528
+ withTag(tag) {
529
+ return this.consola.withTag(tag);
530
+ }
531
+ };
532
+ var defaultLogger = new APILogger();
533
+
534
+ // src/generated/cfg_accounts/retry.ts
535
+ var import_p_retry = __toESM(require("p-retry"), 1);
536
+ var DEFAULT_RETRY_CONFIG = {
537
+ retries: 3,
538
+ factor: 2,
539
+ minTimeout: 1e3,
540
+ maxTimeout: 6e4,
541
+ randomize: true,
542
+ onFailedAttempt: /* @__PURE__ */ __name(() => {
543
+ }, "onFailedAttempt")
544
+ };
545
+ function shouldRetry(error) {
546
+ if (error instanceof NetworkError) {
547
+ return true;
548
+ }
549
+ if (error instanceof APIError) {
550
+ const status = error.statusCode;
551
+ if (status >= 500 && status < 600) {
552
+ return true;
553
+ }
554
+ if (status === 429) {
555
+ return true;
556
+ }
557
+ return false;
558
+ }
559
+ return true;
560
+ }
561
+ __name(shouldRetry, "shouldRetry");
562
+ async function withRetry(fn, config) {
563
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
564
+ return (0, import_p_retry.default)(
565
+ async () => {
566
+ try {
567
+ return await fn();
568
+ } catch (error) {
569
+ if (!shouldRetry(error)) {
570
+ throw new import_p_retry.AbortError(error);
571
+ }
572
+ throw error;
573
+ }
574
+ },
575
+ {
576
+ retries: finalConfig.retries,
577
+ factor: finalConfig.factor,
578
+ minTimeout: finalConfig.minTimeout,
579
+ maxTimeout: finalConfig.maxTimeout,
580
+ randomize: finalConfig.randomize,
581
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
582
+ const pRetryError = error;
583
+ finalConfig.onFailedAttempt({
584
+ error: pRetryError,
585
+ attemptNumber: pRetryError.attemptNumber,
586
+ retriesLeft: pRetryError.retriesLeft
587
+ });
588
+ } : void 0
589
+ }
590
+ );
591
+ }
592
+ __name(withRetry, "withRetry");
593
+
594
+ // src/generated/cfg_accounts/client.ts
595
+ var APIClient = class {
596
+ constructor(baseUrl, options) {
597
+ this.logger = null;
598
+ this.retryConfig = null;
599
+ this.tokenGetter = null;
600
+ this.baseUrl = baseUrl.replace(/\/$/, "");
601
+ this.httpClient = options?.httpClient || new FetchAdapter();
602
+ this.tokenGetter = options?.tokenGetter || null;
603
+ if (options?.loggerConfig !== void 0) {
604
+ this.logger = new APILogger(options.loggerConfig);
605
+ }
606
+ if (options?.retryConfig !== void 0) {
607
+ this.retryConfig = options.retryConfig;
608
+ }
609
+ this.auth = new Auth(this);
610
+ this.oauth = new Oauth(this);
611
+ this.user_profile = new UserProfile(this);
612
+ this.accounts = new Accounts(this);
613
+ }
614
+ static {
615
+ __name(this, "APIClient");
616
+ }
617
+ /**
618
+ * Get CSRF token from cookies (for SessionAuthentication).
619
+ *
620
+ * Returns null if cookie doesn't exist (JWT-only auth).
621
+ */
622
+ getCsrfToken() {
623
+ const name = "csrftoken";
624
+ const value = `; ${document.cookie}`;
625
+ const parts = value.split(`; ${name}=`);
626
+ if (parts.length === 2) {
627
+ return parts.pop()?.split(";").shift() || null;
628
+ }
629
+ return null;
630
+ }
631
+ /**
632
+ * Get the base URL for building streaming/download URLs.
633
+ */
634
+ getBaseUrl() {
635
+ return this.baseUrl;
636
+ }
637
+ /**
638
+ * Get JWT token for URL authentication (used in streaming endpoints).
639
+ * Returns null if no token getter is configured or no token is available.
640
+ */
641
+ getToken() {
642
+ return this.tokenGetter ? this.tokenGetter() : null;
643
+ }
644
+ /**
645
+ * Make HTTP request with Django CSRF and session handling.
646
+ * Automatically retries on network errors and 5xx server errors.
647
+ */
648
+ async request(method, path, options) {
649
+ if (this.retryConfig) {
650
+ return withRetry(() => this._makeRequest(method, path, options), {
651
+ ...this.retryConfig,
652
+ onFailedAttempt: /* @__PURE__ */ __name((info) => {
653
+ if (this.logger) {
654
+ this.logger.warn(
655
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
656
+ );
657
+ }
658
+ this.retryConfig?.onFailedAttempt?.(info);
659
+ }, "onFailedAttempt")
660
+ });
661
+ }
662
+ return this._makeRequest(method, path, options);
663
+ }
664
+ /**
665
+ * Internal request method (without retry wrapper).
666
+ * Used by request() method with optional retry logic.
667
+ */
668
+ async _makeRequest(method, path, options) {
669
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
670
+ const startTime = Date.now();
671
+ const headers = {
672
+ ...options?.headers || {}
673
+ };
674
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
675
+ headers["Content-Type"] = "application/json";
676
+ }
677
+ if (this.logger) {
678
+ this.logger.logRequest({
679
+ method,
680
+ url,
681
+ headers,
682
+ body: options?.formData || options?.body,
683
+ timestamp: startTime
684
+ });
685
+ }
686
+ try {
687
+ const response = await this.httpClient.request({
688
+ method,
689
+ url,
690
+ headers,
691
+ params: options?.params,
692
+ body: options?.body,
693
+ formData: options?.formData,
694
+ binaryBody: options?.binaryBody
695
+ });
696
+ const duration = Date.now() - startTime;
697
+ if (response.status >= 400) {
698
+ const error = new APIError(
699
+ response.status,
700
+ response.statusText,
701
+ response.data,
702
+ url
703
+ );
704
+ if (this.logger) {
705
+ this.logger.logError(
706
+ {
707
+ method,
708
+ url,
709
+ headers,
710
+ body: options?.formData || options?.body,
711
+ timestamp: startTime
712
+ },
713
+ {
714
+ message: error.message,
715
+ statusCode: response.status,
716
+ duration,
717
+ timestamp: Date.now()
718
+ }
719
+ );
720
+ }
721
+ throw error;
722
+ }
723
+ if (this.logger) {
724
+ this.logger.logResponse(
725
+ {
726
+ method,
727
+ url,
728
+ headers,
729
+ body: options?.formData || options?.body,
730
+ timestamp: startTime
731
+ },
732
+ {
733
+ status: response.status,
734
+ statusText: response.statusText,
735
+ data: response.data,
736
+ duration,
737
+ timestamp: Date.now()
738
+ }
739
+ );
740
+ }
741
+ return response.data;
742
+ } catch (error) {
743
+ const duration = Date.now() - startTime;
744
+ if (error instanceof APIError) {
745
+ throw error;
746
+ }
747
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
748
+ if (this.logger) {
749
+ if (isCORSError) {
750
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
751
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
752
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
753
+ } else {
754
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
755
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
756
+ }
757
+ }
758
+ if (typeof window !== "undefined") {
759
+ try {
760
+ if (isCORSError) {
761
+ window.dispatchEvent(new CustomEvent("cors-error", {
762
+ detail: {
763
+ url,
764
+ method,
765
+ error: error instanceof Error ? error.message : String(error),
766
+ timestamp: /* @__PURE__ */ new Date()
767
+ },
768
+ bubbles: true,
769
+ cancelable: false
770
+ }));
771
+ } else {
772
+ window.dispatchEvent(new CustomEvent("network-error", {
773
+ detail: {
774
+ url,
775
+ method,
776
+ error: error instanceof Error ? error.message : String(error),
777
+ timestamp: /* @__PURE__ */ new Date()
778
+ },
779
+ bubbles: true,
780
+ cancelable: false
781
+ }));
782
+ }
783
+ } catch (eventError) {
784
+ }
785
+ }
786
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
787
+ if (this.logger) {
788
+ this.logger.logError(
789
+ {
790
+ method,
791
+ url,
792
+ headers,
793
+ body: options?.formData || options?.body,
794
+ timestamp: startTime
795
+ },
796
+ {
797
+ message: networkError.message,
798
+ duration,
799
+ timestamp: Date.now()
800
+ }
801
+ );
802
+ }
803
+ throw networkError;
804
+ }
805
+ }
806
+ };
807
+
808
+ // src/generated/cfg_accounts/storage.ts
809
+ var LocalStorageAdapter = class {
810
+ static {
811
+ __name(this, "LocalStorageAdapter");
812
+ }
813
+ constructor(logger2) {
814
+ this.logger = logger2;
815
+ }
816
+ getItem(key) {
817
+ try {
818
+ if (typeof window !== "undefined" && window.localStorage) {
819
+ const value = localStorage.getItem(key);
820
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
821
+ return value;
822
+ }
823
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
824
+ } catch (error) {
825
+ this.logger?.error("LocalStorage.getItem failed:", error);
826
+ }
827
+ return null;
828
+ }
829
+ setItem(key, value) {
830
+ try {
831
+ if (typeof window !== "undefined" && window.localStorage) {
832
+ localStorage.setItem(key, value);
833
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
834
+ } else {
835
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
836
+ }
837
+ } catch (error) {
838
+ this.logger?.error("LocalStorage.setItem failed:", error);
839
+ }
840
+ }
841
+ removeItem(key) {
842
+ try {
843
+ if (typeof window !== "undefined" && window.localStorage) {
844
+ localStorage.removeItem(key);
845
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
846
+ } else {
847
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
848
+ }
849
+ } catch (error) {
850
+ this.logger?.error("LocalStorage.removeItem failed:", error);
851
+ }
852
+ }
853
+ };
854
+
855
+ // src/generated/cfg_accounts/enums.ts
856
+ var OAuthConnectionProvider = /* @__PURE__ */ ((OAuthConnectionProvider2) => {
857
+ OAuthConnectionProvider2["GITHUB"] = "github";
858
+ return OAuthConnectionProvider2;
859
+ })(OAuthConnectionProvider || {});
860
+ var OAuthDisconnectRequestRequestProvider = /* @__PURE__ */ ((OAuthDisconnectRequestRequestProvider2) => {
861
+ OAuthDisconnectRequestRequestProvider2["GITHUB"] = "github";
862
+ return OAuthDisconnectRequestRequestProvider2;
863
+ })(OAuthDisconnectRequestRequestProvider || {});
864
+ var OTPRequestRequestChannel = /* @__PURE__ */ ((OTPRequestRequestChannel2) => {
865
+ OTPRequestRequestChannel2["EMAIL"] = "email";
866
+ OTPRequestRequestChannel2["PHONE"] = "phone";
867
+ return OTPRequestRequestChannel2;
868
+ })(OTPRequestRequestChannel || {});
869
+ var OTPVerifyRequestChannel = /* @__PURE__ */ ((OTPVerifyRequestChannel2) => {
870
+ OTPVerifyRequestChannel2["EMAIL"] = "email";
871
+ OTPVerifyRequestChannel2["PHONE"] = "phone";
872
+ return OTPVerifyRequestChannel2;
873
+ })(OTPVerifyRequestChannel || {});
874
+
875
+ // src/generated/cfg_accounts/_utils/schemas/CentrifugoToken.schema.ts
876
+ var import_zod = require("zod");
877
+ var CentrifugoTokenSchema = import_zod.z.object({
878
+ token: import_zod.z.string(),
879
+ centrifugo_url: import_zod.z.union([import_zod.z.url(), import_zod.z.literal("")]),
880
+ expires_at: import_zod.z.iso.datetime(),
881
+ channels: import_zod.z.array(import_zod.z.string())
882
+ });
883
+
884
+ // src/generated/cfg_accounts/_utils/schemas/CfgAccountsProfileAvatarCreateRequest.schema.ts
885
+ var import_zod2 = require("zod");
886
+ var CfgAccountsProfileAvatarCreateRequestSchema = import_zod2.z.object({
887
+ avatar: import_zod2.z.union([import_zod2.z.instanceof(File), import_zod2.z.instanceof(Blob)])
888
+ });
889
+
890
+ // src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeRequestRequest.schema.ts
891
+ var import_zod3 = require("zod");
892
+ var OAuthAuthorizeRequestRequestSchema = import_zod3.z.object({
893
+ redirect_uri: import_zod3.z.union([import_zod3.z.url(), import_zod3.z.literal("")]).optional(),
894
+ source_url: import_zod3.z.union([import_zod3.z.url(), import_zod3.z.literal("")]).optional()
895
+ });
896
+
897
+ // src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeResponse.schema.ts
898
+ var import_zod4 = require("zod");
899
+ var OAuthAuthorizeResponseSchema = import_zod4.z.object({
900
+ authorization_url: import_zod4.z.union([import_zod4.z.url(), import_zod4.z.literal("")]),
901
+ state: import_zod4.z.string()
902
+ });
903
+
904
+ // src/generated/cfg_accounts/_utils/schemas/OAuthCallbackRequestRequest.schema.ts
905
+ var import_zod5 = require("zod");
906
+ var OAuthCallbackRequestRequestSchema = import_zod5.z.object({
907
+ code: import_zod5.z.string().min(10).max(500),
908
+ state: import_zod5.z.string().min(20).max(100),
909
+ redirect_uri: import_zod5.z.union([import_zod5.z.url(), import_zod5.z.literal("")]).optional()
910
+ });
911
+
912
+ // src/generated/cfg_accounts/_utils/schemas/OAuthConnection.schema.ts
913
+ var import_zod6 = require("zod");
914
+ var OAuthConnectionSchema = import_zod6.z.object({
915
+ id: import_zod6.z.int(),
916
+ provider: import_zod6.z.nativeEnum(OAuthConnectionProvider),
917
+ provider_display: import_zod6.z.string(),
918
+ provider_username: import_zod6.z.string(),
919
+ provider_email: import_zod6.z.email(),
920
+ provider_avatar_url: import_zod6.z.union([import_zod6.z.url(), import_zod6.z.literal("")]),
921
+ connected_at: import_zod6.z.iso.datetime(),
922
+ last_login_at: import_zod6.z.iso.datetime()
923
+ });
924
+
925
+ // src/generated/cfg_accounts/_utils/schemas/OAuthDisconnectRequestRequest.schema.ts
926
+ var import_zod7 = require("zod");
927
+ var OAuthDisconnectRequestRequestSchema = import_zod7.z.object({
928
+ provider: import_zod7.z.nativeEnum(OAuthDisconnectRequestRequestProvider)
929
+ });
930
+
931
+ // src/generated/cfg_accounts/_utils/schemas/OAuthError.schema.ts
932
+ var import_zod8 = require("zod");
933
+ var OAuthErrorSchema = import_zod8.z.object({
934
+ error: import_zod8.z.string(),
935
+ error_description: import_zod8.z.string().optional()
936
+ });
937
+
938
+ // src/generated/cfg_accounts/_utils/schemas/OAuthProvidersResponse.schema.ts
939
+ var import_zod9 = require("zod");
940
+ var OAuthProvidersResponseSchema = import_zod9.z.object({
941
+ providers: import_zod9.z.array(import_zod9.z.record(import_zod9.z.string(), import_zod9.z.any()))
942
+ });
943
+
944
+ // src/generated/cfg_accounts/_utils/schemas/OAuthTokenResponse.schema.ts
945
+ var import_zod10 = require("zod");
946
+ var OAuthTokenResponseSchema = import_zod10.z.object({
947
+ requires_2fa: import_zod10.z.boolean().optional(),
948
+ session_id: import_zod10.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
949
+ access: import_zod10.z.string().nullable().optional(),
950
+ refresh: import_zod10.z.string().nullable().optional(),
951
+ user: import_zod10.z.record(import_zod10.z.string(), import_zod10.z.any()).nullable().optional(),
952
+ is_new_user: import_zod10.z.boolean(),
953
+ is_new_connection: import_zod10.z.boolean(),
954
+ should_prompt_2fa: import_zod10.z.boolean().optional()
955
+ });
956
+
957
+ // src/generated/cfg_accounts/_utils/schemas/OTPErrorResponse.schema.ts
958
+ var import_zod11 = require("zod");
959
+ var OTPErrorResponseSchema = import_zod11.z.object({
960
+ error: import_zod11.z.string()
961
+ });
962
+
963
+ // src/generated/cfg_accounts/_utils/schemas/OTPRequestRequest.schema.ts
964
+ var import_zod12 = require("zod");
965
+ var OTPRequestRequestSchema = import_zod12.z.object({
966
+ identifier: import_zod12.z.string().min(1),
967
+ channel: import_zod12.z.nativeEnum(OTPRequestRequestChannel).optional(),
968
+ source_url: import_zod12.z.union([import_zod12.z.url(), import_zod12.z.literal("")]).optional()
969
+ });
970
+
971
+ // src/generated/cfg_accounts/_utils/schemas/OTPRequestResponse.schema.ts
972
+ var import_zod13 = require("zod");
973
+ var OTPRequestResponseSchema = import_zod13.z.object({
974
+ message: import_zod13.z.string()
975
+ });
976
+
977
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyRequest.schema.ts
978
+ var import_zod14 = require("zod");
979
+ var OTPVerifyRequestSchema = import_zod14.z.object({
980
+ identifier: import_zod14.z.string().min(1),
981
+ otp: import_zod14.z.string().min(6).max(6),
982
+ channel: import_zod14.z.nativeEnum(OTPVerifyRequestChannel).optional(),
983
+ source_url: import_zod14.z.union([import_zod14.z.url(), import_zod14.z.literal("")]).optional()
984
+ });
985
+
986
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
987
+ var import_zod16 = require("zod");
988
+
989
+ // src/generated/cfg_accounts/_utils/schemas/User.schema.ts
990
+ var import_zod15 = require("zod");
991
+ var UserSchema = import_zod15.z.object({
992
+ id: import_zod15.z.int(),
993
+ email: import_zod15.z.email(),
994
+ first_name: import_zod15.z.string().max(50).optional(),
995
+ last_name: import_zod15.z.string().max(50).optional(),
996
+ full_name: import_zod15.z.string(),
997
+ initials: import_zod15.z.string(),
998
+ display_username: import_zod15.z.string(),
999
+ company: import_zod15.z.string().max(100).optional(),
1000
+ phone: import_zod15.z.string().max(20).optional(),
1001
+ position: import_zod15.z.string().max(100).optional(),
1002
+ avatar: import_zod15.z.union([import_zod15.z.url(), import_zod15.z.literal("")]).nullable(),
1003
+ is_staff: import_zod15.z.boolean(),
1004
+ is_superuser: import_zod15.z.boolean(),
1005
+ date_joined: import_zod15.z.iso.datetime(),
1006
+ last_login: import_zod15.z.iso.datetime().nullable(),
1007
+ unanswered_messages_count: import_zod15.z.int(),
1008
+ centrifugo: CentrifugoTokenSchema.nullable()
1009
+ });
1010
+
1011
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
1012
+ var OTPVerifyResponseSchema = import_zod16.z.object({
1013
+ requires_2fa: import_zod16.z.boolean().optional(),
1014
+ session_id: import_zod16.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
1015
+ refresh: import_zod16.z.string().nullable().optional(),
1016
+ access: import_zod16.z.string().nullable().optional(),
1017
+ user: UserSchema.nullable().optional(),
1018
+ should_prompt_2fa: import_zod16.z.boolean().optional()
1019
+ });
1020
+
1021
+ // src/generated/cfg_accounts/_utils/schemas/PatchedUserProfileUpdateRequest.schema.ts
1022
+ var import_zod17 = require("zod");
1023
+ var PatchedUserProfileUpdateRequestSchema = import_zod17.z.object({
1024
+ first_name: import_zod17.z.string().max(50).optional(),
1025
+ last_name: import_zod17.z.string().max(50).optional(),
1026
+ company: import_zod17.z.string().max(100).optional(),
1027
+ phone: import_zod17.z.string().max(20).optional(),
1028
+ position: import_zod17.z.string().max(100).optional()
1029
+ });
1030
+
1031
+ // src/generated/cfg_accounts/_utils/schemas/TokenRefresh.schema.ts
1032
+ var import_zod18 = require("zod");
1033
+ var TokenRefreshSchema = import_zod18.z.object({
1034
+ access: import_zod18.z.string(),
1035
+ refresh: import_zod18.z.string()
1036
+ });
1037
+
1038
+ // src/generated/cfg_accounts/_utils/schemas/TokenRefreshRequest.schema.ts
1039
+ var import_zod19 = require("zod");
1040
+ var TokenRefreshRequestSchema = import_zod19.z.object({
1041
+ refresh: import_zod19.z.string().min(1)
1042
+ });
1043
+
1044
+ // src/generated/cfg_accounts/_utils/schemas/UserProfileUpdateRequest.schema.ts
1045
+ var import_zod20 = require("zod");
1046
+ var UserProfileUpdateRequestSchema = import_zod20.z.object({
1047
+ first_name: import_zod20.z.string().max(50).optional(),
1048
+ last_name: import_zod20.z.string().max(50).optional(),
1049
+ company: import_zod20.z.string().max(100).optional(),
1050
+ phone: import_zod20.z.string().max(20).optional(),
1051
+ position: import_zod20.z.string().max(100).optional()
1052
+ });
1053
+
1054
+ // src/generated/cfg_accounts/_utils/fetchers/accounts.ts
1055
+ var import_consola2 = require("consola");
1056
+
1057
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__auth.ts
1058
+ var import_consola3 = require("consola");
1059
+
1060
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__oauth.ts
1061
+ var import_consola4 = require("consola");
1062
+
1063
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__user_profile.ts
1064
+ var import_consola5 = require("consola");
1065
+
1066
+ // src/generated/cfg_accounts/index.ts
1067
+ var TOKEN_KEY = "auth_token";
1068
+ var REFRESH_TOKEN_KEY = "refresh_token";
1069
+ var API = class {
1070
+ constructor(baseUrl, options) {
1071
+ this._token = null;
1072
+ this._refreshToken = null;
1073
+ this.baseUrl = baseUrl;
1074
+ this.options = options;
1075
+ const logger2 = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
1076
+ this.storage = options?.storage || new LocalStorageAdapter(logger2);
1077
+ this._loadTokensFromStorage();
1078
+ this._client = new APIClient(this.baseUrl, {
1079
+ retryConfig: this.options?.retryConfig,
1080
+ loggerConfig: this.options?.loggerConfig,
1081
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
1082
+ });
1083
+ this._injectAuthHeader();
1084
+ this.auth = this._client.auth;
1085
+ this.oauth = this._client.oauth;
1086
+ this.user_profile = this._client.user_profile;
1087
+ this.accounts = this._client.accounts;
1088
+ }
1089
+ static {
1090
+ __name(this, "API");
1091
+ }
1092
+ _loadTokensFromStorage() {
1093
+ this._token = this.storage.getItem(TOKEN_KEY);
1094
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
1095
+ }
1096
+ _reinitClients() {
1097
+ this._client = new APIClient(this.baseUrl, {
1098
+ retryConfig: this.options?.retryConfig,
1099
+ loggerConfig: this.options?.loggerConfig,
1100
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
1101
+ });
1102
+ this._injectAuthHeader();
1103
+ this.auth = this._client.auth;
1104
+ this.oauth = this._client.oauth;
1105
+ this.user_profile = this._client.user_profile;
1106
+ this.accounts = this._client.accounts;
1107
+ }
1108
+ _injectAuthHeader() {
1109
+ const originalRequest = this._client.request.bind(this._client);
1110
+ this._client.request = async (method, path, options) => {
1111
+ const token = this.getToken();
1112
+ const mergedOptions = {
1113
+ ...options,
1114
+ headers: {
1115
+ ...options?.headers || {},
1116
+ ...token ? { "Authorization": `Bearer ${token}` } : {}
1117
+ }
1118
+ };
1119
+ return originalRequest(method, path, mergedOptions);
1120
+ };
1121
+ }
1122
+ /**
1123
+ * Get current JWT token
1124
+ */
1125
+ getToken() {
1126
+ return this.storage.getItem(TOKEN_KEY);
1127
+ }
1128
+ /**
1129
+ * Get current refresh token
1130
+ */
1131
+ getRefreshToken() {
1132
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
1133
+ }
1134
+ /**
1135
+ * Set JWT token and refresh token
1136
+ * @param token - JWT access token
1137
+ * @param refreshToken - JWT refresh token (optional)
1138
+ */
1139
+ setToken(token, refreshToken) {
1140
+ this._token = token;
1141
+ this.storage.setItem(TOKEN_KEY, token);
1142
+ if (refreshToken) {
1143
+ this._refreshToken = refreshToken;
1144
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
1145
+ }
1146
+ this._reinitClients();
1147
+ }
1148
+ /**
1149
+ * Clear all tokens
1150
+ */
1151
+ clearTokens() {
1152
+ this._token = null;
1153
+ this._refreshToken = null;
1154
+ this.storage.removeItem(TOKEN_KEY);
1155
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
1156
+ this._reinitClients();
1157
+ }
1158
+ /**
1159
+ * Check if user is authenticated
1160
+ */
1161
+ isAuthenticated() {
1162
+ return !!this.getToken();
1163
+ }
1164
+ /**
1165
+ * Update base URL and reinitialize clients
1166
+ * @param url - New base URL
1167
+ */
1168
+ setBaseUrl(url) {
1169
+ this.baseUrl = url;
1170
+ this._reinitClients();
1171
+ }
1172
+ /**
1173
+ * Get current base URL
1174
+ */
1175
+ getBaseUrl() {
1176
+ return this.baseUrl;
1177
+ }
1178
+ /**
1179
+ * Get OpenAPI schema path
1180
+ * @returns Path to the OpenAPI schema JSON file
1181
+ *
1182
+ * Note: The OpenAPI schema is available in the schema.json file.
1183
+ * You can load it dynamically using:
1184
+ * ```typescript
1185
+ * const schema = await fetch('./schema.json').then(r => r.json());
1186
+ * // or using fs in Node.js:
1187
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
1188
+ * ```
1189
+ */
1190
+ getSchemaPath() {
1191
+ return "./schema.json";
1192
+ }
1193
+ };
1194
+
1195
+ // src/generated/cfg_centrifugo/logger.ts
1196
+ var import_consola6 = require("consola");
1197
+ var DEFAULT_CONFIG2 = {
1198
+ enabled: process.env.NODE_ENV !== "production",
1199
+ logRequests: true,
1200
+ logResponses: true,
1201
+ logErrors: true,
1202
+ logBodies: true,
1203
+ logHeaders: false
1204
+ };
1205
+ var SENSITIVE_HEADERS2 = [
1206
+ "authorization",
1207
+ "cookie",
1208
+ "set-cookie",
1209
+ "x-api-key",
1210
+ "x-csrf-token"
1211
+ ];
1212
+ var APILogger2 = class {
1213
+ static {
1214
+ __name(this, "APILogger");
1215
+ }
1216
+ constructor(config = {}) {
1217
+ this.config = { ...DEFAULT_CONFIG2, ...config };
1218
+ this.consola = config.consola || (0, import_consola6.createConsola)({
1219
+ level: this.config.enabled ? 4 : 0
1220
+ });
1221
+ }
1222
+ /**
1223
+ * Enable logging
1224
+ */
1225
+ enable() {
1226
+ this.config.enabled = true;
1227
+ }
1228
+ /**
1229
+ * Disable logging
1230
+ */
1231
+ disable() {
1232
+ this.config.enabled = false;
1233
+ }
1234
+ /**
1235
+ * Update configuration
1236
+ */
1237
+ setConfig(config) {
1238
+ this.config = { ...this.config, ...config };
1239
+ }
1240
+ /**
1241
+ * Filter sensitive headers
1242
+ */
1243
+ filterHeaders(headers) {
1244
+ if (!headers) return {};
1245
+ const filtered = {};
1246
+ Object.keys(headers).forEach((key) => {
1247
+ const lowerKey = key.toLowerCase();
1248
+ if (SENSITIVE_HEADERS2.includes(lowerKey)) {
1249
+ filtered[key] = "***";
1250
+ } else {
1251
+ filtered[key] = headers[key] || "";
1252
+ }
1253
+ });
1254
+ return filtered;
1255
+ }
1256
+ /**
1257
+ * Log request
1258
+ */
1259
+ logRequest(request) {
1260
+ if (!this.config.enabled || !this.config.logRequests) return;
1261
+ const { method, url, headers, body } = request;
1262
+ this.consola.start(`${method} ${url}`);
1263
+ if (this.config.logHeaders && headers) {
1264
+ this.consola.debug("Headers:", this.filterHeaders(headers));
1265
+ }
1266
+ if (this.config.logBodies && body) {
1267
+ this.consola.debug("Body:", body);
1268
+ }
1269
+ }
1270
+ /**
1271
+ * Log response
1272
+ */
1273
+ logResponse(request, response) {
1274
+ if (!this.config.enabled || !this.config.logResponses) return;
1275
+ const { method, url } = request;
1276
+ const { status, statusText, data, duration } = response;
1277
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
1278
+ this.consola.success(
1279
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
1280
+ );
1281
+ if (this.config.logBodies && data) {
1282
+ this.consola.debug("Response:", data);
1283
+ }
1284
+ }
1285
+ /**
1286
+ * Log error
1287
+ */
1288
+ logError(request, error) {
1289
+ if (!this.config.enabled || !this.config.logErrors) return;
1290
+ const { method, url } = request;
1291
+ const { message, statusCode, fieldErrors, duration } = error;
1292
+ this.consola.error(
1293
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
1294
+ );
1295
+ this.consola.error("Message:", message);
1296
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
1297
+ this.consola.error("Field Errors:");
1298
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
1299
+ errors.forEach((err) => {
1300
+ this.consola.error(` \u2022 ${field}: ${err}`);
1301
+ });
1302
+ });
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Log general info
1307
+ */
1308
+ info(message, ...args) {
1309
+ if (!this.config.enabled) return;
1310
+ this.consola.info(message, ...args);
1311
+ }
1312
+ /**
1313
+ * Log warning
1314
+ */
1315
+ warn(message, ...args) {
1316
+ if (!this.config.enabled) return;
1317
+ this.consola.warn(message, ...args);
1318
+ }
1319
+ /**
1320
+ * Log error
1321
+ */
1322
+ error(message, ...args) {
1323
+ if (!this.config.enabled) return;
1324
+ this.consola.error(message, ...args);
1325
+ }
1326
+ /**
1327
+ * Log debug
1328
+ */
1329
+ debug(message, ...args) {
1330
+ if (!this.config.enabled) return;
1331
+ this.consola.debug(message, ...args);
1332
+ }
1333
+ /**
1334
+ * Log success
1335
+ */
1336
+ success(message, ...args) {
1337
+ if (!this.config.enabled) return;
1338
+ this.consola.success(message, ...args);
1339
+ }
1340
+ /**
1341
+ * Create a sub-logger with prefix
1342
+ */
1343
+ withTag(tag) {
1344
+ return this.consola.withTag(tag);
1345
+ }
1346
+ };
1347
+ var defaultLogger2 = new APILogger2();
1348
+
1349
+ // src/generated/cfg_centrifugo/retry.ts
1350
+ var import_p_retry2 = __toESM(require("p-retry"), 1);
1351
+
1352
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelInfo.schema.ts
1353
+ var import_zod21 = require("zod");
1354
+ var CentrifugoChannelInfoSchema = import_zod21.z.object({
1355
+ num_clients: import_zod21.z.int()
1356
+ });
1357
+
1358
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsRequestRequest.schema.ts
1359
+ var import_zod22 = require("zod");
1360
+ var CentrifugoChannelsRequestRequestSchema = import_zod22.z.object({
1361
+ pattern: import_zod22.z.string().nullable().optional()
1362
+ });
1363
+
1364
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
1365
+ var import_zod25 = require("zod");
1366
+
1367
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResult.schema.ts
1368
+ var import_zod23 = require("zod");
1369
+ var CentrifugoChannelsResultSchema = import_zod23.z.object({
1370
+ channels: import_zod23.z.record(import_zod23.z.string(), CentrifugoChannelInfoSchema)
1371
+ });
1372
+
1373
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoError.schema.ts
1374
+ var import_zod24 = require("zod");
1375
+ var CentrifugoErrorSchema = import_zod24.z.object({
1376
+ code: import_zod24.z.int().optional(),
1377
+ message: import_zod24.z.string().optional()
1378
+ });
1379
+
1380
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
1381
+ var CentrifugoChannelsResponseSchema = import_zod25.z.object({
1382
+ error: CentrifugoErrorSchema.optional(),
1383
+ result: CentrifugoChannelsResultSchema.optional()
1384
+ });
1385
+
1386
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoClientInfo.schema.ts
1387
+ var import_zod26 = require("zod");
1388
+ var CentrifugoClientInfoSchema = import_zod26.z.object({
1389
+ user: import_zod26.z.string(),
1390
+ client: import_zod26.z.string(),
1391
+ conn_info: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.any()).nullable().optional(),
1392
+ chan_info: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.any()).nullable().optional()
1393
+ });
1394
+
1395
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHealthCheck.schema.ts
1396
+ var import_zod27 = require("zod");
1397
+ var CentrifugoHealthCheckSchema = import_zod27.z.object({
1398
+ status: import_zod27.z.string(),
1399
+ wrapper_url: import_zod27.z.string(),
1400
+ has_api_key: import_zod27.z.boolean(),
1401
+ timestamp: import_zod27.z.string()
1402
+ });
1403
+
1404
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
1405
+ var import_zod29 = require("zod");
1406
+
1407
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoStreamPosition.schema.ts
1408
+ var import_zod28 = require("zod");
1409
+ var CentrifugoStreamPositionSchema = import_zod28.z.object({
1410
+ offset: import_zod28.z.int(),
1411
+ epoch: import_zod28.z.string()
1412
+ });
1413
+
1414
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
1415
+ var CentrifugoHistoryRequestRequestSchema = import_zod29.z.object({
1416
+ channel: import_zod29.z.string(),
1417
+ limit: import_zod29.z.int().nullable().optional(),
1418
+ since: CentrifugoStreamPositionSchema.optional(),
1419
+ reverse: import_zod29.z.boolean().nullable().optional()
1420
+ });
1421
+
1422
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
1423
+ var import_zod32 = require("zod");
1424
+
1425
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
1426
+ var import_zod31 = require("zod");
1427
+
1428
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPublication.schema.ts
1429
+ var import_zod30 = require("zod");
1430
+ var CentrifugoPublicationSchema = import_zod30.z.object({
1431
+ data: import_zod30.z.record(import_zod30.z.string(), import_zod30.z.any()),
1432
+ info: CentrifugoClientInfoSchema.optional(),
1433
+ offset: import_zod30.z.int(),
1434
+ tags: import_zod30.z.record(import_zod30.z.string(), import_zod30.z.any()).nullable().optional()
1435
+ });
1436
+
1437
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
1438
+ var CentrifugoHistoryResultSchema = import_zod31.z.object({
1439
+ publications: import_zod31.z.array(CentrifugoPublicationSchema),
1440
+ epoch: import_zod31.z.string(),
1441
+ offset: import_zod31.z.int()
1442
+ });
1443
+
1444
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
1445
+ var CentrifugoHistoryResponseSchema = import_zod32.z.object({
1446
+ error: CentrifugoErrorSchema.optional(),
1447
+ result: CentrifugoHistoryResultSchema.optional()
1448
+ });
1449
+
1450
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
1451
+ var import_zod37 = require("zod");
1452
+
1453
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
1454
+ var import_zod36 = require("zod");
1455
+
1456
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
1457
+ var import_zod35 = require("zod");
1458
+
1459
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoMetrics.schema.ts
1460
+ var import_zod33 = require("zod");
1461
+ var CentrifugoMetricsSchema = import_zod33.z.object({
1462
+ interval: import_zod33.z.number(),
1463
+ items: import_zod33.z.record(import_zod33.z.string(), import_zod33.z.number())
1464
+ });
1465
+
1466
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoProcess.schema.ts
1467
+ var import_zod34 = require("zod");
1468
+ var CentrifugoProcessSchema = import_zod34.z.object({
1469
+ cpu: import_zod34.z.number(),
1470
+ rss: import_zod34.z.int()
1471
+ });
1472
+
1473
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
1474
+ var CentrifugoNodeInfoSchema = import_zod35.z.object({
1475
+ uid: import_zod35.z.string(),
1476
+ name: import_zod35.z.string(),
1477
+ version: import_zod35.z.string(),
1478
+ num_clients: import_zod35.z.int(),
1479
+ num_users: import_zod35.z.int(),
1480
+ num_channels: import_zod35.z.int(),
1481
+ uptime: import_zod35.z.int(),
1482
+ num_subs: import_zod35.z.int(),
1483
+ metrics: CentrifugoMetricsSchema.optional(),
1484
+ process: CentrifugoProcessSchema.optional()
1485
+ });
1486
+
1487
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
1488
+ var CentrifugoInfoResultSchema = import_zod36.z.object({
1489
+ nodes: import_zod36.z.array(CentrifugoNodeInfoSchema)
1490
+ });
1491
+
1492
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
1493
+ var CentrifugoInfoResponseSchema = import_zod37.z.object({
1494
+ error: CentrifugoErrorSchema.optional(),
1495
+ result: CentrifugoInfoResultSchema.optional()
1496
+ });
1497
+
1498
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoOverviewStats.schema.ts
1499
+ var import_zod38 = require("zod");
1500
+ var CentrifugoOverviewStatsSchema = import_zod38.z.object({
1501
+ total: import_zod38.z.int(),
1502
+ successful: import_zod38.z.int(),
1503
+ failed: import_zod38.z.int(),
1504
+ timeout: import_zod38.z.int(),
1505
+ success_rate: import_zod38.z.number(),
1506
+ avg_duration_ms: import_zod38.z.number(),
1507
+ avg_acks_received: import_zod38.z.number(),
1508
+ period_hours: import_zod38.z.int()
1509
+ });
1510
+
1511
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceRequestRequest.schema.ts
1512
+ var import_zod39 = require("zod");
1513
+ var CentrifugoPresenceRequestRequestSchema = import_zod39.z.object({
1514
+ channel: import_zod39.z.string()
1515
+ });
1516
+
1517
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
1518
+ var import_zod41 = require("zod");
1519
+
1520
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResult.schema.ts
1521
+ var import_zod40 = require("zod");
1522
+ var CentrifugoPresenceResultSchema = import_zod40.z.object({
1523
+ presence: import_zod40.z.record(import_zod40.z.string(), CentrifugoClientInfoSchema)
1524
+ });
1525
+
1526
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
1527
+ var CentrifugoPresenceResponseSchema = import_zod41.z.object({
1528
+ error: CentrifugoErrorSchema.optional(),
1529
+ result: CentrifugoPresenceResultSchema.optional()
1530
+ });
1531
+
1532
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsRequestRequest.schema.ts
1533
+ var import_zod42 = require("zod");
1534
+ var CentrifugoPresenceStatsRequestRequestSchema = import_zod42.z.object({
1535
+ channel: import_zod42.z.string()
1536
+ });
1537
+
1538
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
1539
+ var import_zod44 = require("zod");
1540
+
1541
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResult.schema.ts
1542
+ var import_zod43 = require("zod");
1543
+ var CentrifugoPresenceStatsResultSchema = import_zod43.z.object({
1544
+ num_clients: import_zod43.z.int(),
1545
+ num_users: import_zod43.z.int()
1546
+ });
1547
+
1548
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
1549
+ var CentrifugoPresenceStatsResponseSchema = import_zod44.z.object({
1550
+ error: CentrifugoErrorSchema.optional(),
1551
+ result: CentrifugoPresenceStatsResultSchema.optional()
1552
+ });
1553
+
1554
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
1555
+ var import_zod46 = require("zod");
1556
+
1557
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelStats.schema.ts
1558
+ var import_zod45 = require("zod");
1559
+ var ChannelStatsSchema = import_zod45.z.object({
1560
+ channel: import_zod45.z.string(),
1561
+ total: import_zod45.z.int(),
1562
+ successful: import_zod45.z.int(),
1563
+ failed: import_zod45.z.int(),
1564
+ avg_duration_ms: import_zod45.z.number(),
1565
+ avg_acks: import_zod45.z.number(),
1566
+ last_activity_at: import_zod45.z.string().nullable()
1567
+ });
1568
+
1569
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
1570
+ var ChannelListSchema = import_zod46.z.object({
1571
+ channels: import_zod46.z.array(ChannelStatsSchema),
1572
+ total_channels: import_zod46.z.int()
1573
+ });
1574
+
1575
+ // src/generated/cfg_centrifugo/_utils/schemas/ConnectionTokenResponse.schema.ts
1576
+ var import_zod47 = require("zod");
1577
+ var ConnectionTokenResponseSchema = import_zod47.z.object({
1578
+ token: import_zod47.z.string(),
1579
+ centrifugo_url: import_zod47.z.string(),
1580
+ expires_at: import_zod47.z.string(),
1581
+ channels: import_zod47.z.array(import_zod47.z.string())
1582
+ });
1583
+
1584
+ // src/generated/cfg_centrifugo/_utils/schemas/ManualAckRequestRequest.schema.ts
1585
+ var import_zod48 = require("zod");
1586
+ var ManualAckRequestRequestSchema = import_zod48.z.object({
1587
+ message_id: import_zod48.z.string(),
1588
+ client_id: import_zod48.z.string()
1589
+ });
1590
+
1591
+ // src/generated/cfg_centrifugo/_utils/schemas/ManualAckResponse.schema.ts
1592
+ var import_zod49 = require("zod");
1593
+ var ManualAckResponseSchema = import_zod49.z.object({
1594
+ success: import_zod49.z.boolean(),
1595
+ message_id: import_zod49.z.string(),
1596
+ error: import_zod49.z.string().nullable().optional()
1597
+ });
1598
+
1599
+ // src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
1600
+ var import_zod51 = require("zod");
1601
+
1602
+ // src/generated/cfg_centrifugo/_utils/schemas/Publish.schema.ts
1603
+ var import_zod50 = require("zod");
1604
+ var PublishSchema = import_zod50.z.object({
1605
+ message_id: import_zod50.z.string(),
1606
+ channel: import_zod50.z.string(),
1607
+ status: import_zod50.z.string(),
1608
+ wait_for_ack: import_zod50.z.boolean(),
1609
+ acks_received: import_zod50.z.int(),
1610
+ acks_expected: import_zod50.z.int().nullable(),
1611
+ duration_ms: import_zod50.z.number().nullable(),
1612
+ created_at: import_zod50.z.iso.datetime(),
1613
+ completed_at: import_zod50.z.iso.datetime().nullable(),
1614
+ error_code: import_zod50.z.string().nullable(),
1615
+ error_message: import_zod50.z.string().nullable()
1616
+ });
1617
+
1618
+ // src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
1619
+ var PaginatedPublishListSchema = import_zod51.z.object({
1620
+ count: import_zod51.z.int(),
1621
+ page: import_zod51.z.int(),
1622
+ pages: import_zod51.z.int(),
1623
+ page_size: import_zod51.z.int(),
1624
+ has_next: import_zod51.z.boolean(),
1625
+ has_previous: import_zod51.z.boolean(),
1626
+ next_page: import_zod51.z.int().nullable().optional(),
1627
+ previous_page: import_zod51.z.int().nullable().optional(),
1628
+ results: import_zod51.z.array(PublishSchema)
1629
+ });
1630
+
1631
+ // src/generated/cfg_centrifugo/_utils/schemas/PublishTestRequestRequest.schema.ts
1632
+ var import_zod52 = require("zod");
1633
+ var PublishTestRequestRequestSchema = import_zod52.z.object({
1634
+ channel: import_zod52.z.string(),
1635
+ data: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.any()),
1636
+ wait_for_ack: import_zod52.z.boolean().optional(),
1637
+ ack_timeout: import_zod52.z.int().min(1).max(60).optional()
1638
+ });
1639
+
1640
+ // src/generated/cfg_centrifugo/_utils/schemas/PublishTestResponse.schema.ts
1641
+ var import_zod53 = require("zod");
1642
+ var PublishTestResponseSchema = import_zod53.z.object({
1643
+ success: import_zod53.z.boolean(),
1644
+ message_id: import_zod53.z.string(),
1645
+ channel: import_zod53.z.string(),
1646
+ acks_received: import_zod53.z.int().optional(),
1647
+ delivered: import_zod53.z.boolean().optional(),
1648
+ error: import_zod53.z.string().nullable().optional()
1649
+ });
1650
+
1651
+ // src/generated/cfg_centrifugo/_utils/schemas/TimelineItem.schema.ts
1652
+ var import_zod54 = require("zod");
1653
+ var TimelineItemSchema = import_zod54.z.object({
1654
+ timestamp: import_zod54.z.string(),
1655
+ count: import_zod54.z.int(),
1656
+ successful: import_zod54.z.int(),
1657
+ failed: import_zod54.z.int(),
1658
+ timeout: import_zod54.z.int()
1659
+ });
1660
+
1661
+ // src/generated/cfg_centrifugo/_utils/schemas/TimelineResponse.schema.ts
1662
+ var import_zod55 = require("zod");
1663
+ var TimelineResponseSchema = import_zod55.z.object({
1664
+ timeline: import_zod55.z.array(TimelineItemSchema),
1665
+ period_hours: import_zod55.z.int(),
1666
+ interval: import_zod55.z.string()
1667
+ });
1668
+
1669
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_admin_api.ts
1670
+ var import_consola7 = require("consola");
1671
+
1672
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_auth.ts
1673
+ var import_consola8 = require("consola");
1674
+
1675
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_monitoring.ts
1676
+ var import_consola9 = require("consola");
1677
+
1678
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_testing.ts
1679
+ var import_consola10 = require("consola");
1680
+
1681
+ // src/generated/cfg_webpush/logger.ts
1682
+ var import_consola11 = require("consola");
1683
+ var DEFAULT_CONFIG3 = {
1684
+ enabled: process.env.NODE_ENV !== "production",
1685
+ logRequests: true,
1686
+ logResponses: true,
1687
+ logErrors: true,
1688
+ logBodies: true,
1689
+ logHeaders: false
1690
+ };
1691
+ var SENSITIVE_HEADERS3 = [
1692
+ "authorization",
1693
+ "cookie",
1694
+ "set-cookie",
1695
+ "x-api-key",
1696
+ "x-csrf-token"
1697
+ ];
1698
+ var APILogger3 = class {
1699
+ static {
1700
+ __name(this, "APILogger");
1701
+ }
1702
+ constructor(config = {}) {
1703
+ this.config = { ...DEFAULT_CONFIG3, ...config };
1704
+ this.consola = config.consola || (0, import_consola11.createConsola)({
1705
+ level: this.config.enabled ? 4 : 0
1706
+ });
1707
+ }
1708
+ /**
1709
+ * Enable logging
1710
+ */
1711
+ enable() {
1712
+ this.config.enabled = true;
1713
+ }
1714
+ /**
1715
+ * Disable logging
1716
+ */
1717
+ disable() {
1718
+ this.config.enabled = false;
1719
+ }
1720
+ /**
1721
+ * Update configuration
1722
+ */
1723
+ setConfig(config) {
1724
+ this.config = { ...this.config, ...config };
1725
+ }
1726
+ /**
1727
+ * Filter sensitive headers
1728
+ */
1729
+ filterHeaders(headers) {
1730
+ if (!headers) return {};
1731
+ const filtered = {};
1732
+ Object.keys(headers).forEach((key) => {
1733
+ const lowerKey = key.toLowerCase();
1734
+ if (SENSITIVE_HEADERS3.includes(lowerKey)) {
1735
+ filtered[key] = "***";
1736
+ } else {
1737
+ filtered[key] = headers[key] || "";
1738
+ }
1739
+ });
1740
+ return filtered;
1741
+ }
1742
+ /**
1743
+ * Log request
1744
+ */
1745
+ logRequest(request) {
1746
+ if (!this.config.enabled || !this.config.logRequests) return;
1747
+ const { method, url, headers, body } = request;
1748
+ this.consola.start(`${method} ${url}`);
1749
+ if (this.config.logHeaders && headers) {
1750
+ this.consola.debug("Headers:", this.filterHeaders(headers));
1751
+ }
1752
+ if (this.config.logBodies && body) {
1753
+ this.consola.debug("Body:", body);
1754
+ }
1755
+ }
1756
+ /**
1757
+ * Log response
1758
+ */
1759
+ logResponse(request, response) {
1760
+ if (!this.config.enabled || !this.config.logResponses) return;
1761
+ const { method, url } = request;
1762
+ const { status, statusText, data, duration } = response;
1763
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
1764
+ this.consola.success(
1765
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
1766
+ );
1767
+ if (this.config.logBodies && data) {
1768
+ this.consola.debug("Response:", data);
1769
+ }
1770
+ }
1771
+ /**
1772
+ * Log error
1773
+ */
1774
+ logError(request, error) {
1775
+ if (!this.config.enabled || !this.config.logErrors) return;
1776
+ const { method, url } = request;
1777
+ const { message, statusCode, fieldErrors, duration } = error;
1778
+ this.consola.error(
1779
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
1780
+ );
1781
+ this.consola.error("Message:", message);
1782
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
1783
+ this.consola.error("Field Errors:");
1784
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
1785
+ errors.forEach((err) => {
1786
+ this.consola.error(` \u2022 ${field}: ${err}`);
1787
+ });
1788
+ });
1789
+ }
1790
+ }
1791
+ /**
1792
+ * Log general info
1793
+ */
1794
+ info(message, ...args) {
1795
+ if (!this.config.enabled) return;
1796
+ this.consola.info(message, ...args);
1797
+ }
1798
+ /**
1799
+ * Log warning
1800
+ */
1801
+ warn(message, ...args) {
1802
+ if (!this.config.enabled) return;
1803
+ this.consola.warn(message, ...args);
1804
+ }
1805
+ /**
1806
+ * Log error
1807
+ */
1808
+ error(message, ...args) {
1809
+ if (!this.config.enabled) return;
1810
+ this.consola.error(message, ...args);
1811
+ }
1812
+ /**
1813
+ * Log debug
1814
+ */
1815
+ debug(message, ...args) {
1816
+ if (!this.config.enabled) return;
1817
+ this.consola.debug(message, ...args);
1818
+ }
1819
+ /**
1820
+ * Log success
1821
+ */
1822
+ success(message, ...args) {
1823
+ if (!this.config.enabled) return;
1824
+ this.consola.success(message, ...args);
1825
+ }
1826
+ /**
1827
+ * Create a sub-logger with prefix
1828
+ */
1829
+ withTag(tag) {
1830
+ return this.consola.withTag(tag);
1831
+ }
1832
+ };
1833
+ var defaultLogger3 = new APILogger3();
1834
+
1835
+ // src/generated/cfg_webpush/retry.ts
1836
+ var import_p_retry3 = __toESM(require("p-retry"), 1);
1837
+
1838
+ // src/generated/cfg_webpush/_utils/schemas/SendPushRequestRequest.schema.ts
1839
+ var import_zod56 = require("zod");
1840
+ var SendPushRequestRequestSchema = import_zod56.z.object({
1841
+ title: import_zod56.z.string().min(1).max(255),
1842
+ body: import_zod56.z.string().min(1),
1843
+ icon: import_zod56.z.union([import_zod56.z.url(), import_zod56.z.literal("")]).nullable().optional(),
1844
+ url: import_zod56.z.union([import_zod56.z.url(), import_zod56.z.literal("")]).nullable().optional()
1845
+ });
1846
+
1847
+ // src/generated/cfg_webpush/_utils/schemas/SendPushResponse.schema.ts
1848
+ var import_zod57 = require("zod");
1849
+ var SendPushResponseSchema = import_zod57.z.object({
1850
+ success: import_zod57.z.boolean(),
1851
+ sent_to: import_zod57.z.int()
1852
+ });
1853
+
1854
+ // src/generated/cfg_webpush/_utils/schemas/SubscribeRequestRequest.schema.ts
1855
+ var import_zod58 = require("zod");
1856
+ var SubscribeRequestRequestSchema = import_zod58.z.object({
1857
+ endpoint: import_zod58.z.union([import_zod58.z.url(), import_zod58.z.literal("")]),
1858
+ keys: import_zod58.z.record(import_zod58.z.string(), import_zod58.z.string().min(1))
1859
+ });
1860
+
1861
+ // src/generated/cfg_webpush/_utils/schemas/SubscribeResponse.schema.ts
1862
+ var import_zod59 = require("zod");
1863
+ var SubscribeResponseSchema = import_zod59.z.object({
1864
+ success: import_zod59.z.boolean(),
1865
+ subscription_id: import_zod59.z.int(),
1866
+ created: import_zod59.z.boolean()
1867
+ });
1868
+
1869
+ // src/generated/cfg_webpush/_utils/schemas/VapidPublicKeyResponse.schema.ts
1870
+ var import_zod60 = require("zod");
1871
+ var VapidPublicKeyResponseSchema = import_zod60.z.object({
1872
+ publicKey: import_zod60.z.string()
1873
+ });
1874
+
1875
+ // src/generated/cfg_webpush/_utils/fetchers/webpush__web_push.ts
1876
+ var import_consola12 = require("consola");
1877
+
1878
+ // src/index.ts
1879
+ var isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
1880
+ var apiUrl = isStaticBuild ? "" : process.env.NEXT_PUBLIC_API_URL || "";
1881
+ var api = new API(
1882
+ apiUrl,
1883
+ {
1884
+ storage: new LocalStorageAdapter()
1885
+ }
1886
+ );
1887
+ var BaseClient = class {
1888
+ static {
1889
+ __name(this, "BaseClient");
1890
+ }
1891
+ static {
1892
+ this.api = api;
1893
+ }
1894
+ };
1895
+
1896
+ // src/auth/utils/logger.ts
1897
+ var import_consola13 = require("consola");
1898
+ var isDevelopment = process.env.NODE_ENV === "development";
1899
+ var isStaticBuild2 = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
1900
+ var showLogs = isDevelopment || isStaticBuild2;
1901
+ var logger = (0, import_consola13.createConsola)({
1902
+ level: showLogs ? 4 : 1
1903
+ // dev: debug, production: errors only
1904
+ }).withTag("api");
1905
+ var authLogger = logger.withTag("auth");
1906
+
1907
+ // src/auth/middlewares/tokenRefresh.ts
1908
+ var isRefreshing = false;
1909
+ var refreshSubscribers = [];
1910
+ function subscribeTokenRefresh(callback) {
1911
+ refreshSubscribers.push(callback);
1912
+ }
1913
+ __name(subscribeTokenRefresh, "subscribeTokenRefresh");
1914
+ function onTokenRefreshed(token) {
1915
+ refreshSubscribers.forEach((callback) => callback(token));
1916
+ refreshSubscribers = [];
1917
+ }
1918
+ __name(onTokenRefreshed, "onTokenRefreshed");
1919
+ async function refreshAccessToken() {
1920
+ if (isRefreshing) {
1921
+ return new Promise((resolve) => {
1922
+ subscribeTokenRefresh((token) => resolve(token));
1923
+ });
1924
+ }
1925
+ isRefreshing = true;
1926
+ authLogger.info("Starting token refresh...");
1927
+ try {
1928
+ const refreshToken = api.getRefreshToken();
1929
+ if (!refreshToken) {
1930
+ authLogger.warn("No refresh token available for refresh");
1931
+ onTokenRefreshed(null);
1932
+ return null;
1933
+ }
1934
+ const result = await api.auth.accountsTokenRefreshCreate({
1935
+ refresh: refreshToken
1936
+ });
1937
+ const newAccessToken = result.access;
1938
+ if (!newAccessToken) {
1939
+ authLogger.error("Token refresh response missing access token");
1940
+ onTokenRefreshed(null);
1941
+ return null;
1942
+ }
1943
+ api.setToken(newAccessToken, refreshToken);
1944
+ authLogger.info("Token refreshed successfully");
1945
+ onTokenRefreshed(newAccessToken);
1946
+ return newAccessToken;
1947
+ } catch (error) {
1948
+ authLogger.error("Token refresh error:", error);
1949
+ onTokenRefreshed(null);
1950
+ return null;
1951
+ } finally {
1952
+ isRefreshing = false;
1953
+ }
1954
+ }
1955
+ __name(refreshAccessToken, "refreshAccessToken");
1956
+ function isAuthenticationError(response) {
1957
+ return response.status === 401;
1958
+ }
1959
+ __name(isAuthenticationError, "isAuthenticationError");
1960
+ function createAutoRefreshFetch(originalFetch) {
1961
+ return async (input, init) => {
1962
+ let response = await originalFetch(input, init);
1963
+ if (isAuthenticationError(response) && api.getRefreshToken()) {
1964
+ authLogger.info("Received 401, attempting token refresh...");
1965
+ const newToken = await refreshAccessToken();
1966
+ if (newToken) {
1967
+ const newInit = {
1968
+ ...init,
1969
+ headers: {
1970
+ ...init?.headers,
1971
+ Authorization: `Bearer ${newToken}`
1972
+ }
1973
+ };
1974
+ authLogger.info("Retrying request with new token...");
1975
+ response = await originalFetch(input, newInit);
1976
+ } else {
1977
+ authLogger.warn("Token refresh failed, returning original 401 response");
1978
+ }
1979
+ }
1980
+ return response;
1981
+ };
1982
+ }
1983
+ __name(createAutoRefreshFetch, "createAutoRefreshFetch");
1984
+ function isTokenExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
1985
+ const token = api.getToken();
1986
+ if (!token) return false;
1987
+ try {
1988
+ const payload = JSON.parse(atob(token.split(".")[1]));
1989
+ const expiresAt = payload.exp * 1e3;
1990
+ const now = Date.now();
1991
+ const timeUntilExpiry = expiresAt - now;
1992
+ return timeUntilExpiry < thresholdMs;
1993
+ } catch (error) {
1994
+ authLogger.error("Error checking token expiry:", error);
1995
+ return false;
1996
+ }
1997
+ }
1998
+ __name(isTokenExpiringSoon, "isTokenExpiringSoon");
1999
+ async function refreshIfExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
2000
+ if (isTokenExpiringSoon(thresholdMs)) {
2001
+ authLogger.info("Token expiring soon, proactively refreshing...");
2002
+ await refreshAccessToken();
2003
+ }
2004
+ }
2005
+ __name(refreshIfExpiringSoon, "refreshIfExpiringSoon");
47
2006
  //# sourceMappingURL=auth-server.cjs.map