@djangocfg/api 2.1.455 → 2.1.456

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 (87) hide show
  1. package/dist/auth.cjs +2654 -2920
  2. package/dist/auth.cjs.map +1 -1
  3. package/dist/auth.d.cts +18 -82
  4. package/dist/auth.d.ts +18 -82
  5. package/dist/auth.mjs +385 -2861
  6. package/dist/auth.mjs.map +1 -1
  7. package/dist/chunk-2G67QRNU.mjs +2096 -0
  8. package/dist/chunk-2G67QRNU.mjs.map +1 -0
  9. package/dist/chunk-32SRQGAC.mjs +2109 -0
  10. package/dist/chunk-32SRQGAC.mjs.map +1 -0
  11. package/dist/chunk-4BPRCONN.mjs +2098 -0
  12. package/dist/chunk-4BPRCONN.mjs.map +1 -0
  13. package/dist/chunk-5UZ2Z323.mjs +2021 -0
  14. package/dist/chunk-5UZ2Z323.mjs.map +1 -0
  15. package/dist/chunk-7KFTJXNM.mjs +2097 -0
  16. package/dist/chunk-7KFTJXNM.mjs.map +1 -0
  17. package/dist/chunk-BK4K5CVT.mjs +2019 -0
  18. package/dist/chunk-BK4K5CVT.mjs.map +1 -0
  19. package/dist/chunk-JLPJZ6WB.mjs +2020 -0
  20. package/dist/chunk-JLPJZ6WB.mjs.map +1 -0
  21. package/dist/chunk-TVU6PYJH.mjs +2032 -0
  22. package/dist/chunk-TVU6PYJH.mjs.map +1 -0
  23. package/dist/clients.cjs +2210 -1847
  24. package/dist/clients.cjs.map +1 -1
  25. package/dist/clients.d.cts +23 -0
  26. package/dist/clients.d.ts +23 -0
  27. package/dist/clients.mjs +14 -1845
  28. package/dist/clients.mjs.map +1 -1
  29. package/dist/hooks.cjs +1776 -962
  30. package/dist/hooks.cjs.map +1 -1
  31. package/dist/hooks.mjs +4 -1375
  32. package/dist/hooks.mjs.map +1 -1
  33. package/dist/index.cjs +2245 -1877
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +81 -4
  36. package/dist/index.d.ts +81 -4
  37. package/dist/index.mjs +20 -1860
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/sdk.gen-2SQOPTWJ.mjs +26 -0
  40. package/dist/sdk.gen-2SQOPTWJ.mjs.map +1 -0
  41. package/dist/sdk.gen-HSGK4C5S.mjs +26 -0
  42. package/dist/sdk.gen-HSGK4C5S.mjs.map +1 -0
  43. package/dist/sdk.gen-NUK2VGHO.mjs +25 -0
  44. package/dist/sdk.gen-NUK2VGHO.mjs.map +1 -0
  45. package/dist/sdk.gen-O4KAQUZB.mjs +26 -0
  46. package/dist/sdk.gen-O4KAQUZB.mjs.map +1 -0
  47. package/dist/sdk.gen-PPAVSBNT.mjs +26 -0
  48. package/dist/sdk.gen-PPAVSBNT.mjs.map +1 -0
  49. package/dist/sdk.gen-XLHLOCJ2.mjs +25 -0
  50. package/dist/sdk.gen-XLHLOCJ2.mjs.map +1 -0
  51. package/dist/sdk.gen-ZOE6NQAL.mjs +26 -0
  52. package/dist/sdk.gen-ZOE6NQAL.mjs.map +1 -0
  53. package/dist/sdk.gen-ZT7LGJVO.mjs +26 -0
  54. package/dist/sdk.gen-ZT7LGJVO.mjs.map +1 -0
  55. package/package.json +2 -2
  56. package/src/_api/generated/_cfg_accounts/hooks/index.ts +1 -0
  57. package/src/_api/generated/_cfg_accounts/hooks/useCfgAccountsTokenBlacklistCreate.ts +28 -0
  58. package/src/_api/generated/_cfg_accounts/openapi.json +99 -0
  59. package/src/_api/generated/_cfg_accounts/schemas/TokenBlacklistRequest.ts +11 -0
  60. package/src/_api/generated/_cfg_accounts/schemas/index.ts +1 -0
  61. package/src/_api/generated/_cfg_centrifugo/openapi.json +9 -0
  62. package/src/_api/generated/_cfg_totp/openapi.json +33 -0
  63. package/src/_api/generated/helpers/auth.ts +276 -31
  64. package/src/_api/generated/openapi.json +129 -0
  65. package/src/_api/generated/sdk.gen.ts +94 -16
  66. package/src/_api/generated/types.gen.ts +18 -0
  67. package/src/auth/__tests__/guard.test.ts +0 -31
  68. package/src/auth/constants.ts +6 -0
  69. package/src/auth/context/AccountsContext.tsx +14 -24
  70. package/src/auth/context/AuthContext.tsx +226 -609
  71. package/src/auth/hooks/index.ts +3 -4
  72. package/src/auth/hooks/useGithubAuth.ts +3 -3
  73. package/src/auth/hooks/useSession.ts +22 -0
  74. package/src/auth/hooks/useTwoFactor.ts +4 -4
  75. package/src/auth/middlewares/index.ts +5 -6
  76. package/src/auth/utils/guard.ts +0 -22
  77. package/src/auth/utils/index.ts +0 -2
  78. package/src/_api/generated/_cfg_accounts/events.ts +0 -198
  79. package/src/_api/generated/_cfg_centrifugo/events.ts +0 -198
  80. package/src/_api/generated/_cfg_totp/events.ts +0 -198
  81. package/src/auth/__tests__/jwt.test.ts +0 -119
  82. package/src/auth/__tests__/sessionBootstrap.test.ts +0 -111
  83. package/src/auth/__tests__/useTokenRefresh.dom.test.tsx +0 -167
  84. package/src/auth/hooks/useAuthGuard.ts +0 -35
  85. package/src/auth/hooks/useTokenRefresh.ts +0 -131
  86. package/src/auth/refreshHandler.ts +0 -79
  87. package/src/auth/utils/jwt.ts +0 -66
