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