package/dist/clients.cjs CHANGED
@@ -4,6 +4,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
6
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
7
10
  var __export = (target, all) => {
8
11
  for (var name in all)
9
12
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -18,130 +21,1604 @@ var __copyProps = (to, from, except, desc) => {
18
21
  };
19
22
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
23
 
21
- // src/clients.ts
22
- var clients_exports = {};
23
- __export(clients_exports, {
24
- AccountsAPI: () => API,
25
- CentrifugoAPI: () => API2,
26
- TotpAPI: () => API3,
27
- apiAccounts: () => CfgAccountsApi,
28
- apiCentrifugo: () => CfgCentrifugoApi,
29
- apiTotp: () => CfgTotpApi
30
- });
31
- module.exports = __toCommonJS(clients_exports);
32
-
33
24
  // src/_api/generated/helpers/errors.ts
34
- var APIError = class extends Error {
35
- constructor(statusCode, statusText, response, url, message) {
36
- super(message || `HTTP ${statusCode}: ${statusText}`);
37
- this.statusCode = statusCode;
38
- this.statusText = statusText;
39
- this.response = response;
40
- this.url = url;
41
- this.name = "APIError";
25
+ var APIError;
26
+ var init_errors = __esm({
27
+ "src/_api/generated/helpers/errors.ts"() {
28
+ APIError = class extends Error {
29
+ constructor(statusCode, statusText, response, url, message) {
30
+ super(message || `HTTP ${statusCode}: ${statusText}`);
31
+ this.statusCode = statusCode;
32
+ this.statusText = statusText;
33
+ this.response = response;
34
+ this.url = url;
35
+ this.name = "APIError";
36
+ }
37
+ static {
38
+ __name(this, "APIError");
39
+ }
40
+ get details() {
41
+ if (typeof this.response === "object" && this.response !== null) {
42
+ return this.response;
43
+ }
44
+ return null;
45
+ }
46
+ get fieldErrors() {
47
+ const details = this.details;
48
+ if (!details) return null;
49
+ const fieldErrors = {};
50
+ for (const [key, value] of Object.entries(details)) {
51
+ if (Array.isArray(value)) fieldErrors[key] = value;
52
+ }
53
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
54
+ }
55
+ get errorMessage() {
56
+ const details = this.details;
57
+ if (!details) return this.message;
58
+ if (details.detail) {
59
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
60
+ }
61
+ if (details.error) return String(details.error);
62
+ if (details.message) return String(details.message);
63
+ const fieldErrors = this.fieldErrors;
64
+ if (fieldErrors) {
65
+ const firstField = Object.keys(fieldErrors)[0];
66
+ if (firstField) return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
67
+ }
68
+ return this.message;
69
+ }
70
+ get isValidationError() {
71
+ return this.statusCode === 400;
72
+ }
73
+ get isAuthError() {
74
+ return this.statusCode === 401;
75
+ }
76
+ get isPermissionError() {
77
+ return this.statusCode === 403;
78
+ }
79
+ get isNotFoundError() {
80
+ return this.statusCode === 404;
81
+ }
82
+ get isServerError() {
83
+ return this.statusCode >= 500 && this.statusCode < 600;
84
+ }
85
+ };
42
86
  }
43
- static {
44
- __name(this, "APIError");
87
+ });
88
+
89
+ // src/_api/generated/core/bodySerializer.gen.ts
90
+ var serializeFormDataPair, formDataBodySerializer, jsonBodySerializer;
91
+ var init_bodySerializer_gen = __esm({
92
+ "src/_api/generated/core/bodySerializer.gen.ts"() {
93
+ serializeFormDataPair = /* @__PURE__ */ __name((data, key, value) => {
94
+ if (typeof value === "string" || value instanceof Blob) {
95
+ data.append(key, value);
96
+ } else if (value instanceof Date) {
97
+ data.append(key, value.toISOString());
98
+ } else {
99
+ data.append(key, JSON.stringify(value));
100
+ }
101
+ }, "serializeFormDataPair");
102
+ formDataBodySerializer = {
103
+ bodySerializer: /* @__PURE__ */ __name((body) => {
104
+ const data = new FormData();
105
+ Object.entries(body).forEach(([key, value]) => {
106
+ if (value === void 0 || value === null) {
107
+ return;
108
+ }
109
+ if (Array.isArray(value)) {
110
+ value.forEach((v) => serializeFormDataPair(data, key, v));
111
+ } else {
112
+ serializeFormDataPair(data, key, value);
113
+ }
114
+ });
115
+ return data;
116
+ }, "bodySerializer")
117
+ };
118
+ jsonBodySerializer = {
119
+ bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
120
+ };
45
121
  }
46
- get details() {
47
- if (typeof this.response === "object" && this.response !== null) {
48
- return this.response;
49
- }
50
- return null;
122
+ });
123
+
124
+ // src/_api/generated/core/params.gen.ts
125
+ var extraPrefixesMap, extraPrefixes;
126
+ var init_params_gen = __esm({
127
+ "src/_api/generated/core/params.gen.ts"() {
128
+ extraPrefixesMap = {
129
+ $body_: "body",
130
+ $headers_: "headers",
131
+ $path_: "path",
132
+ $query_: "query"
133
+ };
134
+ extraPrefixes = Object.entries(extraPrefixesMap);
51
135
  }
52
- get fieldErrors() {
53
- const details = this.details;
54
- if (!details) return null;
55
- const fieldErrors = {};
56
- for (const [key, value] of Object.entries(details)) {
57
- if (Array.isArray(value)) fieldErrors[key] = value;
58
- }
59
- return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
136
+ });
137
+
138
+ // src/_api/generated/core/queryKeySerializer.gen.ts
139
+ var init_queryKeySerializer_gen = __esm({
140
+ "src/_api/generated/core/queryKeySerializer.gen.ts"() {
60
141
  }
61
- get errorMessage() {
62
- const details = this.details;
63
- if (!details) return this.message;
64
- if (details.detail) {
65
- return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
66
- }
67
- if (details.error) return String(details.error);
68
- if (details.message) return String(details.message);
69
- const fieldErrors = this.fieldErrors;
70
- if (fieldErrors) {
71
- const firstField = Object.keys(fieldErrors)[0];
72
- if (firstField) return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
142
+ });
143
+
144
+ // src/_api/generated/core/serverSentEvents.gen.ts
145
+ function createSseClient({
146
+ onRequest,
147
+ onSseError,
148
+ onSseEvent,
149
+ responseTransformer,
150
+ responseValidator,
151
+ sseDefaultRetryDelay,
152
+ sseMaxRetryAttempts,
153
+ sseMaxRetryDelay,
154
+ sseSleepFn,
155
+ url,
156
+ ...options
157
+ }) {
158
+ let lastEventId;
159
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
160
+ const createStream = /* @__PURE__ */ __name(async function* () {
161
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
162
+ let attempt = 0;
163
+ const signal = options.signal ?? new AbortController().signal;
164
+ while (true) {
165
+ if (signal.aborted) break;
166
+ attempt++;
167
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
168
+ if (lastEventId !== void 0) {
169
+ headers.set("Last-Event-ID", lastEventId);
170
+ }
171
+ try {
172
+ const requestInit = {
173
+ redirect: "follow",
174
+ ...options,
175
+ body: options.serializedBody,
176
+ headers,
177
+ signal
178
+ };
179
+ let request = new Request(url, requestInit);
180
+ if (onRequest) {
181
+ request = await onRequest(url, requestInit);
182
+ }
183
+ const _fetch = options.fetch ?? globalThis.fetch;
184
+ const response = await _fetch(request);
185
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
186
+ if (!response.body) throw new Error("No body in SSE response");
187
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
188
+ let buffer = "";
189
+ const abortHandler = /* @__PURE__ */ __name(() => {
190
+ try {
191
+ reader.cancel();
192
+ } catch {
193
+ }
194
+ }, "abortHandler");
195
+ signal.addEventListener("abort", abortHandler);
196
+ try {
197
+ while (true) {
198
+ const { done, value } = await reader.read();
199
+ if (done) break;
200
+ buffer += value;
201
+ buffer = buffer.replace(/\r\n?/g, "\n");
202
+ const chunks = buffer.split("\n\n");
203
+ buffer = chunks.pop() ?? "";
204
+ for (const chunk of chunks) {
205
+ const lines = chunk.split("\n");
206
+ const dataLines = [];
207
+ let eventName;
208
+ for (const line of lines) {
209
+ if (line.startsWith("data:")) {
210
+ dataLines.push(line.replace(/^data:\s*/, ""));
211
+ } else if (line.startsWith("event:")) {
212
+ eventName = line.replace(/^event:\s*/, "");
213
+ } else if (line.startsWith("id:")) {
214
+ lastEventId = line.replace(/^id:\s*/, "");
215
+ } else if (line.startsWith("retry:")) {
216
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
217
+ if (!Number.isNaN(parsed)) {
218
+ retryDelay = parsed;
219
+ }
220
+ }
221
+ }
222
+ let data;
223
+ let parsedJson = false;
224
+ if (dataLines.length) {
225
+ const rawData = dataLines.join("\n");
226
+ try {
227
+ data = JSON.parse(rawData);
228
+ parsedJson = true;
229
+ } catch {
230
+ data = rawData;
231
+ }
232
+ }
233
+ if (parsedJson) {
234
+ if (responseValidator) {
235
+ await responseValidator(data);
236
+ }
237
+ if (responseTransformer) {
238
+ data = await responseTransformer(data);
239
+ }
240
+ }
241
+ onSseEvent?.({
242
+ data,
243
+ event: eventName,
244
+ id: lastEventId,
245
+ retry: retryDelay
246
+ });
247
+ if (dataLines.length) {
248
+ yield data;
249
+ }
250
+ }
251
+ }
252
+ } finally {
253
+ signal.removeEventListener("abort", abortHandler);
254
+ reader.releaseLock();
255
+ }
256
+ break;
257
+ } catch (error) {
258
+ onSseError?.(error);
259
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
260
+ break;
261
+ }
262
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
263
+ await sleep(backoff);
264
+ }
73
265
  }
74
- return this.message;
266
+ }, "createStream");
267
+ const stream = createStream();
268
+ return { stream };
269
+ }
270
+ var init_serverSentEvents_gen = __esm({
271
+ "src/_api/generated/core/serverSentEvents.gen.ts"() {
272
+ __name(createSseClient, "createSseClient");
75
273
  }
76
- get isValidationError() {
77
- return this.statusCode === 400;
274
+ });
275
+
276
+ // src/_api/generated/core/pathSerializer.gen.ts
277
+ var separatorArrayExplode, separatorArrayNoExplode, separatorObjectExplode, serializeArrayParam, serializePrimitiveParam, serializeObjectParam;
278
+ var init_pathSerializer_gen = __esm({
279
+ "src/_api/generated/core/pathSerializer.gen.ts"() {
280
+ separatorArrayExplode = /* @__PURE__ */ __name((style) => {
281
+ switch (style) {
282
+ case "label":
283
+ return ".";
284
+ case "matrix":
285
+ return ";";
286
+ case "simple":
287
+ return ",";
288
+ default:
289
+ return "&";
290
+ }
291
+ }, "separatorArrayExplode");
292
+ separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
293
+ switch (style) {
294
+ case "form":
295
+ return ",";
296
+ case "pipeDelimited":
297
+ return "|";
298
+ case "spaceDelimited":
299
+ return "%20";
300
+ default:
301
+ return ",";
302
+ }
303
+ }, "separatorArrayNoExplode");
304
+ separatorObjectExplode = /* @__PURE__ */ __name((style) => {
305
+ switch (style) {
306
+ case "label":
307
+ return ".";
308
+ case "matrix":
309
+ return ";";
310
+ case "simple":
311
+ return ",";
312
+ default:
313
+ return "&";
314
+ }
315
+ }, "separatorObjectExplode");
316
+ serializeArrayParam = /* @__PURE__ */ __name(({
317
+ allowReserved,
318
+ explode,
319
+ name,
320
+ style,
321
+ value
322
+ }) => {
323
+ if (!explode) {
324
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
325
+ switch (style) {
326
+ case "label":
327
+ return `.${joinedValues2}`;
328
+ case "matrix":
329
+ return `;${name}=${joinedValues2}`;
330
+ case "simple":
331
+ return joinedValues2;
332
+ default:
333
+ return `${name}=${joinedValues2}`;
334
+ }
335
+ }
336
+ const separator = separatorArrayExplode(style);
337
+ const joinedValues = value.map((v) => {
338
+ if (style === "label" || style === "simple") {
339
+ return allowReserved ? v : encodeURIComponent(v);
340
+ }
341
+ return serializePrimitiveParam({
342
+ allowReserved,
343
+ name,
344
+ value: v
345
+ });
346
+ }).join(separator);
347
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
348
+ }, "serializeArrayParam");
349
+ serializePrimitiveParam = /* @__PURE__ */ __name(({
350
+ allowReserved,
351
+ name,
352
+ value
353
+ }) => {
354
+ if (value === void 0 || value === null) {
355
+ return "";
356
+ }
357
+ if (typeof value === "object") {
358
+ throw new Error(
359
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
360
+ );
361
+ }
362
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
363
+ }, "serializePrimitiveParam");
364
+ serializeObjectParam = /* @__PURE__ */ __name(({
365
+ allowReserved,
366
+ explode,
367
+ name,
368
+ style,
369
+ value,
370
+ valueOnly
371
+ }) => {
372
+ if (value instanceof Date) {
373
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
374
+ }
375
+ if (style !== "deepObject" && !explode) {
376
+ let values = [];
377
+ Object.entries(value).forEach(([key, v]) => {
378
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
379
+ });
380
+ const joinedValues2 = values.join(",");
381
+ switch (style) {
382
+ case "form":
383
+ return `${name}=${joinedValues2}`;
384
+ case "label":
385
+ return `.${joinedValues2}`;
386
+ case "matrix":
387
+ return `;${name}=${joinedValues2}`;
388
+ default:
389
+ return joinedValues2;
390
+ }
391
+ }
392
+ const separator = separatorObjectExplode(style);
393
+ const joinedValues = Object.entries(value).map(
394
+ ([key, v]) => serializePrimitiveParam({
395
+ allowReserved,
396
+ name: style === "deepObject" ? `${name}[${key}]` : key,
397
+ value: v
398
+ })
399
+ ).join(separator);
400
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
401
+ }, "serializeObjectParam");
78
402
  }
79
- get isAuthError() {
80
- return this.statusCode === 401;
403
+ });
404
+
405
+ // src/_api/generated/core/utils.gen.ts
406
+ function getValidRequestBody(options) {
407
+ const hasBody = options.body !== void 0;
408
+ const isSerializedBody = hasBody && options.bodySerializer;
409
+ if (isSerializedBody) {
410
+ if ("serializedBody" in options) {
411
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
412
+ return hasSerializedBody ? options.serializedBody : null;
413
+ }
414
+ return options.body !== "" ? options.body : null;
81
415
  }
82
- get isPermissionError() {
83
- return this.statusCode === 403;
416
+ if (hasBody) {
417
+ return options.body;
84
418
  }
85
- get isNotFoundError() {
86
- return this.statusCode === 404;
419
+ return void 0;
420
+ }
421
+ var PATH_PARAM_RE, defaultPathSerializer, getUrl;
422
+ var init_utils_gen = __esm({
423
+ "src/_api/generated/core/utils.gen.ts"() {
424
+ init_pathSerializer_gen();
425
+ PATH_PARAM_RE = /\{[^{}]+\}/g;
426
+ defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
427
+ let url = _url;
428
+ const matches = _url.match(PATH_PARAM_RE);
429
+ if (matches) {
430
+ for (const match of matches) {
431
+ let explode = false;
432
+ let name = match.substring(1, match.length - 1);
433
+ let style = "simple";
434
+ if (name.endsWith("*")) {
435
+ explode = true;
436
+ name = name.substring(0, name.length - 1);
437
+ }
438
+ if (name.startsWith(".")) {
439
+ name = name.substring(1);
440
+ style = "label";
441
+ } else if (name.startsWith(";")) {
442
+ name = name.substring(1);
443
+ style = "matrix";
444
+ }
445
+ const value = path[name];
446
+ if (value === void 0 || value === null) {
447
+ continue;
448
+ }
449
+ if (Array.isArray(value)) {
450
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
451
+ continue;
452
+ }
453
+ if (typeof value === "object") {
454
+ url = url.replace(
455
+ match,
456
+ serializeObjectParam({
457
+ explode,
458
+ name,
459
+ style,
460
+ value,
461
+ valueOnly: true
462
+ })
463
+ );
464
+ continue;
465
+ }
466
+ if (style === "matrix") {
467
+ url = url.replace(
468
+ match,
469
+ `;${serializePrimitiveParam({
470
+ name,
471
+ value
472
+ })}`
473
+ );
474
+ continue;
475
+ }
476
+ const replaceValue = encodeURIComponent(
477
+ style === "label" ? `.${value}` : value
478
+ );
479
+ url = url.replace(match, replaceValue);
480
+ }
481
+ }
482
+ return url;
483
+ }, "defaultPathSerializer");
484
+ getUrl = /* @__PURE__ */ __name(({
485
+ baseUrl,
486
+ path,
487
+ query,
488
+ querySerializer,
489
+ url: _url
490
+ }) => {
491
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
492
+ let url = (baseUrl ?? "") + pathUrl;
493
+ if (path) {
494
+ url = defaultPathSerializer({ path, url });
495
+ }
496
+ let search = query ? querySerializer(query) : "";
497
+ if (search.startsWith("?")) {
498
+ search = search.substring(1);
499
+ }
500
+ if (search) {
501
+ url += `?${search}`;
502
+ }
503
+ return url;
504
+ }, "getUrl");
505
+ __name(getValidRequestBody, "getValidRequestBody");
87
506
  }
88
- get isServerError() {
89
- return this.statusCode >= 500 && this.statusCode < 600;
507
+ });
508
+
509
+ // src/_api/generated/core/auth.gen.ts
510
+ var getAuthToken;
511
+ var init_auth_gen = __esm({
512
+ "src/_api/generated/core/auth.gen.ts"() {
513
+ getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
514
+ const token = typeof callback === "function" ? await callback(auth2) : callback;
515
+ if (!token) {
516
+ return;
517
+ }
518
+ if (auth2.scheme === "bearer") {
519
+ return `Bearer ${token}`;
520
+ }
521
+ if (auth2.scheme === "basic") {
522
+ return `Basic ${btoa(token)}`;
523
+ }
524
+ return token;
525
+ }, "getAuthToken");
90
526
  }
91
- };
527
+ });
92
528
 
93
- // src/_api/generated/helpers/auth.ts
94
- var ACCESS_KEY = "cfg.access_token";
95
- var REFRESH_KEY = "cfg.refresh_token";
96
- var API_KEY_KEY = "cfg.api_key";
97
- var isBrowser = typeof window !== "undefined";
98
- var localStorageBackend = {
99
- get(key) {
100
- if (!isBrowser) return null;
101
- try {
102
- return window.localStorage.getItem(key);
103
- } catch {
104
- return null;
105
- }
106
- },
107
- set(key, value) {
108
- if (!isBrowser) return;
109
- try {
110
- if (value === null) window.localStorage.removeItem(key);
111
- else window.localStorage.setItem(key, value);
112
- } catch {
529
+ // src/_api/generated/client/utils.gen.ts
530
+ async function setAuthParams(options) {
531
+ for (const auth2 of options.security ?? []) {
532
+ if (checkForExistence(options, auth2.name)) {
533
+ continue;
113
534
  }
114
- }
115
- };
116
- var COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
117
- var cookieBackend = {
118
- get(key) {
119
- if (!isBrowser) return null;
120
- try {
121
- const re = new RegExp(`(?:^|;\\s*)${encodeURIComponent(key)}=([^;]*)`);
122
- const m = document.cookie.match(re);
123
- return m ? decodeURIComponent(m[1]) : null;
124
- } catch {
125
- return null;
535
+ const token = await getAuthToken(auth2, options.auth);
536
+ if (!token) {
537
+ continue;
126
538
  }
127
- },
128
- set(key, value) {
129
- if (!isBrowser) return;
130
- try {
131
- const k = encodeURIComponent(key);
132
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
133
- if (value === null) {
134
- document.cookie = `${k}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
135
- } else {
136
- const v = encodeURIComponent(value);
137
- document.cookie = `${k}=${v}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
138
- }
139
- } catch {
539
+ const name = auth2.name ?? "Authorization";
540
+ switch (auth2.in) {
541
+ case "query":
542
+ if (!options.query) {
543
+ options.query = {};
544
+ }
545
+ options.query[name] = token;
546
+ break;
547
+ case "cookie":
548
+ options.headers.append("Cookie", `${name}=${token}`);
549
+ break;
550
+ case "header":
551
+ default:
552
+ options.headers.set(name, token);
553
+ break;
140
554
  }
141
555
  }
142
- };
143
- var _storage = localStorageBackend;
144
- var _storageMode = "localStorage";
556
+ }
557
+ var createQuerySerializer, getParseAs, checkForExistence, buildUrl, mergeConfigs, headersEntries, mergeHeaders, Interceptors, createInterceptors, defaultQuerySerializer, defaultHeaders, createConfig;
558
+ var init_utils_gen2 = __esm({
559
+ "src/_api/generated/client/utils.gen.ts"() {
560
+ init_auth_gen();
561
+ init_bodySerializer_gen();
562
+ init_pathSerializer_gen();
563
+ init_utils_gen();
564
+ createQuerySerializer = /* @__PURE__ */ __name(({
565
+ parameters = {},
566
+ ...args
567
+ } = {}) => {
568
+ const querySerializer = /* @__PURE__ */ __name((queryParams) => {
569
+ const search = [];
570
+ if (queryParams && typeof queryParams === "object") {
571
+ for (const name in queryParams) {
572
+ const value = queryParams[name];
573
+ if (value === void 0 || value === null) {
574
+ continue;
575
+ }
576
+ const options = parameters[name] || args;
577
+ if (Array.isArray(value)) {
578
+ const serializedArray = serializeArrayParam({
579
+ allowReserved: options.allowReserved,
580
+ explode: true,
581
+ name,
582
+ style: "form",
583
+ value,
584
+ ...options.array
585
+ });
586
+ if (serializedArray) search.push(serializedArray);
587
+ } else if (typeof value === "object") {
588
+ const serializedObject = serializeObjectParam({
589
+ allowReserved: options.allowReserved,
590
+ explode: true,
591
+ name,
592
+ style: "deepObject",
593
+ value,
594
+ ...options.object
595
+ });
596
+ if (serializedObject) search.push(serializedObject);
597
+ } else {
598
+ const serializedPrimitive = serializePrimitiveParam({
599
+ allowReserved: options.allowReserved,
600
+ name,
601
+ value
602
+ });
603
+ if (serializedPrimitive) search.push(serializedPrimitive);
604
+ }
605
+ }
606
+ }
607
+ return search.join("&");
608
+ }, "querySerializer");
609
+ return querySerializer;
610
+ }, "createQuerySerializer");
611
+ getParseAs = /* @__PURE__ */ __name((contentType) => {
612
+ if (!contentType) {
613
+ return "stream";
614
+ }
615
+ const cleanContent = contentType.split(";")[0]?.trim();
616
+ if (!cleanContent) {
617
+ return;
618
+ }
619
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
620
+ return "json";
621
+ }
622
+ if (cleanContent === "multipart/form-data") {
623
+ return "formData";
624
+ }
625
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
626
+ return "blob";
627
+ }
628
+ if (cleanContent.startsWith("text/")) {
629
+ return "text";
630
+ }
631
+ return;
632
+ }, "getParseAs");
633
+ checkForExistence = /* @__PURE__ */ __name((options, name) => {
634
+ if (!name) {
635
+ return false;
636
+ }
637
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
638
+ return true;
639
+ }
640
+ return false;
641
+ }, "checkForExistence");
642
+ __name(setAuthParams, "setAuthParams");
643
+ buildUrl = /* @__PURE__ */ __name((options) => getUrl({
644
+ baseUrl: options.baseUrl,
645
+ path: options.path,
646
+ query: options.query,
647
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
648
+ url: options.url
649
+ }), "buildUrl");
650
+ mergeConfigs = /* @__PURE__ */ __name((a, b) => {
651
+ const config = { ...a, ...b };
652
+ if (config.baseUrl?.endsWith("/")) {
653
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
654
+ }
655
+ config.headers = mergeHeaders(a.headers, b.headers);
656
+ return config;
657
+ }, "mergeConfigs");
658
+ headersEntries = /* @__PURE__ */ __name((headers) => {
659
+ const entries = [];
660
+ headers.forEach((value, key) => {
661
+ entries.push([key, value]);
662
+ });
663
+ return entries;
664
+ }, "headersEntries");
665
+ mergeHeaders = /* @__PURE__ */ __name((...headers) => {
666
+ const mergedHeaders = new Headers();
667
+ for (const header of headers) {
668
+ if (!header) {
669
+ continue;
670
+ }
671
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
672
+ for (const [key, value] of iterator) {
673
+ if (value === null) {
674
+ mergedHeaders.delete(key);
675
+ } else if (Array.isArray(value)) {
676
+ for (const v of value) {
677
+ mergedHeaders.append(key, v);
678
+ }
679
+ } else if (value !== void 0) {
680
+ mergedHeaders.set(
681
+ key,
682
+ typeof value === "object" ? JSON.stringify(value) : value
683
+ );
684
+ }
685
+ }
686
+ }
687
+ return mergedHeaders;
688
+ }, "mergeHeaders");
689
+ Interceptors = class {
690
+ static {
691
+ __name(this, "Interceptors");
692
+ }
693
+ fns = [];
694
+ clear() {
695
+ this.fns = [];
696
+ }
697
+ eject(id) {
698
+ const index = this.getInterceptorIndex(id);
699
+ if (this.fns[index]) {
700
+ this.fns[index] = null;
701
+ }
702
+ }
703
+ exists(id) {
704
+ const index = this.getInterceptorIndex(id);
705
+ return Boolean(this.fns[index]);
706
+ }
707
+ getInterceptorIndex(id) {
708
+ if (typeof id === "number") {
709
+ return this.fns[id] ? id : -1;
710
+ }
711
+ return this.fns.indexOf(id);
712
+ }
713
+ update(id, fn) {
714
+ const index = this.getInterceptorIndex(id);
715
+ if (this.fns[index]) {
716
+ this.fns[index] = fn;
717
+ return id;
718
+ }
719
+ return false;
720
+ }
721
+ use(fn) {
722
+ this.fns.push(fn);
723
+ return this.fns.length - 1;
724
+ }
725
+ };
726
+ createInterceptors = /* @__PURE__ */ __name(() => ({
727
+ error: new Interceptors(),
728
+ request: new Interceptors(),
729
+ response: new Interceptors()
730
+ }), "createInterceptors");
731
+ defaultQuerySerializer = createQuerySerializer({
732
+ allowReserved: false,
733
+ array: {
734
+ explode: true,
735
+ style: "form"
736
+ },
737
+ object: {
738
+ explode: true,
739
+ style: "deepObject"
740
+ }
741
+ });
742
+ defaultHeaders = {
743
+ "Content-Type": "application/json"
744
+ };
745
+ createConfig = /* @__PURE__ */ __name((override = {}) => ({
746
+ ...jsonBodySerializer,
747
+ headers: defaultHeaders,
748
+ parseAs: "auto",
749
+ querySerializer: defaultQuerySerializer,
750
+ ...override
751
+ }), "createConfig");
752
+ }
753
+ });
754
+
755
+ // src/_api/generated/client/client.gen.ts
756
+ var createClient;
757
+ var init_client_gen = __esm({
758
+ "src/_api/generated/client/client.gen.ts"() {
759
+ init_serverSentEvents_gen();
760
+ init_utils_gen();
761
+ init_utils_gen2();
762
+ createClient = /* @__PURE__ */ __name((config = {}) => {
763
+ let _config = mergeConfigs(createConfig(), config);
764
+ const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
765
+ const setConfig = /* @__PURE__ */ __name((config2) => {
766
+ _config = mergeConfigs(_config, config2);
767
+ return getConfig();
768
+ }, "setConfig");
769
+ const interceptors = createInterceptors();
770
+ const beforeRequest = /* @__PURE__ */ __name(async (options) => {
771
+ const opts = {
772
+ ..._config,
773
+ ...options,
774
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
775
+ headers: mergeHeaders(_config.headers, options.headers),
776
+ serializedBody: void 0
777
+ };
778
+ if (opts.security) {
779
+ await setAuthParams(opts);
780
+ }
781
+ if (opts.requestValidator) {
782
+ await opts.requestValidator(opts);
783
+ }
784
+ if (opts.body !== void 0 && opts.bodySerializer) {
785
+ opts.serializedBody = opts.bodySerializer(opts.body);
786
+ }
787
+ if (opts.body === void 0 || opts.serializedBody === "") {
788
+ opts.headers.delete("Content-Type");
789
+ }
790
+ const resolvedOpts = opts;
791
+ const url = buildUrl(resolvedOpts);
792
+ return { opts: resolvedOpts, url };
793
+ }, "beforeRequest");
794
+ const request = /* @__PURE__ */ __name(async (options) => {
795
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
796
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
797
+ let request2;
798
+ let response;
799
+ try {
800
+ const { opts, url } = await beforeRequest(options);
801
+ const requestInit = {
802
+ redirect: "follow",
803
+ ...opts,
804
+ body: getValidRequestBody(opts)
805
+ };
806
+ request2 = new Request(url, requestInit);
807
+ for (const fn of interceptors.request.fns) {
808
+ if (fn) {
809
+ request2 = await fn(request2, opts);
810
+ }
811
+ }
812
+ const _fetch = opts.fetch;
813
+ response = await _fetch(request2);
814
+ for (const fn of interceptors.response.fns) {
815
+ if (fn) {
816
+ response = await fn(response, request2, opts);
817
+ }
818
+ }
819
+ const result = {
820
+ request: request2,
821
+ response
822
+ };
823
+ if (response.ok) {
824
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
825
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
826
+ let emptyData;
827
+ switch (parseAs) {
828
+ case "arrayBuffer":
829
+ case "blob":
830
+ case "text":
831
+ emptyData = await response[parseAs]();
832
+ break;
833
+ case "formData":
834
+ emptyData = new FormData();
835
+ break;
836
+ case "stream":
837
+ emptyData = response.body;
838
+ break;
839
+ case "json":
840
+ default:
841
+ emptyData = {};
842
+ break;
843
+ }
844
+ return opts.responseStyle === "data" ? emptyData : {
845
+ data: emptyData,
846
+ ...result
847
+ };
848
+ }
849
+ let data;
850
+ switch (parseAs) {
851
+ case "arrayBuffer":
852
+ case "blob":
853
+ case "formData":
854
+ case "text":
855
+ data = await response[parseAs]();
856
+ break;
857
+ case "json": {
858
+ const text = await response.text();
859
+ data = text ? JSON.parse(text) : {};
860
+ break;
861
+ }
862
+ case "stream":
863
+ return opts.responseStyle === "data" ? response.body : {
864
+ data: response.body,
865
+ ...result
866
+ };
867
+ }
868
+ if (parseAs === "json") {
869
+ if (opts.responseValidator) {
870
+ await opts.responseValidator(data);
871
+ }
872
+ if (opts.responseTransformer) {
873
+ data = await opts.responseTransformer(data);
874
+ }
875
+ }
876
+ return opts.responseStyle === "data" ? data : {
877
+ data,
878
+ ...result
879
+ };
880
+ }
881
+ const textError = await response.text();
882
+ let jsonError;
883
+ try {
884
+ jsonError = JSON.parse(textError);
885
+ } catch {
886
+ }
887
+ throw jsonError ?? textError;
888
+ } catch (error) {
889
+ let finalError = error;
890
+ for (const fn of interceptors.error.fns) {
891
+ if (fn) {
892
+ finalError = await fn(finalError, response, request2, options);
893
+ }
894
+ }
895
+ finalError = finalError || {};
896
+ if (throwOnError) {
897
+ throw finalError;
898
+ }
899
+ return responseStyle === "data" ? void 0 : {
900
+ error: finalError,
901
+ request: request2,
902
+ response
903
+ };
904
+ }
905
+ }, "request");
906
+ const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
907
+ const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
908
+ const { opts, url } = await beforeRequest(options);
909
+ return createSseClient({
910
+ ...opts,
911
+ body: opts.body,
912
+ method,
913
+ onRequest: /* @__PURE__ */ __name(async (url2, init) => {
914
+ let request2 = new Request(url2, init);
915
+ for (const fn of interceptors.request.fns) {
916
+ if (fn) {
917
+ request2 = await fn(request2, opts);
918
+ }
919
+ }
920
+ return request2;
921
+ }, "onRequest"),
922
+ serializedBody: getValidRequestBody(opts),
923
+ url
924
+ });
925
+ }, "makeSseFn");
926
+ const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
927
+ return {
928
+ buildUrl: _buildUrl,
929
+ connect: makeMethodFn("CONNECT"),
930
+ delete: makeMethodFn("DELETE"),
931
+ get: makeMethodFn("GET"),
932
+ getConfig,
933
+ head: makeMethodFn("HEAD"),
934
+ interceptors,
935
+ options: makeMethodFn("OPTIONS"),
936
+ patch: makeMethodFn("PATCH"),
937
+ post: makeMethodFn("POST"),
938
+ put: makeMethodFn("PUT"),
939
+ request,
940
+ setConfig,
941
+ sse: {
942
+ connect: makeSseFn("CONNECT"),
943
+ delete: makeSseFn("DELETE"),
944
+ get: makeSseFn("GET"),
945
+ head: makeSseFn("HEAD"),
946
+ options: makeSseFn("OPTIONS"),
947
+ patch: makeSseFn("PATCH"),
948
+ post: makeSseFn("POST"),
949
+ put: makeSseFn("PUT"),
950
+ trace: makeSseFn("TRACE")
951
+ },
952
+ trace: makeMethodFn("TRACE")
953
+ };
954
+ }, "createClient");
955
+ }
956
+ });
957
+
958
+ // src/_api/generated/client/index.ts
959
+ var init_client = __esm({
960
+ "src/_api/generated/client/index.ts"() {
961
+ init_bodySerializer_gen();
962
+ init_params_gen();
963
+ init_queryKeySerializer_gen();
964
+ init_client_gen();
965
+ init_utils_gen2();
966
+ }
967
+ });
968
+
969
+ // src/_api/generated/client.gen.ts
970
+ var client;
971
+ var init_client_gen2 = __esm({
972
+ "src/_api/generated/client.gen.ts"() {
973
+ init_client();
974
+ init_auth();
975
+ client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
976
+ installAuthOnClient(client);
977
+ }
978
+ });
979
+
980
+ // src/_api/generated/sdk.gen.ts
981
+ var sdk_gen_exports = {};
982
+ __export(sdk_gen_exports, {
983
+ CfgAccounts: () => CfgAccounts,
984
+ CfgAccountsApiKey: () => CfgAccountsApiKey,
985
+ CfgAccountsAuth: () => CfgAccountsAuth,
986
+ CfgAccountsOauth: () => CfgAccountsOauth,
987
+ CfgAccountsProfile: () => CfgAccountsProfile,
988
+ CfgCentrifugo: () => CfgCentrifugo,
989
+ CfgTotp: () => CfgTotp,
990
+ CfgTotpBackupCodes: () => CfgTotpBackupCodes,
991
+ CfgTotpSetup: () => CfgTotpSetup,
992
+ CfgTotpVerify: () => CfgTotpVerify
993
+ });
994
+ var CfgAccountsApiKey, CfgAccountsOauth, CfgAccounts, CfgAccountsProfile, CfgAccountsAuth, CfgCentrifugo, CfgTotpBackupCodes, CfgTotp, CfgTotpSetup, CfgTotpVerify;
995
+ var init_sdk_gen = __esm({
996
+ "src/_api/generated/sdk.gen.ts"() {
997
+ init_client();
998
+ init_client_gen2();
999
+ CfgAccountsApiKey = class {
1000
+ static {
1001
+ __name(this, "CfgAccountsApiKey");
1002
+ }
1003
+ /**
1004
+ * Get API key details
1005
+ *
1006
+ * Retrieve the current user's API key (masked) and metadata.
1007
+ */
1008
+ static cfgAccountsApiKeyRetrieve(options) {
1009
+ return (options?.client ?? client).get({
1010
+ security: [
1011
+ { scheme: "bearer", type: "http" },
1012
+ {
1013
+ in: "cookie",
1014
+ name: "sessionid",
1015
+ type: "apiKey"
1016
+ },
1017
+ { name: "X-API-Key", type: "apiKey" }
1018
+ ],
1019
+ url: "/cfg/accounts/api-key/",
1020
+ ...options
1021
+ });
1022
+ }
1023
+ /**
1024
+ * Regenerate API key
1025
+ *
1026
+ * Generate a new API key. The full key is returned only once.
1027
+ */
1028
+ static cfgAccountsApiKeyRegenerateCreate(options) {
1029
+ return (options.client ?? client).post({
1030
+ security: [
1031
+ { scheme: "bearer", type: "http" },
1032
+ {
1033
+ in: "cookie",
1034
+ name: "sessionid",
1035
+ type: "apiKey"
1036
+ },
1037
+ { name: "X-API-Key", type: "apiKey" }
1038
+ ],
1039
+ url: "/cfg/accounts/api-key/regenerate/",
1040
+ ...options,
1041
+ headers: {
1042
+ "Content-Type": "application/json",
1043
+ ...options.headers
1044
+ }
1045
+ });
1046
+ }
1047
+ /**
1048
+ * Reveal API key
1049
+ *
1050
+ * Return the current full API key WITHOUT rotating it. The same durable value every one of the user's agents uses — for the signed-in user to copy and paste into agent onboarding. Default GET stays masked; this is the explicit reveal action.
1051
+ */
1052
+ static cfgAccountsApiKeyRevealCreate(options) {
1053
+ return (options.client ?? client).post({
1054
+ security: [
1055
+ { scheme: "bearer", type: "http" },
1056
+ {
1057
+ in: "cookie",
1058
+ name: "sessionid",
1059
+ type: "apiKey"
1060
+ },
1061
+ { name: "X-API-Key", type: "apiKey" }
1062
+ ],
1063
+ url: "/cfg/accounts/api-key/reveal/",
1064
+ ...options,
1065
+ headers: {
1066
+ "Content-Type": "application/json",
1067
+ ...options.headers
1068
+ }
1069
+ });
1070
+ }
1071
+ /**
1072
+ * Test API key
1073
+ *
1074
+ * Test whether an API key is valid without consuming it.
1075
+ */
1076
+ static cfgAccountsApiKeyTestCreate(options) {
1077
+ return (options.client ?? client).post({
1078
+ security: [
1079
+ { scheme: "bearer", type: "http" },
1080
+ {
1081
+ in: "cookie",
1082
+ name: "sessionid",
1083
+ type: "apiKey"
1084
+ },
1085
+ { name: "X-API-Key", type: "apiKey" }
1086
+ ],
1087
+ url: "/cfg/accounts/api-key/test/",
1088
+ ...options,
1089
+ headers: {
1090
+ "Content-Type": "application/json",
1091
+ ...options.headers
1092
+ }
1093
+ });
1094
+ }
1095
+ };
1096
+ CfgAccountsOauth = class {
1097
+ static {
1098
+ __name(this, "CfgAccountsOauth");
1099
+ }
1100
+ /**
1101
+ * List OAuth connections
1102
+ *
1103
+ * Get all OAuth connections for the current user.
1104
+ */
1105
+ static cfgAccountsOauthConnectionsList(options) {
1106
+ return (options?.client ?? client).get({
1107
+ security: [
1108
+ { name: "X-API-Key", type: "apiKey" },
1109
+ { scheme: "bearer", type: "http" },
1110
+ { name: "Authorization", type: "apiKey" }
1111
+ ],
1112
+ url: "/cfg/accounts/oauth/connections/",
1113
+ ...options
1114
+ });
1115
+ }
1116
+ /**
1117
+ * Disconnect OAuth provider
1118
+ *
1119
+ * Remove OAuth connection for the specified provider.
1120
+ */
1121
+ static cfgAccountsOauthDisconnectCreate(options) {
1122
+ return (options.client ?? client).post({
1123
+ security: [
1124
+ { name: "X-API-Key", type: "apiKey" },
1125
+ { scheme: "bearer", type: "http" },
1126
+ { name: "Authorization", type: "apiKey" }
1127
+ ],
1128
+ url: "/cfg/accounts/oauth/disconnect/",
1129
+ ...options,
1130
+ headers: {
1131
+ "Content-Type": "application/json",
1132
+ ...options.headers
1133
+ }
1134
+ });
1135
+ }
1136
+ /**
1137
+ * Start GitHub OAuth
1138
+ *
1139
+ * Generate GitHub OAuth authorization URL. Redirect user to this URL to start authentication.
1140
+ */
1141
+ static cfgAccountsOauthGithubAuthorizeCreate(options) {
1142
+ return (options?.client ?? client).post({
1143
+ url: "/cfg/accounts/oauth/github/authorize/",
1144
+ ...options,
1145
+ headers: {
1146
+ "Content-Type": "application/json",
1147
+ ...options?.headers
1148
+ }
1149
+ });
1150
+ }
1151
+ /**
1152
+ * Complete GitHub OAuth
1153
+ *
1154
+ * Exchange authorization code for JWT tokens. Call this after GitHub redirects back with code.
1155
+ */
1156
+ static cfgAccountsOauthGithubCallbackCreate(options) {
1157
+ return (options.client ?? client).post({
1158
+ url: "/cfg/accounts/oauth/github/callback/",
1159
+ ...options,
1160
+ headers: {
1161
+ "Content-Type": "application/json",
1162
+ ...options.headers
1163
+ }
1164
+ });
1165
+ }
1166
+ /**
1167
+ * List OAuth providers
1168
+ *
1169
+ * Get list of available OAuth providers for authentication.
1170
+ */
1171
+ static cfgAccountsOauthProvidersRetrieve(options) {
1172
+ return (options?.client ?? client).get({ url: "/cfg/accounts/oauth/providers/", ...options });
1173
+ }
1174
+ };
1175
+ CfgAccounts = class {
1176
+ static {
1177
+ __name(this, "CfgAccounts");
1178
+ }
1179
+ /**
1180
+ * Request OTP code to email.
1181
+ */
1182
+ static cfgAccountsOtpRequestCreate(options) {
1183
+ return (options.client ?? client).post({
1184
+ security: [
1185
+ { name: "X-API-Key", type: "apiKey" },
1186
+ { scheme: "bearer", type: "http" },
1187
+ { name: "Authorization", type: "apiKey" }
1188
+ ],
1189
+ url: "/cfg/accounts/otp/request/",
1190
+ ...options,
1191
+ headers: {
1192
+ "Content-Type": "application/json",
1193
+ ...options.headers
1194
+ }
1195
+ });
1196
+ }
1197
+ /**
1198
+ * Verify OTP code and return JWT tokens or 2FA session.
1199
+ *
1200
+ * If user has 2FA enabled:
1201
+ * - Returns requires_2fa=True with session_id
1202
+ * - Client must complete 2FA verification at /cfg/totp/verify/
1203
+ *
1204
+ * If user has no 2FA:
1205
+ * - Returns JWT tokens and user data directly
1206
+ */
1207
+ static cfgAccountsOtpVerifyCreate(options) {
1208
+ return (options.client ?? client).post({
1209
+ security: [
1210
+ { name: "X-API-Key", type: "apiKey" },
1211
+ { scheme: "bearer", type: "http" },
1212
+ { name: "Authorization", type: "apiKey" }
1213
+ ],
1214
+ url: "/cfg/accounts/otp/verify/",
1215
+ ...options,
1216
+ headers: {
1217
+ "Content-Type": "application/json",
1218
+ ...options.headers
1219
+ }
1220
+ });
1221
+ }
1222
+ };
1223
+ CfgAccountsProfile = class {
1224
+ static {
1225
+ __name(this, "CfgAccountsProfile");
1226
+ }
1227
+ /**
1228
+ * Get current user profile
1229
+ *
1230
+ * Retrieve the current authenticated user's profile information.
1231
+ */
1232
+ static cfgAccountsProfileRetrieve(options) {
1233
+ return (options?.client ?? client).get({
1234
+ security: [{ scheme: "bearer", type: "http" }, {
1235
+ in: "cookie",
1236
+ name: "sessionid",
1237
+ type: "apiKey"
1238
+ }],
1239
+ url: "/cfg/accounts/profile/",
1240
+ ...options
1241
+ });
1242
+ }
1243
+ /**
1244
+ * Upload user avatar
1245
+ *
1246
+ * Upload avatar image for the current authenticated user. Accepts multipart/form-data with 'avatar' field.
1247
+ */
1248
+ static cfgAccountsProfileAvatarCreate(options) {
1249
+ return (options?.client ?? client).post({
1250
+ ...formDataBodySerializer,
1251
+ security: [
1252
+ { name: "X-API-Key", type: "apiKey" },
1253
+ { scheme: "bearer", type: "http" },
1254
+ { name: "Authorization", type: "apiKey" }
1255
+ ],
1256
+ url: "/cfg/accounts/profile/avatar/",
1257
+ ...options,
1258
+ headers: {
1259
+ "Content-Type": null,
1260
+ ...options?.headers
1261
+ }
1262
+ });
1263
+ }
1264
+ /**
1265
+ * Delete user account
1266
+ *
1267
+ *
1268
+ * Permanently delete the current user's account.
1269
+ *
1270
+ * This operation:
1271
+ * - Deactivates the account (user cannot log in)
1272
+ * - Anonymizes personal data (GDPR compliance)
1273
+ * - Frees up the email address for re-registration
1274
+ * - Preserves audit trail
1275
+ *
1276
+ * The account can be restored by an administrator if needed.
1277
+ *
1278
+ */
1279
+ static cfgAccountsProfileDeleteCreate(options) {
1280
+ return (options?.client ?? client).post({
1281
+ security: [{ scheme: "bearer", type: "http" }, {
1282
+ in: "cookie",
1283
+ name: "sessionid",
1284
+ type: "apiKey"
1285
+ }],
1286
+ url: "/cfg/accounts/profile/delete/",
1287
+ ...options
1288
+ });
1289
+ }
1290
+ /**
1291
+ * Partial update user profile
1292
+ *
1293
+ * Partially update the current authenticated user's profile information. Supports avatar upload.
1294
+ */
1295
+ static cfgAccountsProfilePartialPartialUpdate(options) {
1296
+ return (options?.client ?? client).patch({
1297
+ security: [{ scheme: "bearer", type: "http" }, {
1298
+ in: "cookie",
1299
+ name: "sessionid",
1300
+ type: "apiKey"
1301
+ }],
1302
+ url: "/cfg/accounts/profile/partial/",
1303
+ ...options,
1304
+ headers: {
1305
+ "Content-Type": "application/json",
1306
+ ...options?.headers
1307
+ }
1308
+ });
1309
+ }
1310
+ /**
1311
+ * Partial update user profile
1312
+ *
1313
+ * Partially update the current authenticated user's profile information. Supports avatar upload.
1314
+ */
1315
+ static cfgAccountsProfilePartialUpdate(options) {
1316
+ return (options?.client ?? client).put({
1317
+ security: [{ scheme: "bearer", type: "http" }, {
1318
+ in: "cookie",
1319
+ name: "sessionid",
1320
+ type: "apiKey"
1321
+ }],
1322
+ url: "/cfg/accounts/profile/partial/",
1323
+ ...options,
1324
+ headers: {
1325
+ "Content-Type": "application/json",
1326
+ ...options?.headers
1327
+ }
1328
+ });
1329
+ }
1330
+ /**
1331
+ * Update user profile
1332
+ *
1333
+ * Update the current authenticated user's profile information.
1334
+ */
1335
+ static cfgAccountsProfileUpdatePartialUpdate(options) {
1336
+ return (options?.client ?? client).patch({
1337
+ security: [{ scheme: "bearer", type: "http" }, {
1338
+ in: "cookie",
1339
+ name: "sessionid",
1340
+ type: "apiKey"
1341
+ }],
1342
+ url: "/cfg/accounts/profile/update/",
1343
+ ...options,
1344
+ headers: {
1345
+ "Content-Type": "application/json",
1346
+ ...options?.headers
1347
+ }
1348
+ });
1349
+ }
1350
+ /**
1351
+ * Update user profile
1352
+ *
1353
+ * Update the current authenticated user's profile information.
1354
+ */
1355
+ static cfgAccountsProfileUpdateUpdate(options) {
1356
+ return (options?.client ?? client).put({
1357
+ security: [{ scheme: "bearer", type: "http" }, {
1358
+ in: "cookie",
1359
+ name: "sessionid",
1360
+ type: "apiKey"
1361
+ }],
1362
+ url: "/cfg/accounts/profile/update/",
1363
+ ...options,
1364
+ headers: {
1365
+ "Content-Type": "application/json",
1366
+ ...options?.headers
1367
+ }
1368
+ });
1369
+ }
1370
+ };
1371
+ CfgAccountsAuth = class {
1372
+ static {
1373
+ __name(this, "CfgAccountsAuth");
1374
+ }
1375
+ /**
1376
+ * Revoke a refresh token (logout).
1377
+ *
1378
+ * Blacklists the posted refresh token so it can never mint another access
1379
+ * token. Called best-effort by the client's logout — without it, "logout"
1380
+ * is purely client-side and a stolen refresh token survives until expiry.
1381
+ */
1382
+ static cfgAccountsTokenBlacklistCreate(options) {
1383
+ return (options.client ?? client).post({
1384
+ url: "/cfg/accounts/token/blacklist/",
1385
+ ...options,
1386
+ headers: {
1387
+ "Content-Type": "application/json",
1388
+ ...options.headers
1389
+ }
1390
+ });
1391
+ }
1392
+ /**
1393
+ * Refresh JWT token.
1394
+ *
1395
+ * DPoP-aware: when the incoming refresh token is key-bound (`cnf.jkt`), the
1396
+ * rotated access/refresh in the response are re-stamped with the same `cnf`
1397
+ * (stock SimpleJWT drops it from the derived access), and a matching DPoP
1398
+ * proof is required on the refresh request — so a stolen refresh token can't
1399
+ * be used to mint fresh tokens.
1400
+ */
1401
+ static cfgAccountsTokenRefreshCreate(options) {
1402
+ return (options.client ?? client).post({
1403
+ url: "/cfg/accounts/token/refresh/",
1404
+ ...options,
1405
+ headers: {
1406
+ "Content-Type": "application/json",
1407
+ ...options.headers
1408
+ }
1409
+ });
1410
+ }
1411
+ };
1412
+ CfgCentrifugo = class {
1413
+ static {
1414
+ __name(this, "CfgCentrifugo");
1415
+ }
1416
+ /**
1417
+ * Get Centrifugo connection token
1418
+ *
1419
+ * Generate JWT token for WebSocket connection to Centrifugo. Token includes user's allowed channels based on their permissions. Requires authentication.
1420
+ */
1421
+ static cfgCentrifugoAuthTokenRetrieve(options) {
1422
+ return (options?.client ?? client).get({
1423
+ security: [
1424
+ { name: "X-API-Key", type: "apiKey" },
1425
+ { scheme: "bearer", type: "http" },
1426
+ { name: "Authorization", type: "apiKey" }
1427
+ ],
1428
+ url: "/cfg/centrifugo/auth/token/",
1429
+ ...options
1430
+ });
1431
+ }
1432
+ };
1433
+ CfgTotpBackupCodes = class {
1434
+ static {
1435
+ __name(this, "CfgTotpBackupCodes");
1436
+ }
1437
+ /**
1438
+ * Get backup codes status for user.
1439
+ */
1440
+ static cfgTotpBackupCodesRetrieve(options) {
1441
+ return (options?.client ?? client).get({
1442
+ security: [
1443
+ { name: "X-API-Key", type: "apiKey" },
1444
+ { scheme: "bearer", type: "http" },
1445
+ { name: "Authorization", type: "apiKey" }
1446
+ ],
1447
+ url: "/cfg/totp/backup-codes/",
1448
+ ...options
1449
+ });
1450
+ }
1451
+ /**
1452
+ * Regenerate backup codes.
1453
+ *
1454
+ * Requires TOTP code for verification.
1455
+ * Invalidates all existing codes.
1456
+ */
1457
+ static cfgTotpBackupCodesRegenerateCreate(options) {
1458
+ return (options.client ?? client).post({
1459
+ security: [
1460
+ { name: "X-API-Key", type: "apiKey" },
1461
+ { scheme: "bearer", type: "http" },
1462
+ { name: "Authorization", type: "apiKey" }
1463
+ ],
1464
+ url: "/cfg/totp/backup-codes/regenerate/",
1465
+ ...options,
1466
+ headers: {
1467
+ "Content-Type": "application/json",
1468
+ ...options.headers
1469
+ }
1470
+ });
1471
+ }
1472
+ };
1473
+ CfgTotp = class {
1474
+ static {
1475
+ __name(this, "CfgTotp");
1476
+ }
1477
+ /**
1478
+ * List all TOTP devices for user.
1479
+ */
1480
+ static cfgTotpDevicesRetrieve(options) {
1481
+ return (options?.client ?? client).get({
1482
+ security: [
1483
+ { name: "X-API-Key", type: "apiKey" },
1484
+ { scheme: "bearer", type: "http" },
1485
+ { name: "Authorization", type: "apiKey" }
1486
+ ],
1487
+ url: "/cfg/totp/devices/",
1488
+ ...options
1489
+ });
1490
+ }
1491
+ /**
1492
+ * Delete a TOTP device.
1493
+ *
1494
+ * Requires verification code if removing the last/primary device.
1495
+ */
1496
+ static cfgTotpDevicesDestroy(options) {
1497
+ return (options.client ?? client).delete({
1498
+ security: [
1499
+ { name: "X-API-Key", type: "apiKey" },
1500
+ { scheme: "bearer", type: "http" },
1501
+ { name: "Authorization", type: "apiKey" }
1502
+ ],
1503
+ url: "/cfg/totp/devices/{id}/",
1504
+ ...options
1505
+ });
1506
+ }
1507
+ /**
1508
+ * Completely disable 2FA for account.
1509
+ *
1510
+ * Requires verification code.
1511
+ */
1512
+ static cfgTotpDisableCreate(options) {
1513
+ return (options.client ?? client).post({
1514
+ security: [
1515
+ { name: "X-API-Key", type: "apiKey" },
1516
+ { scheme: "bearer", type: "http" },
1517
+ { name: "Authorization", type: "apiKey" }
1518
+ ],
1519
+ url: "/cfg/totp/disable/",
1520
+ ...options,
1521
+ headers: {
1522
+ "Content-Type": "application/json",
1523
+ ...options.headers
1524
+ }
1525
+ });
1526
+ }
1527
+ };
1528
+ CfgTotpSetup = class {
1529
+ static {
1530
+ __name(this, "CfgTotpSetup");
1531
+ }
1532
+ /**
1533
+ * Start 2FA setup process.
1534
+ *
1535
+ * Creates a new TOTP device and returns QR code for scanning.
1536
+ */
1537
+ static cfgTotpSetupCreate(options) {
1538
+ return (options?.client ?? client).post({
1539
+ security: [
1540
+ { name: "X-API-Key", type: "apiKey" },
1541
+ { scheme: "bearer", type: "http" },
1542
+ { name: "Authorization", type: "apiKey" }
1543
+ ],
1544
+ url: "/cfg/totp/setup/",
1545
+ ...options,
1546
+ headers: {
1547
+ "Content-Type": "application/json",
1548
+ ...options?.headers
1549
+ }
1550
+ });
1551
+ }
1552
+ /**
1553
+ * Confirm 2FA setup with first valid code.
1554
+ *
1555
+ * Activates the device and generates backup codes.
1556
+ */
1557
+ static cfgTotpSetupConfirmCreate(options) {
1558
+ return (options.client ?? client).post({
1559
+ security: [
1560
+ { name: "X-API-Key", type: "apiKey" },
1561
+ { scheme: "bearer", type: "http" },
1562
+ { name: "Authorization", type: "apiKey" }
1563
+ ],
1564
+ url: "/cfg/totp/setup/confirm/",
1565
+ ...options,
1566
+ headers: {
1567
+ "Content-Type": "application/json",
1568
+ ...options.headers
1569
+ }
1570
+ });
1571
+ }
1572
+ };
1573
+ CfgTotpVerify = class {
1574
+ static {
1575
+ __name(this, "CfgTotpVerify");
1576
+ }
1577
+ /**
1578
+ * Verify TOTP code for 2FA session.
1579
+ *
1580
+ * Completes authentication and returns JWT tokens on success.
1581
+ */
1582
+ static cfgTotpVerifyCreate(options) {
1583
+ return (options.client ?? client).post({
1584
+ security: [
1585
+ { name: "X-API-Key", type: "apiKey" },
1586
+ { scheme: "bearer", type: "http" },
1587
+ { name: "Authorization", type: "apiKey" }
1588
+ ],
1589
+ url: "/cfg/totp/verify/",
1590
+ ...options,
1591
+ headers: {
1592
+ "Content-Type": "application/json",
1593
+ ...options.headers
1594
+ }
1595
+ });
1596
+ }
1597
+ /**
1598
+ * Verify backup recovery code for 2FA session.
1599
+ *
1600
+ * Alternative verification method when TOTP device unavailable.
1601
+ */
1602
+ static cfgTotpVerifyBackupCreate(options) {
1603
+ return (options.client ?? client).post({
1604
+ security: [
1605
+ { name: "X-API-Key", type: "apiKey" },
1606
+ { scheme: "bearer", type: "http" },
1607
+ { name: "Authorization", type: "apiKey" }
1608
+ ],
1609
+ url: "/cfg/totp/verify/backup/",
1610
+ ...options,
1611
+ headers: {
1612
+ "Content-Type": "application/json",
1613
+ ...options.headers
1614
+ }
1615
+ });
1616
+ }
1617
+ };
1618
+ }
1619
+ });
1620
+
1621
+ // src/_api/generated/helpers/auth.ts
145
1622
  function detectLocale() {
146
1623
  try {
147
1624
  if (typeof document !== "undefined") {
@@ -155,7 +1632,6 @@ function detectLocale() {
155
1632
  }
156
1633
  return null;
157
1634
  }
158
- __name(detectLocale, "detectLocale");
159
1635
  function defaultBaseUrl() {
160
1636
  if (typeof window !== "undefined") {
161
1637
  try {
@@ -167,1807 +1643,683 @@ function defaultBaseUrl() {
167
1643
  }
168
1644
  } catch {
169
1645
  }
170
- return "";
171
- }
172
- try {
173
- if (typeof process !== "undefined" && process.env) {
174
- if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
175
- return process.env.NEXT_PUBLIC_API_URL || "";
176
- }
177
- } catch {
178
- }
179
- return "";
180
- }
181
- __name(defaultBaseUrl, "defaultBaseUrl");
182
- function defaultApiKey() {
183
- try {
184
- if (typeof process !== "undefined" && process.env?.NEXT_PUBLIC_API_KEY) {
185
- return process.env.NEXT_PUBLIC_API_KEY;
186
- }
187
- } catch {
188
- }
189
- return null;
190
- }
191
- __name(defaultApiKey, "defaultApiKey");
192
- var _localeOverride = null;
193
- var _apiKeyOverride = null;
194
- var _baseUrlOverride = null;
195
- var _withCredentials = true;
196
- var _onUnauthorized = null;
197
- var _refreshHandler = null;
198
- var _refreshInflight = null;
199
- var RETRY_MARKER = "X-Auth-Retry";
200
- var _client = null;
201
- function pushClientConfig() {
202
- if (!_client) return;
203
- _client.setConfig({
204
- baseUrl: auth.getBaseUrl(),
205
- credentials: _withCredentials ? "include" : "same-origin"
206
- });
207
- }
208
- __name(pushClientConfig, "pushClientConfig");
209
- var auth = {
210
- // ── Storage mode ──────────────────────────────────────────────────
211
- getStorageMode() {
212
- return _storageMode;
213
- },
214
- setStorageMode(mode) {
215
- _storageMode = mode;
216
- _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
217
- },
218
- // ── Bearer token ──────────────────────────────────────────────────
219
- getToken() {
220
- return _storage.get(ACCESS_KEY);
221
- },
222
- setToken(token) {
223
- _storage.set(ACCESS_KEY, token);
224
- },
225
- getRefreshToken() {
226
- return _storage.get(REFRESH_KEY);
227
- },
228
- setRefreshToken(token) {
229
- _storage.set(REFRESH_KEY, token);
230
- },
231
- clearTokens() {
232
- _storage.set(ACCESS_KEY, null);
233
- _storage.set(REFRESH_KEY, null);
234
- },
235
- isAuthenticated() {
236
- return _storage.get(ACCESS_KEY) !== null;
237
- },
238
- // ── API key ───────────────────────────────────────────────────────
239
- getApiKey() {
240
- return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
241
- },
242
- setApiKey(key) {
243
- _apiKeyOverride = key;
244
- },
245
- setApiKeyPersist(key) {
246
- _apiKeyOverride = key;
247
- _storage.set(API_KEY_KEY, key);
248
- },
249
- clearApiKey() {
250
- _apiKeyOverride = null;
251
- _storage.set(API_KEY_KEY, null);
252
- },
253
- // ── Locale ────────────────────────────────────────────────────────
254
- getLocale() {
255
- return _localeOverride ?? detectLocale();
256
- },
257
- setLocale(locale) {
258
- _localeOverride = locale;
259
- },
260
- // ── Base URL ──────────────────────────────────────────────────────
261
- getBaseUrl() {
262
- const url = _baseUrlOverride ?? defaultBaseUrl();
263
- return url.replace(/\/$/, "");
264
- },
265
- setBaseUrl(url) {
266
- _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
267
- pushClientConfig();
268
- },
269
- // ── Credentials toggle ────────────────────────────────────────────
270
- getWithCredentials() {
271
- return _withCredentials;
272
- },
273
- setWithCredentials(value) {
274
- _withCredentials = value;
275
- pushClientConfig();
276
- },
277
- // ── 401 handler ───────────────────────────────────────────────────
278
- /**
279
- * Fired when the server returns 401 AND no refresh path recovers it
280
- * (no refresh token, no refresh handler, refresh failed, or retry
281
- * still 401). The app should clear local state and redirect to login.
282
- *
283
- * NOT fired for 401 that gets transparently recovered by the refresh
284
- * handler — those are invisible to callers.
285
- */
286
- onUnauthorized(cb) {
287
- _onUnauthorized = cb;
288
- },
289
- /**
290
- * Register the refresh strategy. The handler receives the current
291
- * refresh token and must call your refresh endpoint, returning
292
- * `{ access, refresh? }` on success or `null` on failure.
293
- *
294
- * @example
295
- * auth.setRefreshHandler(async (refresh) => {
296
- * const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
297
- * return data ? { access: data.access, refresh: data.refresh } : null;
298
- * });
299
- */
300
- setRefreshHandler(fn) {
301
- _refreshHandler = fn;
302
- },
303
- /**
304
- * Proactively run the registered refresh handler right now, reusing the
305
- * SAME single-flight promise as the 401-recovery interceptor. Callers
306
- * (e.g. an expiry timer / focus / reconnect) get token rotation,
307
- * de-duplication and rotated-token persistence for free — they must NOT
308
- * re-implement any of it. Returns the fresh access token, or null if
309
- * there is no handler / no refresh token / the refresh failed.
310
- */
311
- refreshNow() {
312
- return tryRefresh();
313
- }
314
- };
315
- async function tryRefresh() {
316
- if (_refreshInflight) return _refreshInflight;
317
- if (!_refreshHandler) return null;
318
- const refresh = auth.getRefreshToken();
319
- if (!refresh) return null;
320
- _refreshInflight = (async () => {
321
- try {
322
- const result = await _refreshHandler(refresh);
323
- if (!result?.access) return null;
324
- auth.setToken(result.access);
325
- if (result.refresh) auth.setRefreshToken(result.refresh);
326
- return result.access;
327
- } catch {
328
- return null;
329
- } finally {
330
- _refreshInflight = null;
331
- }
332
- })();
333
- return _refreshInflight;
334
- }
335
- __name(tryRefresh, "tryRefresh");
336
- function dpopEnabled() {
337
- try {
338
- return typeof process !== "undefined" && process.env?.NEXT_PUBLIC_DPOP_ENABLED === "true";
339
- } catch {
340
- return false;
341
- }
342
- }
343
- __name(dpopEnabled, "dpopEnabled");
344
- var _DPOP_DB = "cfg-auth";
345
- var _DPOP_STORE = "keys";
346
- var _DPOP_KEY_ID = "dpop-ec-p256";
347
- function _idbOpen() {
348
- return new Promise((resolve, reject) => {
349
- const req = indexedDB.open(_DPOP_DB, 1);
350
- req.onupgradeneeded = () => req.result.createObjectStore(_DPOP_STORE);
351
- req.onsuccess = () => resolve(req.result);
352
- req.onerror = () => reject(req.error);
353
- });
354
- }
355
- __name(_idbOpen, "_idbOpen");
356
- function _idbGet(key) {
357
- return _idbOpen().then((db) => new Promise((resolve, reject) => {
358
- const tx = db.transaction(_DPOP_STORE, "readonly");
359
- const req = tx.objectStore(_DPOP_STORE).get(key);
360
- req.onsuccess = () => resolve(req.result);
361
- req.onerror = () => reject(req.error);
362
- }));
363
- }
364
- __name(_idbGet, "_idbGet");
365
- function _idbPut(key, value) {
366
- return _idbOpen().then((db) => new Promise((resolve, reject) => {
367
- const tx = db.transaction(_DPOP_STORE, "readwrite");
368
- tx.objectStore(_DPOP_STORE).put(value, key);
369
- tx.oncomplete = () => resolve();
370
- tx.onerror = () => reject(tx.error);
371
- }));
372
- }
373
- __name(_idbPut, "_idbPut");
374
- var _dpopKeyPromise = null;
375
- function _getDpopKeyPair() {
376
- if (_dpopKeyPromise) return _dpopKeyPromise;
377
- _dpopKeyPromise = (async () => {
378
- const existing = await _idbGet(_DPOP_KEY_ID).catch(() => void 0);
379
- if (existing) return existing;
380
- const pair = await crypto.subtle.generateKey(
381
- { name: "ECDSA", namedCurve: "P-256" },
382
- false,
383
- // extractable:false — JS can sign but never export the private key
384
- ["sign"]
385
- );
386
- await _idbPut(_DPOP_KEY_ID, pair).catch(() => {
387
- });
388
- return pair;
389
- })();
390
- return _dpopKeyPromise;
391
- }
392
- __name(_getDpopKeyPair, "_getDpopKeyPair");
393
- function _b64urlFromBytes(bytes) {
394
- const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
395
- let s = "";
396
- for (let i = 0; i < arr.length; i++) s += String.fromCharCode(arr[i]);
397
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
398
- }
399
- __name(_b64urlFromBytes, "_b64urlFromBytes");
400
- function _b64urlFromString(str) {
401
- return _b64urlFromBytes(new TextEncoder().encode(str));
402
- }
403
- __name(_b64urlFromString, "_b64urlFromString");
404
- async function _publicJwk(pub) {
405
- const jwk = await crypto.subtle.exportKey("jwk", pub);
406
- return { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
407
- }
408
- __name(_publicJwk, "_publicJwk");
409
- async function _makeDpopProof(method, url) {
410
- try {
411
- const pair = await _getDpopKeyPair();
412
- const jwk = await _publicJwk(pair.publicKey);
413
- const header = { typ: "dpop+jwt", alg: "ES256", jwk };
414
- const htu = url.split("#")[0].split("?")[0];
415
- const jti = crypto.randomUUID && crypto.randomUUID() || _b64urlFromBytes(crypto.getRandomValues(new Uint8Array(16)));
416
- const payload = { htm: method.toUpperCase(), htu, iat: Math.floor(Date.now() / 1e3), jti };
417
- const signingInput = `${_b64urlFromString(JSON.stringify(header))}.${_b64urlFromString(JSON.stringify(payload))}`;
418
- const sig = await crypto.subtle.sign(
419
- { name: "ECDSA", hash: "SHA-256" },
420
- pair.privateKey,
421
- new TextEncoder().encode(signingInput)
422
- );
423
- return `${signingInput}.${_b64urlFromBytes(sig)}`;
424
- } catch {
425
- return null;
426
- }
427
- }
428
- __name(_makeDpopProof, "_makeDpopProof");
429
- function installAuthOnClient(client2) {
430
- if (_client) return;
431
- _client = client2;
432
- client2.setConfig({
433
- baseUrl: auth.getBaseUrl(),
434
- credentials: _withCredentials ? "include" : "same-origin"
435
- });
436
- client2.interceptors.request.use(async (request) => {
437
- const token = auth.getToken();
438
- if (token) request.headers.set("Authorization", `Bearer ${token}`);
439
- const locale = auth.getLocale();
440
- if (locale) request.headers.set("Accept-Language", locale);
441
- const apiKey = auth.getApiKey();
442
- if (apiKey && !request.headers.has("X-API-Key")) request.headers.set("X-API-Key", apiKey);
443
- try {
444
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
445
- if (tz) request.headers.set("X-Timezone", tz);
446
- } catch {
447
- }
448
- request.headers.set("X-Client-Time", (/* @__PURE__ */ new Date()).toISOString());
449
- if (dpopEnabled() && typeof window !== "undefined") {
450
- const proof = await _makeDpopProof(request.method, request.url);
451
- if (proof) request.headers.set("DPoP", proof);
452
- }
453
- return request;
454
- });
455
- client2.interceptors.error.use((err, res, req) => {
456
- if (err instanceof APIError) return err;
457
- const url = req?.url ?? "";
458
- const status = res?.status ?? 0;
459
- const statusText = res?.statusText ?? "";
460
- return new APIError(status, statusText, err, url);
461
- });
462
- client2.interceptors.response.use(async (response, request) => {
463
- if (response.status !== 401) return response;
464
- if (request.headers.get(RETRY_MARKER)) {
465
- if (_onUnauthorized) {
466
- try {
467
- _onUnauthorized(response);
468
- } catch {
469
- }
470
- }
471
- return response;
472
- }
473
- const newToken = await tryRefresh();
474
- if (!newToken) {
475
- if (_onUnauthorized) {
476
- try {
477
- _onUnauthorized(response);
478
- } catch {
479
- }
480
- }
481
- return response;
482
- }
483
- const retry = request.clone();
484
- retry.headers.set("Authorization", `Bearer ${newToken}`);
485
- retry.headers.set(RETRY_MARKER, "1");
486
- if (dpopEnabled() && typeof window !== "undefined") {
487
- const proof = await _makeDpopProof(retry.method, retry.url);
488
- if (proof) retry.headers.set("DPoP", proof);
489
- }
490
- try {
491
- const retried = await fetch(retry);
492
- if (retried.status === 401 && _onUnauthorized) {
493
- try {
494
- _onUnauthorized(retried);
495
- } catch {
496
- }
497
- }
498
- return retried;
499
- } catch {
500
- if (_onUnauthorized) {
501
- try {
502
- _onUnauthorized(response);
503
- } catch {
504
- }
505
- }
506
- return response;
507
- }
508
- });
509
- }
510
- __name(installAuthOnClient, "installAuthOnClient");
511
-
512
- // src/_api/generated/helpers/logger.ts
513
- var import_consola = require("consola");
514
- var DEFAULT_CONFIG = {
515
- enabled: typeof process !== "undefined" && process.env.NODE_ENV !== "production",
516
- logRequests: true,
517
- logResponses: true,
518
- logErrors: true,
519
- logBodies: true,
520
- logHeaders: false
521
- };
522
- var SENSITIVE_HEADERS = [
523
- "authorization",
524
- "cookie",
525
- "set-cookie",
526
- "x-api-key",
527
- "x-csrf-token"
528
- ];
529
- var APILogger = class {
530
- static {
531
- __name(this, "APILogger");
532
- }
533
- config;
534
- consola;
535
- constructor(config = {}) {
536
- this.config = { ...DEFAULT_CONFIG, ...config };
537
- this.consola = config.consola || (0, import_consola.createConsola)({
538
- level: this.config.enabled ? 4 : 0
539
- });
540
- }
541
- enable() {
542
- this.config.enabled = true;
543
- }
544
- disable() {
545
- this.config.enabled = false;
546
- }
547
- setConfig(config) {
548
- this.config = { ...this.config, ...config };
549
- }
550
- filterHeaders(headers) {
551
- if (!headers) return {};
552
- const filtered = {};
553
- Object.keys(headers).forEach((key) => {
554
- filtered[key] = SENSITIVE_HEADERS.includes(key.toLowerCase()) ? "***" : headers[key] || "";
555
- });
556
- return filtered;
557
- }
558
- logRequest(request) {
559
- if (!this.config.enabled || !this.config.logRequests) return;
560
- const { method, url, headers, body } = request;
561
- this.consola.start(`${method} ${url}`);
562
- if (this.config.logHeaders && headers) this.consola.debug("Headers:", this.filterHeaders(headers));
563
- if (this.config.logBodies && body) this.consola.debug("Body:", body);
564
- }
565
- logResponse(request, response) {
566
- if (!this.config.enabled || !this.config.logResponses) return;
567
- const { method, url } = request;
568
- const { status, statusText, data, duration } = response;
569
- this.consola.success(`${method} ${url} ${status} ${statusText} (${duration}ms)`);
570
- if (this.config.logBodies && data) this.consola.debug("Response:", data);
571
- }
572
- logError(request, error) {
573
- if (!this.config.enabled || !this.config.logErrors) return;
574
- const { method, url } = request;
575
- const { message, statusCode, fieldErrors, duration } = error;
576
- this.consola.error(`${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`);
577
- this.consola.error("Message:", message);
578
- if (fieldErrors && Object.keys(fieldErrors).length > 0) {
579
- this.consola.error("Field Errors:");
580
- Object.entries(fieldErrors).forEach(([field, errors]) => {
581
- errors.forEach((err) => this.consola.error(` \u2022 ${field}: ${err}`));
582
- });
583
- }
584
- }
585
- info(message, ...args) {
586
- if (this.config.enabled) this.consola.info(message, ...args);
587
- }
588
- warn(message, ...args) {
589
- if (this.config.enabled) this.consola.warn(message, ...args);
590
- }
591
- error(message, ...args) {
592
- if (this.config.enabled) this.consola.error(message, ...args);
593
- }
594
- debug(message, ...args) {
595
- if (this.config.enabled) this.consola.debug(message, ...args);
596
- }
597
- success(message, ...args) {
598
- if (this.config.enabled) this.consola.success(message, ...args);
599
- }
600
- withTag(tag) {
601
- return this.consola.withTag(tag);
602
- }
603
- };
604
- var defaultLogger = new APILogger();
605
-
606
- // src/_api/generated/core/bodySerializer.gen.ts
607
- var serializeFormDataPair = /* @__PURE__ */ __name((data, key, value) => {
608
- if (typeof value === "string" || value instanceof Blob) {
609
- data.append(key, value);
610
- } else if (value instanceof Date) {
611
- data.append(key, value.toISOString());
612
- } else {
613
- data.append(key, JSON.stringify(value));
614
- }
615
- }, "serializeFormDataPair");
616
- var formDataBodySerializer = {
617
- bodySerializer: /* @__PURE__ */ __name((body) => {
618
- const data = new FormData();
619
- Object.entries(body).forEach(([key, value]) => {
620
- if (value === void 0 || value === null) {
621
- return;
622
- }
623
- if (Array.isArray(value)) {
624
- value.forEach((v) => serializeFormDataPair(data, key, v));
625
- } else {
626
- serializeFormDataPair(data, key, value);
627
- }
628
- });
629
- return data;
630
- }, "bodySerializer")
631
- };
632
- var jsonBodySerializer = {
633
- bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
634
- };
635
-
636
- // src/_api/generated/core/params.gen.ts
637
- var extraPrefixesMap = {
638
- $body_: "body",
639
- $headers_: "headers",
640
- $path_: "path",
641
- $query_: "query"
642
- };
643
- var extraPrefixes = Object.entries(extraPrefixesMap);
644
-
645
- // src/_api/generated/core/serverSentEvents.gen.ts
646
- function createSseClient({
647
- onRequest,
648
- onSseError,
649
- onSseEvent,
650
- responseTransformer,
651
- responseValidator,
652
- sseDefaultRetryDelay,
653
- sseMaxRetryAttempts,
654
- sseMaxRetryDelay,
655
- sseSleepFn,
656
- url,
657
- ...options
658
- }) {
659
- let lastEventId;
660
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
661
- const createStream = /* @__PURE__ */ __name(async function* () {
662
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
663
- let attempt = 0;
664
- const signal = options.signal ?? new AbortController().signal;
665
- while (true) {
666
- if (signal.aborted) break;
667
- attempt++;
668
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
669
- if (lastEventId !== void 0) {
670
- headers.set("Last-Event-ID", lastEventId);
671
- }
672
- try {
673
- const requestInit = {
674
- redirect: "follow",
675
- ...options,
676
- body: options.serializedBody,
677
- headers,
678
- signal
679
- };
680
- let request = new Request(url, requestInit);
681
- if (onRequest) {
682
- request = await onRequest(url, requestInit);
683
- }
684
- const _fetch = options.fetch ?? globalThis.fetch;
685
- const response = await _fetch(request);
686
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
687
- if (!response.body) throw new Error("No body in SSE response");
688
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
689
- let buffer = "";
690
- const abortHandler = /* @__PURE__ */ __name(() => {
691
- try {
692
- reader.cancel();
693
- } catch {
694
- }
695
- }, "abortHandler");
696
- signal.addEventListener("abort", abortHandler);
697
- try {
698
- while (true) {
699
- const { done, value } = await reader.read();
700
- if (done) break;
701
- buffer += value;
702
- buffer = buffer.replace(/\r\n?/g, "\n");
703
- const chunks = buffer.split("\n\n");
704
- buffer = chunks.pop() ?? "";
705
- for (const chunk of chunks) {
706
- const lines = chunk.split("\n");
707
- const dataLines = [];
708
- let eventName;
709
- for (const line of lines) {
710
- if (line.startsWith("data:")) {
711
- dataLines.push(line.replace(/^data:\s*/, ""));
712
- } else if (line.startsWith("event:")) {
713
- eventName = line.replace(/^event:\s*/, "");
714
- } else if (line.startsWith("id:")) {
715
- lastEventId = line.replace(/^id:\s*/, "");
716
- } else if (line.startsWith("retry:")) {
717
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
718
- if (!Number.isNaN(parsed)) {
719
- retryDelay = parsed;
720
- }
721
- }
722
- }
723
- let data;
724
- let parsedJson = false;
725
- if (dataLines.length) {
726
- const rawData = dataLines.join("\n");
727
- try {
728
- data = JSON.parse(rawData);
729
- parsedJson = true;
730
- } catch {
731
- data = rawData;
732
- }
733
- }
734
- if (parsedJson) {
735
- if (responseValidator) {
736
- await responseValidator(data);
737
- }
738
- if (responseTransformer) {
739
- data = await responseTransformer(data);
740
- }
741
- }
742
- onSseEvent?.({
743
- data,
744
- event: eventName,
745
- id: lastEventId,
746
- retry: retryDelay
747
- });
748
- if (dataLines.length) {
749
- yield data;
750
- }
751
- }
752
- }
753
- } finally {
754
- signal.removeEventListener("abort", abortHandler);
755
- reader.releaseLock();
756
- }
757
- break;
758
- } catch (error) {
759
- onSseError?.(error);
760
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
761
- break;
762
- }
763
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
764
- await sleep(backoff);
765
- }
766
- }
767
- }, "createStream");
768
- const stream = createStream();
769
- return { stream };
770
- }
771
- __name(createSseClient, "createSseClient");
772
-
773
- // src/_api/generated/core/pathSerializer.gen.ts
774
- var separatorArrayExplode = /* @__PURE__ */ __name((style) => {
775
- switch (style) {
776
- case "label":
777
- return ".";
778
- case "matrix":
779
- return ";";
780
- case "simple":
781
- return ",";
782
- default:
783
- return "&";
784
- }
785
- }, "separatorArrayExplode");
786
- var separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
787
- switch (style) {
788
- case "form":
789
- return ",";
790
- case "pipeDelimited":
791
- return "|";
792
- case "spaceDelimited":
793
- return "%20";
794
- default:
795
- return ",";
796
- }
797
- }, "separatorArrayNoExplode");
798
- var separatorObjectExplode = /* @__PURE__ */ __name((style) => {
799
- switch (style) {
800
- case "label":
801
- return ".";
802
- case "matrix":
803
- return ";";
804
- case "simple":
805
- return ",";
806
- default:
807
- return "&";
808
- }
809
- }, "separatorObjectExplode");
810
- var serializeArrayParam = /* @__PURE__ */ __name(({
811
- allowReserved,
812
- explode,
813
- name,
814
- style,
815
- value
816
- }) => {
817
- if (!explode) {
818
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
819
- switch (style) {
820
- case "label":
821
- return `.${joinedValues2}`;
822
- case "matrix":
823
- return `;${name}=${joinedValues2}`;
824
- case "simple":
825
- return joinedValues2;
826
- default:
827
- return `${name}=${joinedValues2}`;
828
- }
829
- }
830
- const separator = separatorArrayExplode(style);
831
- const joinedValues = value.map((v) => {
832
- if (style === "label" || style === "simple") {
833
- return allowReserved ? v : encodeURIComponent(v);
834
- }
835
- return serializePrimitiveParam({
836
- allowReserved,
837
- name,
838
- value: v
839
- });
840
- }).join(separator);
841
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
842
- }, "serializeArrayParam");
843
- var serializePrimitiveParam = /* @__PURE__ */ __name(({
844
- allowReserved,
845
- name,
846
- value
847
- }) => {
848
- if (value === void 0 || value === null) {
849
- return "";
850
- }
851
- if (typeof value === "object") {
852
- throw new Error(
853
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
854
- );
855
- }
856
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
857
- }, "serializePrimitiveParam");
858
- var serializeObjectParam = /* @__PURE__ */ __name(({
859
- allowReserved,
860
- explode,
861
- name,
862
- style,
863
- value,
864
- valueOnly
865
- }) => {
866
- if (value instanceof Date) {
867
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
868
- }
869
- if (style !== "deepObject" && !explode) {
870
- let values = [];
871
- Object.entries(value).forEach(([key, v]) => {
872
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
873
- });
874
- const joinedValues2 = values.join(",");
875
- switch (style) {
876
- case "form":
877
- return `${name}=${joinedValues2}`;
878
- case "label":
879
- return `.${joinedValues2}`;
880
- case "matrix":
881
- return `;${name}=${joinedValues2}`;
882
- default:
883
- return joinedValues2;
884
- }
885
- }
886
- const separator = separatorObjectExplode(style);
887
- const joinedValues = Object.entries(value).map(
888
- ([key, v]) => serializePrimitiveParam({
889
- allowReserved,
890
- name: style === "deepObject" ? `${name}[${key}]` : key,
891
- value: v
892
- })
893
- ).join(separator);
894
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
895
- }, "serializeObjectParam");
896
-
897
- // src/_api/generated/core/utils.gen.ts
898
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
899
- var defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
900
- let url = _url;
901
- const matches = _url.match(PATH_PARAM_RE);
902
- if (matches) {
903
- for (const match of matches) {
904
- let explode = false;
905
- let name = match.substring(1, match.length - 1);
906
- let style = "simple";
907
- if (name.endsWith("*")) {
908
- explode = true;
909
- name = name.substring(0, name.length - 1);
910
- }
911
- if (name.startsWith(".")) {
912
- name = name.substring(1);
913
- style = "label";
914
- } else if (name.startsWith(";")) {
915
- name = name.substring(1);
916
- style = "matrix";
917
- }
918
- const value = path[name];
919
- if (value === void 0 || value === null) {
920
- continue;
921
- }
922
- if (Array.isArray(value)) {
923
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
924
- continue;
925
- }
926
- if (typeof value === "object") {
927
- url = url.replace(
928
- match,
929
- serializeObjectParam({
930
- explode,
931
- name,
932
- style,
933
- value,
934
- valueOnly: true
935
- })
936
- );
937
- continue;
938
- }
939
- if (style === "matrix") {
940
- url = url.replace(
941
- match,
942
- `;${serializePrimitiveParam({
943
- name,
944
- value
945
- })}`
946
- );
947
- continue;
948
- }
949
- const replaceValue = encodeURIComponent(
950
- style === "label" ? `.${value}` : value
951
- );
952
- url = url.replace(match, replaceValue);
953
- }
954
- }
955
- return url;
956
- }, "defaultPathSerializer");
957
- var getUrl = /* @__PURE__ */ __name(({
958
- baseUrl,
959
- path,
960
- query,
961
- querySerializer,
962
- url: _url
963
- }) => {
964
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
965
- let url = (baseUrl ?? "") + pathUrl;
966
- if (path) {
967
- url = defaultPathSerializer({ path, url });
968
- }
969
- let search = query ? querySerializer(query) : "";
970
- if (search.startsWith("?")) {
971
- search = search.substring(1);
972
- }
973
- if (search) {
974
- url += `?${search}`;
975
- }
976
- return url;
977
- }, "getUrl");
978
- function getValidRequestBody(options) {
979
- const hasBody = options.body !== void 0;
980
- const isSerializedBody = hasBody && options.bodySerializer;
981
- if (isSerializedBody) {
982
- if ("serializedBody" in options) {
983
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
984
- return hasSerializedBody ? options.serializedBody : null;
985
- }
986
- return options.body !== "" ? options.body : null;
1646
+ return "";
987
1647
  }
988
- if (hasBody) {
989
- return options.body;
1648
+ try {
1649
+ if (typeof process !== "undefined" && process.env) {
1650
+ if (process.env.NEXT_PUBLIC_STATIC_BUILD === "true") return "";
1651
+ return process.env.NEXT_PUBLIC_API_URL || "";
1652
+ }
1653
+ } catch {
990
1654
  }
991
- return void 0;
1655
+ return "";
992
1656
  }
993
- __name(getValidRequestBody, "getValidRequestBody");
994
-
995
- // src/_api/generated/core/auth.gen.ts
996
- var getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
997
- const token = typeof callback === "function" ? await callback(auth2) : callback;
998
- if (!token) {
999
- return;
1000
- }
1001
- if (auth2.scheme === "bearer") {
1002
- return `Bearer ${token}`;
1003
- }
1004
- if (auth2.scheme === "basic") {
1005
- return `Basic ${btoa(token)}`;
1006
- }
1007
- return token;
1008
- }, "getAuthToken");
1009
-
1010
- // src/_api/generated/client/utils.gen.ts
1011
- var createQuerySerializer = /* @__PURE__ */ __name(({
1012
- parameters = {},
1013
- ...args
1014
- } = {}) => {
1015
- const querySerializer = /* @__PURE__ */ __name((queryParams) => {
1016
- const search = [];
1017
- if (queryParams && typeof queryParams === "object") {
1018
- for (const name in queryParams) {
1019
- const value = queryParams[name];
1020
- if (value === void 0 || value === null) {
1021
- continue;
1022
- }
1023
- const options = parameters[name] || args;
1024
- if (Array.isArray(value)) {
1025
- const serializedArray = serializeArrayParam({
1026
- allowReserved: options.allowReserved,
1027
- explode: true,
1028
- name,
1029
- style: "form",
1030
- value,
1031
- ...options.array
1032
- });
1033
- if (serializedArray) search.push(serializedArray);
1034
- } else if (typeof value === "object") {
1035
- const serializedObject = serializeObjectParam({
1036
- allowReserved: options.allowReserved,
1037
- explode: true,
1038
- name,
1039
- style: "deepObject",
1040
- value,
1041
- ...options.object
1042
- });
1043
- if (serializedObject) search.push(serializedObject);
1044
- } else {
1045
- const serializedPrimitive = serializePrimitiveParam({
1046
- allowReserved: options.allowReserved,
1047
- name,
1048
- value
1049
- });
1050
- if (serializedPrimitive) search.push(serializedPrimitive);
1051
- }
1052
- }
1657
+ function defaultApiKey() {
1658
+ try {
1659
+ if (typeof process !== "undefined" && process.env?.NEXT_PUBLIC_API_KEY) {
1660
+ return process.env.NEXT_PUBLIC_API_KEY;
1053
1661
  }
1054
- return search.join("&");
1055
- }, "querySerializer");
1056
- return querySerializer;
1057
- }, "createQuerySerializer");
1058
- var getParseAs = /* @__PURE__ */ __name((contentType) => {
1059
- if (!contentType) {
1060
- return "stream";
1061
- }
1062
- const cleanContent = contentType.split(";")[0]?.trim();
1063
- if (!cleanContent) {
1064
- return;
1065
- }
1066
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
1067
- return "json";
1068
- }
1069
- if (cleanContent === "multipart/form-data") {
1070
- return "formData";
1071
- }
1072
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
1073
- return "blob";
1074
- }
1075
- if (cleanContent.startsWith("text/")) {
1076
- return "text";
1077
- }
1078
- return;
1079
- }, "getParseAs");
1080
- var checkForExistence = /* @__PURE__ */ __name((options, name) => {
1081
- if (!name) {
1082
- return false;
1662
+ } catch {
1083
1663
  }
1084
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
1085
- return true;
1664
+ return null;
1665
+ }
1666
+ function jwtExpMs(token) {
1667
+ try {
1668
+ const payload = token.split(".")[1];
1669
+ if (!payload) return null;
1670
+ const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
1671
+ return typeof json.exp === "number" ? json.exp * 1e3 : null;
1672
+ } catch {
1673
+ return null;
1086
1674
  }
1087
- return false;
1088
- }, "checkForExistence");
1089
- async function setAuthParams(options) {
1090
- for (const auth2 of options.security ?? []) {
1091
- if (checkForExistence(options, auth2.name)) {
1092
- continue;
1093
- }
1094
- const token = await getAuthToken(auth2, options.auth);
1095
- if (!token) {
1096
- continue;
1675
+ }
1676
+ function computeSnapshot() {
1677
+ const access = _storage.get(ACCESS_KEY);
1678
+ const refresh = _storage.get(REFRESH_KEY);
1679
+ const now = Date.now();
1680
+ const accessExp = access ? jwtExpMs(access) : null;
1681
+ const accessAlive = access !== null && (accessExp === null || accessExp > now);
1682
+ const refreshExp = refresh ? jwtExpMs(refresh) : null;
1683
+ const refreshAlive = refresh !== null && (refreshExp === null || refreshExp > now);
1684
+ return {
1685
+ status: accessAlive || refreshAlive ? "authenticated" : "anonymous",
1686
+ accessExpiresAt: accessExp
1687
+ };
1688
+ }
1689
+ function scheduleExpiryFlip() {
1690
+ if (!isBrowser) return;
1691
+ if (_expiryTimer !== null) {
1692
+ clearTimeout(_expiryTimer);
1693
+ _expiryTimer = null;
1694
+ }
1695
+ if (_sessionListeners.size === 0) return;
1696
+ const now = Date.now();
1697
+ const exps = [];
1698
+ const access = _storage.get(ACCESS_KEY);
1699
+ const refresh = _storage.get(REFRESH_KEY);
1700
+ const accessExp = access ? jwtExpMs(access) : null;
1701
+ const refreshExp = refresh ? jwtExpMs(refresh) : null;
1702
+ if (accessExp !== null && accessExp > now) exps.push(accessExp);
1703
+ if (refreshExp !== null && refreshExp > now) exps.push(refreshExp);
1704
+ if (!exps.length) return;
1705
+ const delay = Math.min(Math.min(...exps) - now + 250, 2147483647);
1706
+ _expiryTimer = setTimeout(notifySessionChanged, delay);
1707
+ }
1708
+ function notifySessionChanged() {
1709
+ const next = computeSnapshot();
1710
+ const changed = next.status !== _snapshot.status || next.accessExpiresAt !== _snapshot.accessExpiresAt;
1711
+ if (changed) _snapshot = next;
1712
+ scheduleExpiryFlip();
1713
+ if (!changed) return;
1714
+ for (const listener of Array.from(_sessionListeners)) {
1715
+ try {
1716
+ listener();
1717
+ } catch {
1097
1718
  }
1098
- const name = auth2.name ?? "Authorization";
1099
- switch (auth2.in) {
1100
- case "query":
1101
- if (!options.query) {
1102
- options.query = {};
1103
- }
1104
- options.query[name] = token;
1105
- break;
1106
- case "cookie":
1107
- options.headers.append("Cookie", `${name}=${token}`);
1108
- break;
1109
- case "header":
1110
- default:
1111
- options.headers.set(name, token);
1112
- break;
1719
+ }
1720
+ if (isBrowser) {
1721
+ try {
1722
+ window.dispatchEvent(new Event(SESSION_SYNC_EVENT));
1723
+ } catch {
1113
1724
  }
1114
1725
  }
1115
1726
  }
1116
- __name(setAuthParams, "setAuthParams");
1117
- var buildUrl = /* @__PURE__ */ __name((options) => getUrl({
1118
- baseUrl: options.baseUrl,
1119
- path: options.path,
1120
- query: options.query,
1121
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
1122
- url: options.url
1123
- }), "buildUrl");
1124
- var mergeConfigs = /* @__PURE__ */ __name((a, b) => {
1125
- const config = { ...a, ...b };
1126
- if (config.baseUrl?.endsWith("/")) {
1127
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
1128
- }
1129
- config.headers = mergeHeaders(a.headers, b.headers);
1130
- return config;
1131
- }, "mergeConfigs");
1132
- var headersEntries = /* @__PURE__ */ __name((headers) => {
1133
- const entries = [];
1134
- headers.forEach((value, key) => {
1135
- entries.push([key, value]);
1136
- });
1137
- return entries;
1138
- }, "headersEntries");
1139
- var mergeHeaders = /* @__PURE__ */ __name((...headers) => {
1140
- const mergedHeaders = new Headers();
1141
- for (const header of headers) {
1142
- if (!header) {
1143
- continue;
1727
+ function ensureStorageSync() {
1728
+ if (!isBrowser || _storageListenerInstalled) return;
1729
+ _storageListenerInstalled = true;
1730
+ window.addEventListener("storage", (e) => {
1731
+ if (e.key === null || e.key === ACCESS_KEY || e.key === REFRESH_KEY) {
1732
+ notifySessionChanged();
1144
1733
  }
1145
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
1146
- for (const [key, value] of iterator) {
1147
- if (value === null) {
1148
- mergedHeaders.delete(key);
1149
- } else if (Array.isArray(value)) {
1150
- for (const v of value) {
1151
- mergedHeaders.append(key, v);
1152
- }
1153
- } else if (value !== void 0) {
1154
- mergedHeaders.set(
1155
- key,
1156
- typeof value === "object" ? JSON.stringify(value) : value
1157
- );
1734
+ });
1735
+ window.addEventListener(SESSION_SYNC_EVENT, () => notifySessionChanged());
1736
+ }
1737
+ function pushClientConfig() {
1738
+ if (!_client) return;
1739
+ _client.setConfig({
1740
+ baseUrl: auth.getBaseUrl(),
1741
+ credentials: _withCredentials ? "include" : "same-origin"
1742
+ });
1743
+ }
1744
+ async function tryRefresh() {
1745
+ if (_refreshInflight) return _refreshInflight;
1746
+ if (!_refreshHandler) return null;
1747
+ const runRefresh = /* @__PURE__ */ __name(async () => {
1748
+ const refresh = auth.getRefreshToken();
1749
+ if (!refresh) return null;
1750
+ const result = await _refreshHandler(refresh);
1751
+ if (!result?.access) return null;
1752
+ auth.setToken(result.access);
1753
+ if (result.refresh) auth.setRefreshToken(result.refresh);
1754
+ return result.access;
1755
+ }, "runRefresh");
1756
+ _refreshInflight = (async () => {
1757
+ try {
1758
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
1759
+ if (locks?.request) {
1760
+ return await locks.request(`${REFRESH_KEY}:refresh`, runRefresh);
1158
1761
  }
1762
+ return await runRefresh();
1763
+ } catch {
1764
+ return null;
1765
+ } finally {
1766
+ _refreshInflight = null;
1159
1767
  }
1160
- }
1161
- return mergedHeaders;
1162
- }, "mergeHeaders");
1163
- var Interceptors = class {
1164
- static {
1165
- __name(this, "Interceptors");
1166
- }
1167
- fns = [];
1168
- clear() {
1169
- this.fns = [];
1170
- }
1171
- eject(id) {
1172
- const index = this.getInterceptorIndex(id);
1173
- if (this.fns[index]) {
1174
- this.fns[index] = null;
1768
+ })();
1769
+ return _refreshInflight;
1770
+ }
1771
+ function expireSession(response) {
1772
+ auth.clearTokens();
1773
+ for (const cb of Array.from(_sessionExpiredHandlers)) {
1774
+ try {
1775
+ cb(response);
1776
+ } catch {
1175
1777
  }
1176
1778
  }
1177
- exists(id) {
1178
- const index = this.getInterceptorIndex(id);
1179
- return Boolean(this.fns[index]);
1180
- }
1181
- getInterceptorIndex(id) {
1182
- if (typeof id === "number") {
1183
- return this.fns[id] ? id : -1;
1779
+ if (_onUnauthorized) {
1780
+ try {
1781
+ _onUnauthorized(response);
1782
+ } catch {
1184
1783
  }
1185
- return this.fns.indexOf(id);
1186
1784
  }
1187
- update(id, fn) {
1188
- const index = this.getInterceptorIndex(id);
1189
- if (this.fns[index]) {
1190
- this.fns[index] = fn;
1191
- return id;
1192
- }
1785
+ }
1786
+ function dpopEnabled() {
1787
+ try {
1788
+ return typeof process !== "undefined" && process.env?.NEXT_PUBLIC_DPOP_ENABLED === "true";
1789
+ } catch {
1193
1790
  return false;
1194
1791
  }
1195
- use(fn) {
1196
- this.fns.push(fn);
1197
- return this.fns.length - 1;
1198
- }
1199
- };
1200
- var createInterceptors = /* @__PURE__ */ __name(() => ({
1201
- error: new Interceptors(),
1202
- request: new Interceptors(),
1203
- response: new Interceptors()
1204
- }), "createInterceptors");
1205
- var defaultQuerySerializer = createQuerySerializer({
1206
- allowReserved: false,
1207
- array: {
1208
- explode: true,
1209
- style: "form"
1210
- },
1211
- object: {
1212
- explode: true,
1213
- style: "deepObject"
1792
+ }
1793
+ function _idbOpen() {
1794
+ return new Promise((resolve, reject) => {
1795
+ const req = indexedDB.open(_DPOP_DB, 1);
1796
+ req.onupgradeneeded = () => req.result.createObjectStore(_DPOP_STORE);
1797
+ req.onsuccess = () => resolve(req.result);
1798
+ req.onerror = () => reject(req.error);
1799
+ });
1800
+ }
1801
+ function _idbGet(key) {
1802
+ return _idbOpen().then((db) => new Promise((resolve, reject) => {
1803
+ const tx = db.transaction(_DPOP_STORE, "readonly");
1804
+ const req = tx.objectStore(_DPOP_STORE).get(key);
1805
+ req.onsuccess = () => resolve(req.result);
1806
+ req.onerror = () => reject(req.error);
1807
+ }));
1808
+ }
1809
+ function _idbPut(key, value) {
1810
+ return _idbOpen().then((db) => new Promise((resolve, reject) => {
1811
+ const tx = db.transaction(_DPOP_STORE, "readwrite");
1812
+ tx.objectStore(_DPOP_STORE).put(value, key);
1813
+ tx.oncomplete = () => resolve();
1814
+ tx.onerror = () => reject(tx.error);
1815
+ }));
1816
+ }
1817
+ function _getDpopKeyPair() {
1818
+ if (_dpopKeyPromise) return _dpopKeyPromise;
1819
+ _dpopKeyPromise = (async () => {
1820
+ const existing = await _idbGet(_DPOP_KEY_ID).catch(() => void 0);
1821
+ if (existing) return existing;
1822
+ const pair = await crypto.subtle.generateKey(
1823
+ { name: "ECDSA", namedCurve: "P-256" },
1824
+ false,
1825
+ // extractable:false — JS can sign but never export the private key
1826
+ ["sign"]
1827
+ );
1828
+ await _idbPut(_DPOP_KEY_ID, pair).catch(() => {
1829
+ });
1830
+ return pair;
1831
+ })();
1832
+ return _dpopKeyPromise;
1833
+ }
1834
+ function _b64urlFromBytes(bytes) {
1835
+ const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
1836
+ let s = "";
1837
+ for (let i = 0; i < arr.length; i++) s += String.fromCharCode(arr[i]);
1838
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1839
+ }
1840
+ function _b64urlFromString(str) {
1841
+ return _b64urlFromBytes(new TextEncoder().encode(str));
1842
+ }
1843
+ async function _publicJwk(pub) {
1844
+ const jwk = await crypto.subtle.exportKey("jwk", pub);
1845
+ return { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
1846
+ }
1847
+ async function _makeDpopProof(method, url) {
1848
+ try {
1849
+ const pair = await _getDpopKeyPair();
1850
+ const jwk = await _publicJwk(pair.publicKey);
1851
+ const header = { typ: "dpop+jwt", alg: "ES256", jwk };
1852
+ const htu = url.split("#")[0].split("?")[0];
1853
+ const jti = crypto.randomUUID && crypto.randomUUID() || _b64urlFromBytes(crypto.getRandomValues(new Uint8Array(16)));
1854
+ const payload = { htm: method.toUpperCase(), htu, iat: Math.floor(Date.now() / 1e3), jti };
1855
+ const signingInput = `${_b64urlFromString(JSON.stringify(header))}.${_b64urlFromString(JSON.stringify(payload))}`;
1856
+ const sig = await crypto.subtle.sign(
1857
+ { name: "ECDSA", hash: "SHA-256" },
1858
+ pair.privateKey,
1859
+ new TextEncoder().encode(signingInput)
1860
+ );
1861
+ return `${signingInput}.${_b64urlFromBytes(sig)}`;
1862
+ } catch {
1863
+ return null;
1214
1864
  }
1215
- });
1216
- var defaultHeaders = {
1217
- "Content-Type": "application/json"
1218
- };
1219
- var createConfig = /* @__PURE__ */ __name((override = {}) => ({
1220
- ...jsonBodySerializer,
1221
- headers: defaultHeaders,
1222
- parseAs: "auto",
1223
- querySerializer: defaultQuerySerializer,
1224
- ...override
1225
- }), "createConfig");
1226
-
1227
- // src/_api/generated/client/client.gen.ts
1228
- var createClient = /* @__PURE__ */ __name((config = {}) => {
1229
- let _config = mergeConfigs(createConfig(), config);
1230
- const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
1231
- const setConfig = /* @__PURE__ */ __name((config2) => {
1232
- _config = mergeConfigs(_config, config2);
1233
- return getConfig();
1234
- }, "setConfig");
1235
- const interceptors = createInterceptors();
1236
- const beforeRequest = /* @__PURE__ */ __name(async (options) => {
1237
- const opts = {
1238
- ..._config,
1239
- ...options,
1240
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
1241
- headers: mergeHeaders(_config.headers, options.headers),
1242
- serializedBody: void 0
1243
- };
1244
- if (opts.security) {
1245
- await setAuthParams(opts);
1865
+ }
1866
+ function installAuthOnClient(client2) {
1867
+ if (_client) return;
1868
+ _client = client2;
1869
+ client2.setConfig({
1870
+ baseUrl: auth.getBaseUrl(),
1871
+ credentials: _withCredentials ? "include" : "same-origin"
1872
+ });
1873
+ client2.interceptors.request.use(async (request) => {
1874
+ const token = auth.getToken();
1875
+ if (token) request.headers.set("Authorization", `Bearer ${token}`);
1876
+ const locale = auth.getLocale();
1877
+ if (locale) request.headers.set("Accept-Language", locale);
1878
+ const apiKey = auth.getApiKey();
1879
+ if (apiKey && !request.headers.has("X-API-Key")) request.headers.set("X-API-Key", apiKey);
1880
+ try {
1881
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
1882
+ if (tz) request.headers.set("X-Timezone", tz);
1883
+ } catch {
1884
+ }
1885
+ request.headers.set("X-Client-Time", (/* @__PURE__ */ new Date()).toISOString());
1886
+ if (dpopEnabled() && typeof window !== "undefined") {
1887
+ const proof = await _makeDpopProof(request.method, request.url);
1888
+ if (proof) request.headers.set("DPoP", proof);
1246
1889
  }
1247
- if (opts.requestValidator) {
1248
- await opts.requestValidator(opts);
1890
+ return request;
1891
+ });
1892
+ client2.interceptors.error.use((err, res, req) => {
1893
+ if (err instanceof APIError) return err;
1894
+ const url = req?.url ?? "";
1895
+ const status = res?.status ?? 0;
1896
+ const statusText = res?.statusText ?? "";
1897
+ return new APIError(status, statusText, err, url);
1898
+ });
1899
+ client2.interceptors.response.use(async (response, request) => {
1900
+ if (response.status !== 401) return response;
1901
+ if (request.headers.get(RETRY_MARKER)) {
1902
+ expireSession(response);
1903
+ return response;
1249
1904
  }
1250
- if (opts.body !== void 0 && opts.bodySerializer) {
1251
- opts.serializedBody = opts.bodySerializer(opts.body);
1905
+ const newToken = await tryRefresh();
1906
+ if (!newToken) {
1907
+ expireSession(response);
1908
+ return response;
1252
1909
  }
1253
- if (opts.body === void 0 || opts.serializedBody === "") {
1254
- opts.headers.delete("Content-Type");
1910
+ const retry = request.clone();
1911
+ retry.headers.set("Authorization", `Bearer ${newToken}`);
1912
+ retry.headers.set(RETRY_MARKER, "1");
1913
+ if (dpopEnabled() && typeof window !== "undefined") {
1914
+ const proof = await _makeDpopProof(retry.method, retry.url);
1915
+ if (proof) retry.headers.set("DPoP", proof);
1255
1916
  }
1256
- const resolvedOpts = opts;
1257
- const url = buildUrl(resolvedOpts);
1258
- return { opts: resolvedOpts, url };
1259
- }, "beforeRequest");
1260
- const request = /* @__PURE__ */ __name(async (options) => {
1261
- const throwOnError = options.throwOnError ?? _config.throwOnError;
1262
- const responseStyle = options.responseStyle ?? _config.responseStyle;
1263
- let request2;
1264
- let response;
1265
1917
  try {
1266
- const { opts, url } = await beforeRequest(options);
1267
- const requestInit = {
1268
- redirect: "follow",
1269
- ...opts,
1270
- body: getValidRequestBody(opts)
1271
- };
1272
- request2 = new Request(url, requestInit);
1273
- for (const fn of interceptors.request.fns) {
1274
- if (fn) {
1275
- request2 = await fn(request2, opts);
1918
+ const retried = await fetch(retry);
1919
+ if (retried.status === 401) expireSession(retried);
1920
+ return retried;
1921
+ } catch {
1922
+ return response;
1923
+ }
1924
+ });
1925
+ }
1926
+ var ACCESS_KEY, REFRESH_KEY, API_KEY_KEY, isBrowser, localStorageBackend, COOKIE_MAX_AGE, cookieBackend, _storage, _storageMode, _localeOverride, _apiKeyOverride, _baseUrlOverride, _withCredentials, _onUnauthorized, _refreshHandler, _refreshInflight, RETRY_MARKER, SERVER_SNAPSHOT, SESSION_SYNC_EVENT, _snapshot, _sessionListeners, _expiryTimer, _storageListenerInstalled, _sessionExpiredHandlers, _client, auth, _DPOP_DB, _DPOP_STORE, _DPOP_KEY_ID, _dpopKeyPromise;
1927
+ var init_auth = __esm({
1928
+ "src/_api/generated/helpers/auth.ts"() {
1929
+ init_errors();
1930
+ ACCESS_KEY = "cfg.access_token";
1931
+ REFRESH_KEY = "cfg.refresh_token";
1932
+ API_KEY_KEY = "cfg.api_key";
1933
+ isBrowser = typeof window !== "undefined";
1934
+ localStorageBackend = {
1935
+ get(key) {
1936
+ if (!isBrowser) return null;
1937
+ try {
1938
+ return window.localStorage.getItem(key);
1939
+ } catch {
1940
+ return null;
1276
1941
  }
1277
- }
1278
- const _fetch = opts.fetch;
1279
- response = await _fetch(request2);
1280
- for (const fn of interceptors.response.fns) {
1281
- if (fn) {
1282
- response = await fn(response, request2, opts);
1942
+ },
1943
+ set(key, value) {
1944
+ if (!isBrowser) return;
1945
+ try {
1946
+ if (value === null) window.localStorage.removeItem(key);
1947
+ else window.localStorage.setItem(key, value);
1948
+ } catch {
1283
1949
  }
1284
1950
  }
1285
- const result = {
1286
- request: request2,
1287
- response
1288
- };
1289
- if (response.ok) {
1290
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
1291
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
1292
- let emptyData;
1293
- switch (parseAs) {
1294
- case "arrayBuffer":
1295
- case "blob":
1296
- case "text":
1297
- emptyData = await response[parseAs]();
1298
- break;
1299
- case "formData":
1300
- emptyData = new FormData();
1301
- break;
1302
- case "stream":
1303
- emptyData = response.body;
1304
- break;
1305
- case "json":
1306
- default:
1307
- emptyData = {};
1308
- break;
1309
- }
1310
- return opts.responseStyle === "data" ? emptyData : {
1311
- data: emptyData,
1312
- ...result
1313
- };
1951
+ };
1952
+ COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
1953
+ cookieBackend = {
1954
+ get(key) {
1955
+ if (!isBrowser) return null;
1956
+ try {
1957
+ const re = new RegExp(`(?:^|;\\s*)${encodeURIComponent(key)}=([^;]*)`);
1958
+ const m = document.cookie.match(re);
1959
+ return m ? decodeURIComponent(m[1]) : null;
1960
+ } catch {
1961
+ return null;
1314
1962
  }
1315
- let data;
1316
- switch (parseAs) {
1317
- case "arrayBuffer":
1318
- case "blob":
1319
- case "formData":
1320
- case "text":
1321
- data = await response[parseAs]();
1322
- break;
1323
- case "json": {
1324
- const text = await response.text();
1325
- data = text ? JSON.parse(text) : {};
1326
- break;
1963
+ },
1964
+ set(key, value) {
1965
+ if (!isBrowser) return;
1966
+ try {
1967
+ const k = encodeURIComponent(key);
1968
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
1969
+ if (value === null) {
1970
+ document.cookie = `${k}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
1971
+ } else {
1972
+ const v = encodeURIComponent(value);
1973
+ document.cookie = `${k}=${v}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
1327
1974
  }
1328
- case "stream":
1329
- return opts.responseStyle === "data" ? response.body : {
1330
- data: response.body,
1331
- ...result
1332
- };
1975
+ } catch {
1333
1976
  }
1334
- if (parseAs === "json") {
1335
- if (opts.responseValidator) {
1336
- await opts.responseValidator(data);
1337
- }
1338
- if (opts.responseTransformer) {
1339
- data = await opts.responseTransformer(data);
1977
+ }
1978
+ };
1979
+ _storage = localStorageBackend;
1980
+ _storageMode = "localStorage";
1981
+ __name(detectLocale, "detectLocale");
1982
+ __name(defaultBaseUrl, "defaultBaseUrl");
1983
+ __name(defaultApiKey, "defaultApiKey");
1984
+ _localeOverride = null;
1985
+ _apiKeyOverride = null;
1986
+ _baseUrlOverride = null;
1987
+ _withCredentials = true;
1988
+ _onUnauthorized = null;
1989
+ _refreshHandler = null;
1990
+ _refreshInflight = null;
1991
+ RETRY_MARKER = "X-Auth-Retry";
1992
+ __name(jwtExpMs, "jwtExpMs");
1993
+ __name(computeSnapshot, "computeSnapshot");
1994
+ SERVER_SNAPSHOT = { status: "anonymous", accessExpiresAt: null };
1995
+ SESSION_SYNC_EVENT = `cfg-auth:changed:${ACCESS_KEY}`;
1996
+ _snapshot = computeSnapshot();
1997
+ _sessionListeners = /* @__PURE__ */ new Set();
1998
+ _expiryTimer = null;
1999
+ _storageListenerInstalled = false;
2000
+ __name(scheduleExpiryFlip, "scheduleExpiryFlip");
2001
+ __name(notifySessionChanged, "notifySessionChanged");
2002
+ __name(ensureStorageSync, "ensureStorageSync");
2003
+ _sessionExpiredHandlers = /* @__PURE__ */ new Set();
2004
+ _client = null;
2005
+ __name(pushClientConfig, "pushClientConfig");
2006
+ auth = {
2007
+ // ── Storage mode ──────────────────────────────────────────────────
2008
+ getStorageMode() {
2009
+ return _storageMode;
2010
+ },
2011
+ setStorageMode(mode) {
2012
+ _storageMode = mode;
2013
+ _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
2014
+ notifySessionChanged();
2015
+ },
2016
+ // ── Bearer token ──────────────────────────────────────────────────
2017
+ getToken() {
2018
+ return _storage.get(ACCESS_KEY);
2019
+ },
2020
+ setToken(token) {
2021
+ _storage.set(ACCESS_KEY, token);
2022
+ notifySessionChanged();
2023
+ },
2024
+ getRefreshToken() {
2025
+ return _storage.get(REFRESH_KEY);
2026
+ },
2027
+ setRefreshToken(token) {
2028
+ _storage.set(REFRESH_KEY, token);
2029
+ notifySessionChanged();
2030
+ },
2031
+ clearTokens() {
2032
+ _storage.set(ACCESS_KEY, null);
2033
+ _storage.set(REFRESH_KEY, null);
2034
+ notifySessionChanged();
2035
+ },
2036
+ /** Session-aware: token PRESENT and not past its `exp` (or a live refresh
2037
+ * token exists that can mint one). Prefer `getSnapshot().status` in React. */
2038
+ isAuthenticated() {
2039
+ return computeSnapshot().status === "authenticated";
2040
+ },
2041
+ // ── Session (the ONE write path for login/logout flows) ──────────
2042
+ /**
2043
+ * Persist a token pair atomically. Every login flow (OTP verify, 2FA,
2044
+ * OAuth callback) and the refresh handler should end here — do NOT
2045
+ * scatter `setToken`/`setRefreshToken` pairs through app code.
2046
+ * `refresh: undefined` keeps the current refresh token (access-only
2047
+ * rotation); `refresh: null` explicitly drops it.
2048
+ */
2049
+ setSession(tokens) {
2050
+ _storage.set(ACCESS_KEY, tokens.access);
2051
+ if (tokens.refresh !== void 0) _storage.set(REFRESH_KEY, tokens.refresh);
2052
+ notifySessionChanged();
2053
+ },
2054
+ clearSession() {
2055
+ auth.clearTokens();
2056
+ },
2057
+ // ── Reactive snapshot (for useSyncExternalStore) ──────────────────
2058
+ /**
2059
+ * @example React:
2060
+ * const session = useSyncExternalStore(
2061
+ * auth.subscribe, auth.getSnapshot, auth.getServerSnapshot,
2062
+ * );
2063
+ * const isAuthenticated = session.status === 'authenticated';
2064
+ */
2065
+ getSnapshot() {
2066
+ return _snapshot;
2067
+ },
2068
+ getServerSnapshot() {
2069
+ return SERVER_SNAPSHOT;
2070
+ },
2071
+ subscribe(listener) {
2072
+ ensureStorageSync();
2073
+ _sessionListeners.add(listener);
2074
+ notifySessionChanged();
2075
+ return () => {
2076
+ _sessionListeners.delete(listener);
2077
+ if (_sessionListeners.size === 0 && _expiryTimer !== null) {
2078
+ clearTimeout(_expiryTimer);
2079
+ _expiryTimer = null;
1340
2080
  }
1341
- }
1342
- return opts.responseStyle === "data" ? data : {
1343
- data,
1344
- ...result
1345
2081
  };
2082
+ },
2083
+ /**
2084
+ * Fired on TERMINAL 401 — after the refresh+retry path is exhausted.
2085
+ * The store has already cleared the session before calling back, so
2086
+ * handlers only need to route to login (no clear-then-redirect
2087
+ * ordering to get wrong). Returns an unsubscribe function; multiple
2088
+ * handlers compose (unlike the legacy single-slot `onUnauthorized`).
2089
+ */
2090
+ onSessionExpired(cb) {
2091
+ _sessionExpiredHandlers.add(cb);
2092
+ return () => {
2093
+ _sessionExpiredHandlers.delete(cb);
2094
+ };
2095
+ },
2096
+ // ── API key ───────────────────────────────────────────────────────
2097
+ getApiKey() {
2098
+ return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
2099
+ },
2100
+ setApiKey(key) {
2101
+ _apiKeyOverride = key;
2102
+ },
2103
+ setApiKeyPersist(key) {
2104
+ _apiKeyOverride = key;
2105
+ _storage.set(API_KEY_KEY, key);
2106
+ },
2107
+ clearApiKey() {
2108
+ _apiKeyOverride = null;
2109
+ _storage.set(API_KEY_KEY, null);
2110
+ },
2111
+ // ── Locale ────────────────────────────────────────────────────────
2112
+ getLocale() {
2113
+ return _localeOverride ?? detectLocale();
2114
+ },
2115
+ setLocale(locale) {
2116
+ _localeOverride = locale;
2117
+ },
2118
+ // ── Base URL ──────────────────────────────────────────────────────
2119
+ getBaseUrl() {
2120
+ const url = _baseUrlOverride ?? defaultBaseUrl();
2121
+ return url.replace(/\/$/, "");
2122
+ },
2123
+ setBaseUrl(url) {
2124
+ _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
2125
+ pushClientConfig();
2126
+ },
2127
+ // ── Credentials toggle ────────────────────────────────────────────
2128
+ getWithCredentials() {
2129
+ return _withCredentials;
2130
+ },
2131
+ setWithCredentials(value) {
2132
+ _withCredentials = value;
2133
+ pushClientConfig();
2134
+ },
2135
+ // ── 401 handler ───────────────────────────────────────────────────
2136
+ /**
2137
+ * Fired when the server returns 401 AND no refresh path recovers it
2138
+ * (no refresh token, no refresh handler, refresh failed, or retry
2139
+ * still 401). The app should clear local state and redirect to login.
2140
+ *
2141
+ * NOT fired for 401 that gets transparently recovered by the refresh
2142
+ * handler — those are invisible to callers.
2143
+ */
2144
+ onUnauthorized(cb) {
2145
+ _onUnauthorized = cb;
2146
+ },
2147
+ /**
2148
+ * Register the refresh strategy. The handler receives the current
2149
+ * refresh token and must call your refresh endpoint, returning
2150
+ * `{ access, refresh? }` on success or `null` on failure.
2151
+ *
2152
+ * @example
2153
+ * auth.setRefreshHandler(async (refresh) => {
2154
+ * const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
2155
+ * return data ? { access: data.access, refresh: data.refresh } : null;
2156
+ * });
2157
+ */
2158
+ setRefreshHandler(fn) {
2159
+ _refreshHandler = fn;
2160
+ },
2161
+ /**
2162
+ * Proactively run the registered refresh handler right now, reusing the
2163
+ * SAME single-flight promise as the 401-recovery interceptor. Callers
2164
+ * (e.g. an expiry timer / focus / reconnect) get token rotation,
2165
+ * de-duplication and rotated-token persistence for free — they must NOT
2166
+ * re-implement any of it. Returns the fresh access token, or null if
2167
+ * there is no handler / no refresh token / the refresh failed.
2168
+ */
2169
+ refreshNow() {
2170
+ return tryRefresh();
1346
2171
  }
1347
- const textError = await response.text();
1348
- let jsonError;
2172
+ };
2173
+ __name(tryRefresh, "tryRefresh");
2174
+ __name(expireSession, "expireSession");
2175
+ __name(dpopEnabled, "dpopEnabled");
2176
+ _DPOP_DB = "cfg-auth";
2177
+ _DPOP_STORE = "keys";
2178
+ _DPOP_KEY_ID = "dpop-ec-p256";
2179
+ __name(_idbOpen, "_idbOpen");
2180
+ __name(_idbGet, "_idbGet");
2181
+ __name(_idbPut, "_idbPut");
2182
+ _dpopKeyPromise = null;
2183
+ __name(_getDpopKeyPair, "_getDpopKeyPair");
2184
+ __name(_b64urlFromBytes, "_b64urlFromBytes");
2185
+ __name(_b64urlFromString, "_b64urlFromString");
2186
+ __name(_publicJwk, "_publicJwk");
2187
+ __name(_makeDpopProof, "_makeDpopProof");
2188
+ __name(installAuthOnClient, "installAuthOnClient");
2189
+ auth.setRefreshHandler(async (refresh) => {
1349
2190
  try {
1350
- jsonError = JSON.parse(textError);
2191
+ const { CfgAccountsAuth: CfgAccountsAuth2 } = await Promise.resolve().then(() => (init_sdk_gen(), sdk_gen_exports));
2192
+ const { data } = await CfgAccountsAuth2.cfgAccountsTokenRefreshCreate({
2193
+ body: { refresh },
2194
+ throwOnError: true
2195
+ });
2196
+ return data?.access ? { access: data.access, refresh: data.refresh ?? refresh } : null;
1351
2197
  } catch {
2198
+ return null;
1352
2199
  }
1353
- throw jsonError ?? textError;
1354
- } catch (error) {
1355
- let finalError = error;
1356
- for (const fn of interceptors.error.fns) {
1357
- if (fn) {
1358
- finalError = await fn(finalError, response, request2, options);
1359
- }
1360
- }
1361
- finalError = finalError || {};
1362
- if (throwOnError) {
1363
- throw finalError;
1364
- }
1365
- return responseStyle === "data" ? void 0 : {
1366
- error: finalError,
1367
- request: request2,
1368
- response
1369
- };
1370
- }
1371
- }, "request");
1372
- const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
1373
- const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
1374
- const { opts, url } = await beforeRequest(options);
1375
- return createSseClient({
1376
- ...opts,
1377
- body: opts.body,
1378
- method,
1379
- onRequest: /* @__PURE__ */ __name(async (url2, init) => {
1380
- let request2 = new Request(url2, init);
1381
- for (const fn of interceptors.request.fns) {
1382
- if (fn) {
1383
- request2 = await fn(request2, opts);
1384
- }
1385
- }
1386
- return request2;
1387
- }, "onRequest"),
1388
- serializedBody: getValidRequestBody(opts),
1389
- url
1390
2200
  });
1391
- }, "makeSseFn");
1392
- const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
1393
- return {
1394
- buildUrl: _buildUrl,
1395
- connect: makeMethodFn("CONNECT"),
1396
- delete: makeMethodFn("DELETE"),
1397
- get: makeMethodFn("GET"),
1398
- getConfig,
1399
- head: makeMethodFn("HEAD"),
1400
- interceptors,
1401
- options: makeMethodFn("OPTIONS"),
1402
- patch: makeMethodFn("PATCH"),
1403
- post: makeMethodFn("POST"),
1404
- put: makeMethodFn("PUT"),
1405
- request,
1406
- setConfig,
1407
- sse: {
1408
- connect: makeSseFn("CONNECT"),
1409
- delete: makeSseFn("DELETE"),
1410
- get: makeSseFn("GET"),
1411
- head: makeSseFn("HEAD"),
1412
- options: makeSseFn("OPTIONS"),
1413
- patch: makeSseFn("PATCH"),
1414
- post: makeSseFn("POST"),
1415
- put: makeSseFn("PUT"),
1416
- trace: makeSseFn("TRACE")
1417
- },
1418
- trace: makeMethodFn("TRACE")
1419
- };
1420
- }, "createClient");
2201
+ }
2202
+ });
1421
2203
 
1422
- // src/_api/generated/client.gen.ts
1423
- var client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
1424
- installAuthOnClient(client);
2204
+ // src/clients.ts
2205
+ var clients_exports = {};
2206
+ __export(clients_exports, {
2207
+ AccountsAPI: () => API,
2208
+ CentrifugoAPI: () => API2,
2209
+ TotpAPI: () => API3,
2210
+ apiAccounts: () => CfgAccountsApi,
2211
+ apiCentrifugo: () => CfgCentrifugoApi,
2212
+ apiTotp: () => CfgTotpApi
2213
+ });
2214
+ module.exports = __toCommonJS(clients_exports);
1425
2215
 
1426
- // src/_api/generated/sdk.gen.ts
1427
- var CfgAccountsApiKey = class {
1428
- static {
1429
- __name(this, "CfgAccountsApiKey");
1430
- }
1431
- /**
1432
- * Get API key details
1433
- *
1434
- * Retrieve the current user's API key (masked) and metadata.
1435
- */
1436
- static cfgAccountsApiKeyRetrieve(options) {
1437
- return (options?.client ?? client).get({
1438
- security: [
1439
- { scheme: "bearer", type: "http" },
1440
- {
1441
- in: "cookie",
1442
- name: "sessionid",
1443
- type: "apiKey"
1444
- },
1445
- { name: "X-API-Key", type: "apiKey" }
1446
- ],
1447
- url: "/cfg/accounts/api-key/",
1448
- ...options
1449
- });
1450
- }
1451
- /**
1452
- * Regenerate API key
1453
- *
1454
- * Generate a new API key. The full key is returned only once.
1455
- */
1456
- static cfgAccountsApiKeyRegenerateCreate(options) {
1457
- return (options.client ?? client).post({
1458
- security: [
1459
- { scheme: "bearer", type: "http" },
1460
- {
1461
- in: "cookie",
1462
- name: "sessionid",
1463
- type: "apiKey"
1464
- },
1465
- { name: "X-API-Key", type: "apiKey" }
1466
- ],
1467
- url: "/cfg/accounts/api-key/regenerate/",
1468
- ...options,
1469
- headers: {
1470
- "Content-Type": "application/json",
1471
- ...options.headers
1472
- }
1473
- });
1474
- }
1475
- /**
1476
- * Reveal API key
1477
- *
1478
- * Return the current full API key WITHOUT rotating it. The same durable value every one of the user's agents uses — for the signed-in user to copy and paste into agent onboarding. Default GET stays masked; this is the explicit reveal action.
1479
- */
1480
- static cfgAccountsApiKeyRevealCreate(options) {
1481
- return (options.client ?? client).post({
1482
- security: [
1483
- { scheme: "bearer", type: "http" },
1484
- {
1485
- in: "cookie",
1486
- name: "sessionid",
1487
- type: "apiKey"
1488
- },
1489
- { name: "X-API-Key", type: "apiKey" }
1490
- ],
1491
- url: "/cfg/accounts/api-key/reveal/",
1492
- ...options,
1493
- headers: {
1494
- "Content-Type": "application/json",
1495
- ...options.headers
1496
- }
1497
- });
1498
- }
1499
- /**
1500
- * Test API key
1501
- *
1502
- * Test whether an API key is valid without consuming it.
1503
- */
1504
- static cfgAccountsApiKeyTestCreate(options) {
1505
- return (options.client ?? client).post({
1506
- security: [
1507
- { scheme: "bearer", type: "http" },
1508
- {
1509
- in: "cookie",
1510
- name: "sessionid",
1511
- type: "apiKey"
1512
- },
1513
- { name: "X-API-Key", type: "apiKey" }
1514
- ],
1515
- url: "/cfg/accounts/api-key/test/",
1516
- ...options,
1517
- headers: {
1518
- "Content-Type": "application/json",
1519
- ...options.headers
1520
- }
1521
- });
1522
- }
1523
- };
1524
- var CfgAccountsOauth = class {
1525
- static {
1526
- __name(this, "CfgAccountsOauth");
1527
- }
1528
- /**
1529
- * List OAuth connections
1530
- *
1531
- * Get all OAuth connections for the current user.
1532
- */
1533
- static cfgAccountsOauthConnectionsList(options) {
1534
- return (options?.client ?? client).get({
1535
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1536
- url: "/cfg/accounts/oauth/connections/",
1537
- ...options
1538
- });
1539
- }
1540
- /**
1541
- * Disconnect OAuth provider
1542
- *
1543
- * Remove OAuth connection for the specified provider.
1544
- */
1545
- static cfgAccountsOauthDisconnectCreate(options) {
1546
- return (options.client ?? client).post({
1547
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1548
- url: "/cfg/accounts/oauth/disconnect/",
1549
- ...options,
1550
- headers: {
1551
- "Content-Type": "application/json",
1552
- ...options.headers
1553
- }
1554
- });
1555
- }
1556
- /**
1557
- * Start GitHub OAuth
1558
- *
1559
- * Generate GitHub OAuth authorization URL. Redirect user to this URL to start authentication.
1560
- */
1561
- static cfgAccountsOauthGithubAuthorizeCreate(options) {
1562
- return (options?.client ?? client).post({
1563
- url: "/cfg/accounts/oauth/github/authorize/",
1564
- ...options,
1565
- headers: {
1566
- "Content-Type": "application/json",
1567
- ...options?.headers
1568
- }
1569
- });
1570
- }
1571
- /**
1572
- * Complete GitHub OAuth
1573
- *
1574
- * Exchange authorization code for JWT tokens. Call this after GitHub redirects back with code.
1575
- */
1576
- static cfgAccountsOauthGithubCallbackCreate(options) {
1577
- return (options.client ?? client).post({
1578
- url: "/cfg/accounts/oauth/github/callback/",
1579
- ...options,
1580
- headers: {
1581
- "Content-Type": "application/json",
1582
- ...options.headers
1583
- }
1584
- });
1585
- }
1586
- /**
1587
- * List OAuth providers
1588
- *
1589
- * Get list of available OAuth providers for authentication.
1590
- */
1591
- static cfgAccountsOauthProvidersRetrieve(options) {
1592
- return (options?.client ?? client).get({ url: "/cfg/accounts/oauth/providers/", ...options });
1593
- }
1594
- };
1595
- var CfgAccounts = class {
1596
- static {
1597
- __name(this, "CfgAccounts");
1598
- }
1599
- /**
1600
- * Request OTP code to email.
1601
- */
1602
- static cfgAccountsOtpRequestCreate(options) {
1603
- return (options.client ?? client).post({
1604
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1605
- url: "/cfg/accounts/otp/request/",
1606
- ...options,
1607
- headers: {
1608
- "Content-Type": "application/json",
1609
- ...options.headers
1610
- }
1611
- });
1612
- }
1613
- /**
1614
- * Verify OTP code and return JWT tokens or 2FA session.
1615
- *
1616
- * If user has 2FA enabled:
1617
- * - Returns requires_2fa=True with session_id
1618
- * - Client must complete 2FA verification at /cfg/totp/verify/
1619
- *
1620
- * If user has no 2FA:
1621
- * - Returns JWT tokens and user data directly
1622
- */
1623
- static cfgAccountsOtpVerifyCreate(options) {
1624
- return (options.client ?? client).post({
1625
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1626
- url: "/cfg/accounts/otp/verify/",
1627
- ...options,
1628
- headers: {
1629
- "Content-Type": "application/json",
1630
- ...options.headers
1631
- }
1632
- });
1633
- }
1634
- };
1635
- var CfgAccountsProfile = class {
1636
- static {
1637
- __name(this, "CfgAccountsProfile");
1638
- }
1639
- /**
1640
- * Get current user profile
1641
- *
1642
- * Retrieve the current authenticated user's profile information.
1643
- */
1644
- static cfgAccountsProfileRetrieve(options) {
1645
- return (options?.client ?? client).get({
1646
- security: [{ scheme: "bearer", type: "http" }, {
1647
- in: "cookie",
1648
- name: "sessionid",
1649
- type: "apiKey"
1650
- }],
1651
- url: "/cfg/accounts/profile/",
1652
- ...options
1653
- });
1654
- }
1655
- /**
1656
- * Upload user avatar
1657
- *
1658
- * Upload avatar image for the current authenticated user. Accepts multipart/form-data with 'avatar' field.
1659
- */
1660
- static cfgAccountsProfileAvatarCreate(options) {
1661
- return (options?.client ?? client).post({
1662
- ...formDataBodySerializer,
1663
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1664
- url: "/cfg/accounts/profile/avatar/",
1665
- ...options,
1666
- headers: {
1667
- "Content-Type": null,
1668
- ...options?.headers
1669
- }
1670
- });
1671
- }
1672
- /**
1673
- * Delete user account
1674
- *
1675
- *
1676
- * Permanently delete the current user's account.
1677
- *
1678
- * This operation:
1679
- * - Deactivates the account (user cannot log in)
1680
- * - Anonymizes personal data (GDPR compliance)
1681
- * - Frees up the email address for re-registration
1682
- * - Preserves audit trail
1683
- *
1684
- * The account can be restored by an administrator if needed.
1685
- *
1686
- */
1687
- static cfgAccountsProfileDeleteCreate(options) {
1688
- return (options?.client ?? client).post({
1689
- security: [{ scheme: "bearer", type: "http" }, {
1690
- in: "cookie",
1691
- name: "sessionid",
1692
- type: "apiKey"
1693
- }],
1694
- url: "/cfg/accounts/profile/delete/",
1695
- ...options
1696
- });
1697
- }
1698
- /**
1699
- * Partial update user profile
1700
- *
1701
- * Partially update the current authenticated user's profile information. Supports avatar upload.
1702
- */
1703
- static cfgAccountsProfilePartialPartialUpdate(options) {
1704
- return (options?.client ?? client).patch({
1705
- security: [{ scheme: "bearer", type: "http" }, {
1706
- in: "cookie",
1707
- name: "sessionid",
1708
- type: "apiKey"
1709
- }],
1710
- url: "/cfg/accounts/profile/partial/",
1711
- ...options,
1712
- headers: {
1713
- "Content-Type": "application/json",
1714
- ...options?.headers
1715
- }
1716
- });
1717
- }
1718
- /**
1719
- * Partial update user profile
1720
- *
1721
- * Partially update the current authenticated user's profile information. Supports avatar upload.
1722
- */
1723
- static cfgAccountsProfilePartialUpdate(options) {
1724
- return (options?.client ?? client).put({
1725
- security: [{ scheme: "bearer", type: "http" }, {
1726
- in: "cookie",
1727
- name: "sessionid",
1728
- type: "apiKey"
1729
- }],
1730
- url: "/cfg/accounts/profile/partial/",
1731
- ...options,
1732
- headers: {
1733
- "Content-Type": "application/json",
1734
- ...options?.headers
1735
- }
1736
- });
1737
- }
1738
- /**
1739
- * Update user profile
1740
- *
1741
- * Update the current authenticated user's profile information.
1742
- */
1743
- static cfgAccountsProfileUpdatePartialUpdate(options) {
1744
- return (options?.client ?? client).patch({
1745
- security: [{ scheme: "bearer", type: "http" }, {
1746
- in: "cookie",
1747
- name: "sessionid",
1748
- type: "apiKey"
1749
- }],
1750
- url: "/cfg/accounts/profile/update/",
1751
- ...options,
1752
- headers: {
1753
- "Content-Type": "application/json",
1754
- ...options?.headers
1755
- }
1756
- });
1757
- }
1758
- /**
1759
- * Update user profile
1760
- *
1761
- * Update the current authenticated user's profile information.
1762
- */
1763
- static cfgAccountsProfileUpdateUpdate(options) {
1764
- return (options?.client ?? client).put({
1765
- security: [{ scheme: "bearer", type: "http" }, {
1766
- in: "cookie",
1767
- name: "sessionid",
1768
- type: "apiKey"
1769
- }],
1770
- url: "/cfg/accounts/profile/update/",
1771
- ...options,
1772
- headers: {
1773
- "Content-Type": "application/json",
1774
- ...options?.headers
1775
- }
1776
- });
1777
- }
2216
+ // src/_api/generated/index.ts
2217
+ init_auth();
2218
+ init_auth();
2219
+
2220
+ // src/_api/generated/_cfg_accounts/api.ts
2221
+ init_auth();
2222
+
2223
+ // src/_api/generated/helpers/logger.ts
2224
+ var import_consola = require("consola");
2225
+ var DEFAULT_CONFIG = {
2226
+ enabled: typeof process !== "undefined" && process.env.NODE_ENV !== "production",
2227
+ logRequests: true,
2228
+ logResponses: true,
2229
+ logErrors: true,
2230
+ logBodies: true,
2231
+ logHeaders: false
1778
2232
  };
1779
- var CfgAccountsAuth = class {
2233
+ var SENSITIVE_HEADERS = [
2234
+ "authorization",
2235
+ "cookie",
2236
+ "set-cookie",
2237
+ "x-api-key",
2238
+ "x-csrf-token"
2239
+ ];
2240
+ var APILogger = class {
1780
2241
  static {
1781
- __name(this, "CfgAccountsAuth");
2242
+ __name(this, "APILogger");
1782
2243
  }
1783
- /**
1784
- * Refresh JWT token.
1785
- *
1786
- * DPoP-aware: when the incoming refresh token is key-bound (`cnf.jkt`), the
1787
- * rotated access/refresh in the response are re-stamped with the same `cnf`
1788
- * (stock SimpleJWT drops it from the derived access), and a matching DPoP
1789
- * proof is required on the refresh request — so a stolen refresh token can't
1790
- * be used to mint fresh tokens.
1791
- */
1792
- static cfgAccountsTokenRefreshCreate(options) {
1793
- return (options.client ?? client).post({
1794
- url: "/cfg/accounts/token/refresh/",
1795
- ...options,
1796
- headers: {
1797
- "Content-Type": "application/json",
1798
- ...options.headers
1799
- }
2244
+ config;
2245
+ consola;
2246
+ constructor(config = {}) {
2247
+ this.config = { ...DEFAULT_CONFIG, ...config };
2248
+ this.consola = config.consola || (0, import_consola.createConsola)({
2249
+ level: this.config.enabled ? 4 : 0
1800
2250
  });
1801
2251
  }
1802
- };
1803
- var CfgCentrifugo = class {
1804
- static {
1805
- __name(this, "CfgCentrifugo");
1806
- }
1807
- /**
1808
- * Get Centrifugo connection token
1809
- *
1810
- * Generate JWT token for WebSocket connection to Centrifugo. Token includes user's allowed channels based on their permissions. Requires authentication.
1811
- */
1812
- static cfgCentrifugoAuthTokenRetrieve(options) {
1813
- return (options?.client ?? client).get({
1814
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1815
- url: "/cfg/centrifugo/auth/token/",
1816
- ...options
1817
- });
2252
+ enable() {
2253
+ this.config.enabled = true;
1818
2254
  }
1819
- };
1820
- var CfgTotpBackupCodes = class {
1821
- static {
1822
- __name(this, "CfgTotpBackupCodes");
2255
+ disable() {
2256
+ this.config.enabled = false;
1823
2257
  }
1824
- /**
1825
- * Get backup codes status for user.
1826
- */
1827
- static cfgTotpBackupCodesRetrieve(options) {
1828
- return (options?.client ?? client).get({
1829
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1830
- url: "/cfg/totp/backup-codes/",
1831
- ...options
1832
- });
2258
+ setConfig(config) {
2259
+ this.config = { ...this.config, ...config };
1833
2260
  }
1834
- /**
1835
- * Regenerate backup codes.
1836
- *
1837
- * Requires TOTP code for verification.
1838
- * Invalidates all existing codes.
1839
- */
1840
- static cfgTotpBackupCodesRegenerateCreate(options) {
1841
- return (options.client ?? client).post({
1842
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1843
- url: "/cfg/totp/backup-codes/regenerate/",
1844
- ...options,
1845
- headers: {
1846
- "Content-Type": "application/json",
1847
- ...options.headers
1848
- }
2261
+ filterHeaders(headers) {
2262
+ if (!headers) return {};
2263
+ const filtered = {};
2264
+ Object.keys(headers).forEach((key) => {
2265
+ filtered[key] = SENSITIVE_HEADERS.includes(key.toLowerCase()) ? "***" : headers[key] || "";
1849
2266
  });
2267
+ return filtered;
1850
2268
  }
1851
- };
1852
- var CfgTotp = class {
1853
- static {
1854
- __name(this, "CfgTotp");
1855
- }
1856
- /**
1857
- * List all TOTP devices for user.
1858
- */
1859
- static cfgTotpDevicesRetrieve(options) {
1860
- return (options?.client ?? client).get({
1861
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1862
- url: "/cfg/totp/devices/",
1863
- ...options
1864
- });
2269
+ logRequest(request) {
2270
+ if (!this.config.enabled || !this.config.logRequests) return;
2271
+ const { method, url, headers, body } = request;
2272
+ this.consola.start(`${method} ${url}`);
2273
+ if (this.config.logHeaders && headers) this.consola.debug("Headers:", this.filterHeaders(headers));
2274
+ if (this.config.logBodies && body) this.consola.debug("Body:", body);
1865
2275
  }
1866
- /**
1867
- * Delete a TOTP device.
1868
- *
1869
- * Requires verification code if removing the last/primary device.
1870
- */
1871
- static cfgTotpDevicesDestroy(options) {
1872
- return (options.client ?? client).delete({
1873
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1874
- url: "/cfg/totp/devices/{id}/",
1875
- ...options
1876
- });
2276
+ logResponse(request, response) {
2277
+ if (!this.config.enabled || !this.config.logResponses) return;
2278
+ const { method, url } = request;
2279
+ const { status, statusText, data, duration } = response;
2280
+ this.consola.success(`${method} ${url} ${status} ${statusText} (${duration}ms)`);
2281
+ if (this.config.logBodies && data) this.consola.debug("Response:", data);
1877
2282
  }
1878
- /**
1879
- * Completely disable 2FA for account.
1880
- *
1881
- * Requires verification code.
1882
- */
1883
- static cfgTotpDisableCreate(options) {
1884
- return (options.client ?? client).post({
1885
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1886
- url: "/cfg/totp/disable/",
1887
- ...options,
1888
- headers: {
1889
- "Content-Type": "application/json",
1890
- ...options.headers
1891
- }
1892
- });
2283
+ logError(request, error) {
2284
+ if (!this.config.enabled || !this.config.logErrors) return;
2285
+ const { method, url } = request;
2286
+ const { message, statusCode, fieldErrors, duration } = error;
2287
+ this.consola.error(`${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`);
2288
+ this.consola.error("Message:", message);
2289
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
2290
+ this.consola.error("Field Errors:");
2291
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
2292
+ errors.forEach((err) => this.consola.error(` \u2022 ${field}: ${err}`));
2293
+ });
2294
+ }
1893
2295
  }
1894
- };
1895
- var CfgTotpSetup = class {
1896
- static {
1897
- __name(this, "CfgTotpSetup");
2296
+ info(message, ...args) {
2297
+ if (this.config.enabled) this.consola.info(message, ...args);
1898
2298
  }
1899
- /**
1900
- * Start 2FA setup process.
1901
- *
1902
- * Creates a new TOTP device and returns QR code for scanning.
1903
- */
1904
- static cfgTotpSetupCreate(options) {
1905
- return (options?.client ?? client).post({
1906
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1907
- url: "/cfg/totp/setup/",
1908
- ...options,
1909
- headers: {
1910
- "Content-Type": "application/json",
1911
- ...options?.headers
1912
- }
1913
- });
2299
+ warn(message, ...args) {
2300
+ if (this.config.enabled) this.consola.warn(message, ...args);
1914
2301
  }
1915
- /**
1916
- * Confirm 2FA setup with first valid code.
1917
- *
1918
- * Activates the device and generates backup codes.
1919
- */
1920
- static cfgTotpSetupConfirmCreate(options) {
1921
- return (options.client ?? client).post({
1922
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1923
- url: "/cfg/totp/setup/confirm/",
1924
- ...options,
1925
- headers: {
1926
- "Content-Type": "application/json",
1927
- ...options.headers
1928
- }
1929
- });
2302
+ error(message, ...args) {
2303
+ if (this.config.enabled) this.consola.error(message, ...args);
1930
2304
  }
1931
- };
1932
- var CfgTotpVerify = class {
1933
- static {
1934
- __name(this, "CfgTotpVerify");
2305
+ debug(message, ...args) {
2306
+ if (this.config.enabled) this.consola.debug(message, ...args);
1935
2307
  }
1936
- /**
1937
- * Verify TOTP code for 2FA session.
1938
- *
1939
- * Completes authentication and returns JWT tokens on success.
1940
- */
1941
- static cfgTotpVerifyCreate(options) {
1942
- return (options.client ?? client).post({
1943
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1944
- url: "/cfg/totp/verify/",
1945
- ...options,
1946
- headers: {
1947
- "Content-Type": "application/json",
1948
- ...options.headers
1949
- }
1950
- });
2308
+ success(message, ...args) {
2309
+ if (this.config.enabled) this.consola.success(message, ...args);
1951
2310
  }
1952
- /**
1953
- * Verify backup recovery code for 2FA session.
1954
- *
1955
- * Alternative verification method when TOTP device unavailable.
1956
- */
1957
- static cfgTotpVerifyBackupCreate(options) {
1958
- return (options.client ?? client).post({
1959
- security: [{ name: "X-API-Key", type: "apiKey" }, { scheme: "bearer", type: "http" }],
1960
- url: "/cfg/totp/verify/backup/",
1961
- ...options,
1962
- headers: {
1963
- "Content-Type": "application/json",
1964
- ...options.headers
1965
- }
1966
- });
2311
+ withTag(tag) {
2312
+ return this.consola.withTag(tag);
1967
2313
  }
1968
2314
  };
2315
+ var defaultLogger = new APILogger();
1969
2316
 
1970
2317
  // src/_api/generated/_cfg_accounts/api.ts
2318
+ init_sdk_gen();
2319
+ init_sdk_gen();
2320
+ init_sdk_gen();
2321
+ init_sdk_gen();
2322
+ init_sdk_gen();
1971
2323
  var API = class {
1972
2324
  static {
1973
2325
  __name(this, "API");
@@ -2043,7 +2395,13 @@ var API = class {
2043
2395
  }
2044
2396
  };
2045
2397
 
2398
+ // src/_api/generated/helpers/index.ts
2399
+ init_auth();
2400
+ init_errors();
2401
+
2046
2402
  // src/_api/generated/_cfg_centrifugo/api.ts
2403
+ init_auth();
2404
+ init_sdk_gen();
2047
2405
  var API2 = class {
2048
2406
  static {
2049
2407
  __name(this, "API");
@@ -2116,6 +2474,11 @@ var API2 = class {
2116
2474
  };
2117
2475
 
2118
2476
  // src/_api/generated/_cfg_totp/api.ts
2477
+ init_auth();
2478
+ init_sdk_gen();
2479
+ init_sdk_gen();
2480
+ init_sdk_gen();
2481
+ init_sdk_gen();
2119
2482
  var API3 = class {
2120
2483
  static {
2121
2484
  __name(this, "API");