@djangocfg/api 2.1.332 → 2.1.334

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.
package/dist/clients.cjs CHANGED
@@ -30,805 +30,6 @@ __export(clients_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(clients_exports);
32
32
 
33
- // src/_api/generated/core/bodySerializer.gen.ts
34
- var jsonBodySerializer = {
35
- bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
36
- };
37
-
38
- // src/_api/generated/core/params.gen.ts
39
- var extraPrefixesMap = {
40
- $body_: "body",
41
- $headers_: "headers",
42
- $path_: "path",
43
- $query_: "query"
44
- };
45
- var extraPrefixes = Object.entries(extraPrefixesMap);
46
-
47
- // src/_api/generated/core/serverSentEvents.gen.ts
48
- function createSseClient({
49
- onRequest,
50
- onSseError,
51
- onSseEvent,
52
- responseTransformer,
53
- responseValidator,
54
- sseDefaultRetryDelay,
55
- sseMaxRetryAttempts,
56
- sseMaxRetryDelay,
57
- sseSleepFn,
58
- url,
59
- ...options
60
- }) {
61
- let lastEventId;
62
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
63
- const createStream = /* @__PURE__ */ __name(async function* () {
64
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
65
- let attempt = 0;
66
- const signal = options.signal ?? new AbortController().signal;
67
- while (true) {
68
- if (signal.aborted) break;
69
- attempt++;
70
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
71
- if (lastEventId !== void 0) {
72
- headers.set("Last-Event-ID", lastEventId);
73
- }
74
- try {
75
- const requestInit = {
76
- redirect: "follow",
77
- ...options,
78
- body: options.serializedBody,
79
- headers,
80
- signal
81
- };
82
- let request = new Request(url, requestInit);
83
- if (onRequest) {
84
- request = await onRequest(url, requestInit);
85
- }
86
- const _fetch = options.fetch ?? globalThis.fetch;
87
- const response = await _fetch(request);
88
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
89
- if (!response.body) throw new Error("No body in SSE response");
90
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
91
- let buffer = "";
92
- const abortHandler = /* @__PURE__ */ __name(() => {
93
- try {
94
- reader.cancel();
95
- } catch {
96
- }
97
- }, "abortHandler");
98
- signal.addEventListener("abort", abortHandler);
99
- try {
100
- while (true) {
101
- const { done, value } = await reader.read();
102
- if (done) break;
103
- buffer += value;
104
- buffer = buffer.replace(/\r\n?/g, "\n");
105
- const chunks = buffer.split("\n\n");
106
- buffer = chunks.pop() ?? "";
107
- for (const chunk of chunks) {
108
- const lines = chunk.split("\n");
109
- const dataLines = [];
110
- let eventName;
111
- for (const line of lines) {
112
- if (line.startsWith("data:")) {
113
- dataLines.push(line.replace(/^data:\s*/, ""));
114
- } else if (line.startsWith("event:")) {
115
- eventName = line.replace(/^event:\s*/, "");
116
- } else if (line.startsWith("id:")) {
117
- lastEventId = line.replace(/^id:\s*/, "");
118
- } else if (line.startsWith("retry:")) {
119
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
120
- if (!Number.isNaN(parsed)) {
121
- retryDelay = parsed;
122
- }
123
- }
124
- }
125
- let data;
126
- let parsedJson = false;
127
- if (dataLines.length) {
128
- const rawData = dataLines.join("\n");
129
- try {
130
- data = JSON.parse(rawData);
131
- parsedJson = true;
132
- } catch {
133
- data = rawData;
134
- }
135
- }
136
- if (parsedJson) {
137
- if (responseValidator) {
138
- await responseValidator(data);
139
- }
140
- if (responseTransformer) {
141
- data = await responseTransformer(data);
142
- }
143
- }
144
- onSseEvent?.({
145
- data,
146
- event: eventName,
147
- id: lastEventId,
148
- retry: retryDelay
149
- });
150
- if (dataLines.length) {
151
- yield data;
152
- }
153
- }
154
- }
155
- } finally {
156
- signal.removeEventListener("abort", abortHandler);
157
- reader.releaseLock();
158
- }
159
- break;
160
- } catch (error) {
161
- onSseError?.(error);
162
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
163
- break;
164
- }
165
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
166
- await sleep(backoff);
167
- }
168
- }
169
- }, "createStream");
170
- const stream = createStream();
171
- return { stream };
172
- }
173
- __name(createSseClient, "createSseClient");
174
-
175
- // src/_api/generated/core/pathSerializer.gen.ts
176
- var separatorArrayExplode = /* @__PURE__ */ __name((style) => {
177
- switch (style) {
178
- case "label":
179
- return ".";
180
- case "matrix":
181
- return ";";
182
- case "simple":
183
- return ",";
184
- default:
185
- return "&";
186
- }
187
- }, "separatorArrayExplode");
188
- var separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
189
- switch (style) {
190
- case "form":
191
- return ",";
192
- case "pipeDelimited":
193
- return "|";
194
- case "spaceDelimited":
195
- return "%20";
196
- default:
197
- return ",";
198
- }
199
- }, "separatorArrayNoExplode");
200
- var separatorObjectExplode = /* @__PURE__ */ __name((style) => {
201
- switch (style) {
202
- case "label":
203
- return ".";
204
- case "matrix":
205
- return ";";
206
- case "simple":
207
- return ",";
208
- default:
209
- return "&";
210
- }
211
- }, "separatorObjectExplode");
212
- var serializeArrayParam = /* @__PURE__ */ __name(({
213
- allowReserved,
214
- explode,
215
- name,
216
- style,
217
- value
218
- }) => {
219
- if (!explode) {
220
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
221
- switch (style) {
222
- case "label":
223
- return `.${joinedValues2}`;
224
- case "matrix":
225
- return `;${name}=${joinedValues2}`;
226
- case "simple":
227
- return joinedValues2;
228
- default:
229
- return `${name}=${joinedValues2}`;
230
- }
231
- }
232
- const separator = separatorArrayExplode(style);
233
- const joinedValues = value.map((v) => {
234
- if (style === "label" || style === "simple") {
235
- return allowReserved ? v : encodeURIComponent(v);
236
- }
237
- return serializePrimitiveParam({
238
- allowReserved,
239
- name,
240
- value: v
241
- });
242
- }).join(separator);
243
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
244
- }, "serializeArrayParam");
245
- var serializePrimitiveParam = /* @__PURE__ */ __name(({
246
- allowReserved,
247
- name,
248
- value
249
- }) => {
250
- if (value === void 0 || value === null) {
251
- return "";
252
- }
253
- if (typeof value === "object") {
254
- throw new Error(
255
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
256
- );
257
- }
258
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
259
- }, "serializePrimitiveParam");
260
- var serializeObjectParam = /* @__PURE__ */ __name(({
261
- allowReserved,
262
- explode,
263
- name,
264
- style,
265
- value,
266
- valueOnly
267
- }) => {
268
- if (value instanceof Date) {
269
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
270
- }
271
- if (style !== "deepObject" && !explode) {
272
- let values = [];
273
- Object.entries(value).forEach(([key, v]) => {
274
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
275
- });
276
- const joinedValues2 = values.join(",");
277
- switch (style) {
278
- case "form":
279
- return `${name}=${joinedValues2}`;
280
- case "label":
281
- return `.${joinedValues2}`;
282
- case "matrix":
283
- return `;${name}=${joinedValues2}`;
284
- default:
285
- return joinedValues2;
286
- }
287
- }
288
- const separator = separatorObjectExplode(style);
289
- const joinedValues = Object.entries(value).map(
290
- ([key, v]) => serializePrimitiveParam({
291
- allowReserved,
292
- name: style === "deepObject" ? `${name}[${key}]` : key,
293
- value: v
294
- })
295
- ).join(separator);
296
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
297
- }, "serializeObjectParam");
298
-
299
- // src/_api/generated/core/utils.gen.ts
300
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
301
- var defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
302
- let url = _url;
303
- const matches = _url.match(PATH_PARAM_RE);
304
- if (matches) {
305
- for (const match of matches) {
306
- let explode = false;
307
- let name = match.substring(1, match.length - 1);
308
- let style = "simple";
309
- if (name.endsWith("*")) {
310
- explode = true;
311
- name = name.substring(0, name.length - 1);
312
- }
313
- if (name.startsWith(".")) {
314
- name = name.substring(1);
315
- style = "label";
316
- } else if (name.startsWith(";")) {
317
- name = name.substring(1);
318
- style = "matrix";
319
- }
320
- const value = path[name];
321
- if (value === void 0 || value === null) {
322
- continue;
323
- }
324
- if (Array.isArray(value)) {
325
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
326
- continue;
327
- }
328
- if (typeof value === "object") {
329
- url = url.replace(
330
- match,
331
- serializeObjectParam({
332
- explode,
333
- name,
334
- style,
335
- value,
336
- valueOnly: true
337
- })
338
- );
339
- continue;
340
- }
341
- if (style === "matrix") {
342
- url = url.replace(
343
- match,
344
- `;${serializePrimitiveParam({
345
- name,
346
- value
347
- })}`
348
- );
349
- continue;
350
- }
351
- const replaceValue = encodeURIComponent(
352
- style === "label" ? `.${value}` : value
353
- );
354
- url = url.replace(match, replaceValue);
355
- }
356
- }
357
- return url;
358
- }, "defaultPathSerializer");
359
- var getUrl = /* @__PURE__ */ __name(({
360
- baseUrl,
361
- path,
362
- query,
363
- querySerializer,
364
- url: _url
365
- }) => {
366
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
367
- let url = (baseUrl ?? "") + pathUrl;
368
- if (path) {
369
- url = defaultPathSerializer({ path, url });
370
- }
371
- let search = query ? querySerializer(query) : "";
372
- if (search.startsWith("?")) {
373
- search = search.substring(1);
374
- }
375
- if (search) {
376
- url += `?${search}`;
377
- }
378
- return url;
379
- }, "getUrl");
380
- function getValidRequestBody(options) {
381
- const hasBody = options.body !== void 0;
382
- const isSerializedBody = hasBody && options.bodySerializer;
383
- if (isSerializedBody) {
384
- if ("serializedBody" in options) {
385
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
386
- return hasSerializedBody ? options.serializedBody : null;
387
- }
388
- return options.body !== "" ? options.body : null;
389
- }
390
- if (hasBody) {
391
- return options.body;
392
- }
393
- return void 0;
394
- }
395
- __name(getValidRequestBody, "getValidRequestBody");
396
-
397
- // src/_api/generated/core/auth.gen.ts
398
- var getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
399
- const token = typeof callback === "function" ? await callback(auth2) : callback;
400
- if (!token) {
401
- return;
402
- }
403
- if (auth2.scheme === "bearer") {
404
- return `Bearer ${token}`;
405
- }
406
- if (auth2.scheme === "basic") {
407
- return `Basic ${btoa(token)}`;
408
- }
409
- return token;
410
- }, "getAuthToken");
411
-
412
- // src/_api/generated/client/utils.gen.ts
413
- var createQuerySerializer = /* @__PURE__ */ __name(({
414
- parameters = {},
415
- ...args
416
- } = {}) => {
417
- const querySerializer = /* @__PURE__ */ __name((queryParams) => {
418
- const search = [];
419
- if (queryParams && typeof queryParams === "object") {
420
- for (const name in queryParams) {
421
- const value = queryParams[name];
422
- if (value === void 0 || value === null) {
423
- continue;
424
- }
425
- const options = parameters[name] || args;
426
- if (Array.isArray(value)) {
427
- const serializedArray = serializeArrayParam({
428
- allowReserved: options.allowReserved,
429
- explode: true,
430
- name,
431
- style: "form",
432
- value,
433
- ...options.array
434
- });
435
- if (serializedArray) search.push(serializedArray);
436
- } else if (typeof value === "object") {
437
- const serializedObject = serializeObjectParam({
438
- allowReserved: options.allowReserved,
439
- explode: true,
440
- name,
441
- style: "deepObject",
442
- value,
443
- ...options.object
444
- });
445
- if (serializedObject) search.push(serializedObject);
446
- } else {
447
- const serializedPrimitive = serializePrimitiveParam({
448
- allowReserved: options.allowReserved,
449
- name,
450
- value
451
- });
452
- if (serializedPrimitive) search.push(serializedPrimitive);
453
- }
454
- }
455
- }
456
- return search.join("&");
457
- }, "querySerializer");
458
- return querySerializer;
459
- }, "createQuerySerializer");
460
- var getParseAs = /* @__PURE__ */ __name((contentType) => {
461
- if (!contentType) {
462
- return "stream";
463
- }
464
- const cleanContent = contentType.split(";")[0]?.trim();
465
- if (!cleanContent) {
466
- return;
467
- }
468
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
469
- return "json";
470
- }
471
- if (cleanContent === "multipart/form-data") {
472
- return "formData";
473
- }
474
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
475
- return "blob";
476
- }
477
- if (cleanContent.startsWith("text/")) {
478
- return "text";
479
- }
480
- return;
481
- }, "getParseAs");
482
- var checkForExistence = /* @__PURE__ */ __name((options, name) => {
483
- if (!name) {
484
- return false;
485
- }
486
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
487
- return true;
488
- }
489
- return false;
490
- }, "checkForExistence");
491
- var setAuthParams = /* @__PURE__ */ __name(async ({
492
- security,
493
- ...options
494
- }) => {
495
- for (const auth2 of security) {
496
- if (checkForExistence(options, auth2.name)) {
497
- continue;
498
- }
499
- const token = await getAuthToken(auth2, options.auth);
500
- if (!token) {
501
- continue;
502
- }
503
- const name = auth2.name ?? "Authorization";
504
- switch (auth2.in) {
505
- case "query":
506
- if (!options.query) {
507
- options.query = {};
508
- }
509
- options.query[name] = token;
510
- break;
511
- case "cookie":
512
- options.headers.append("Cookie", `${name}=${token}`);
513
- break;
514
- case "header":
515
- default:
516
- options.headers.set(name, token);
517
- break;
518
- }
519
- }
520
- }, "setAuthParams");
521
- var buildUrl = /* @__PURE__ */ __name((options) => getUrl({
522
- baseUrl: options.baseUrl,
523
- path: options.path,
524
- query: options.query,
525
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
526
- url: options.url
527
- }), "buildUrl");
528
- var mergeConfigs = /* @__PURE__ */ __name((a, b) => {
529
- const config = { ...a, ...b };
530
- if (config.baseUrl?.endsWith("/")) {
531
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
532
- }
533
- config.headers = mergeHeaders(a.headers, b.headers);
534
- return config;
535
- }, "mergeConfigs");
536
- var headersEntries = /* @__PURE__ */ __name((headers) => {
537
- const entries = [];
538
- headers.forEach((value, key) => {
539
- entries.push([key, value]);
540
- });
541
- return entries;
542
- }, "headersEntries");
543
- var mergeHeaders = /* @__PURE__ */ __name((...headers) => {
544
- const mergedHeaders = new Headers();
545
- for (const header of headers) {
546
- if (!header) {
547
- continue;
548
- }
549
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
550
- for (const [key, value] of iterator) {
551
- if (value === null) {
552
- mergedHeaders.delete(key);
553
- } else if (Array.isArray(value)) {
554
- for (const v of value) {
555
- mergedHeaders.append(key, v);
556
- }
557
- } else if (value !== void 0) {
558
- mergedHeaders.set(
559
- key,
560
- typeof value === "object" ? JSON.stringify(value) : value
561
- );
562
- }
563
- }
564
- }
565
- return mergedHeaders;
566
- }, "mergeHeaders");
567
- var Interceptors = class {
568
- static {
569
- __name(this, "Interceptors");
570
- }
571
- fns = [];
572
- clear() {
573
- this.fns = [];
574
- }
575
- eject(id) {
576
- const index = this.getInterceptorIndex(id);
577
- if (this.fns[index]) {
578
- this.fns[index] = null;
579
- }
580
- }
581
- exists(id) {
582
- const index = this.getInterceptorIndex(id);
583
- return Boolean(this.fns[index]);
584
- }
585
- getInterceptorIndex(id) {
586
- if (typeof id === "number") {
587
- return this.fns[id] ? id : -1;
588
- }
589
- return this.fns.indexOf(id);
590
- }
591
- update(id, fn) {
592
- const index = this.getInterceptorIndex(id);
593
- if (this.fns[index]) {
594
- this.fns[index] = fn;
595
- return id;
596
- }
597
- return false;
598
- }
599
- use(fn) {
600
- this.fns.push(fn);
601
- return this.fns.length - 1;
602
- }
603
- };
604
- var createInterceptors = /* @__PURE__ */ __name(() => ({
605
- error: new Interceptors(),
606
- request: new Interceptors(),
607
- response: new Interceptors()
608
- }), "createInterceptors");
609
- var defaultQuerySerializer = createQuerySerializer({
610
- allowReserved: false,
611
- array: {
612
- explode: true,
613
- style: "form"
614
- },
615
- object: {
616
- explode: true,
617
- style: "deepObject"
618
- }
619
- });
620
- var defaultHeaders = {
621
- "Content-Type": "application/json"
622
- };
623
- var createConfig = /* @__PURE__ */ __name((override = {}) => ({
624
- ...jsonBodySerializer,
625
- headers: defaultHeaders,
626
- parseAs: "auto",
627
- querySerializer: defaultQuerySerializer,
628
- ...override
629
- }), "createConfig");
630
-
631
- // src/_api/generated/client/client.gen.ts
632
- var createClient = /* @__PURE__ */ __name((config = {}) => {
633
- let _config = mergeConfigs(createConfig(), config);
634
- const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
635
- const setConfig = /* @__PURE__ */ __name((config2) => {
636
- _config = mergeConfigs(_config, config2);
637
- return getConfig();
638
- }, "setConfig");
639
- const interceptors = createInterceptors();
640
- const beforeRequest = /* @__PURE__ */ __name(async (options) => {
641
- const opts = {
642
- ..._config,
643
- ...options,
644
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
645
- headers: mergeHeaders(_config.headers, options.headers),
646
- serializedBody: void 0
647
- };
648
- if (opts.security) {
649
- await setAuthParams({
650
- ...opts,
651
- security: opts.security
652
- });
653
- }
654
- if (opts.requestValidator) {
655
- await opts.requestValidator(opts);
656
- }
657
- if (opts.body !== void 0 && opts.bodySerializer) {
658
- opts.serializedBody = opts.bodySerializer(opts.body);
659
- }
660
- if (opts.body === void 0 || opts.serializedBody === "") {
661
- opts.headers.delete("Content-Type");
662
- }
663
- const resolvedOpts = opts;
664
- const url = buildUrl(resolvedOpts);
665
- return { opts: resolvedOpts, url };
666
- }, "beforeRequest");
667
- const request = /* @__PURE__ */ __name(async (options) => {
668
- const throwOnError = options.throwOnError ?? _config.throwOnError;
669
- const responseStyle = options.responseStyle ?? _config.responseStyle;
670
- let request2;
671
- let response;
672
- try {
673
- const { opts, url } = await beforeRequest(options);
674
- const requestInit = {
675
- redirect: "follow",
676
- ...opts,
677
- body: getValidRequestBody(opts)
678
- };
679
- request2 = new Request(url, requestInit);
680
- for (const fn of interceptors.request.fns) {
681
- if (fn) {
682
- request2 = await fn(request2, opts);
683
- }
684
- }
685
- const _fetch = opts.fetch;
686
- response = await _fetch(request2);
687
- for (const fn of interceptors.response.fns) {
688
- if (fn) {
689
- response = await fn(response, request2, opts);
690
- }
691
- }
692
- const result = {
693
- request: request2,
694
- response
695
- };
696
- if (response.ok) {
697
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
698
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
699
- let emptyData;
700
- switch (parseAs) {
701
- case "arrayBuffer":
702
- case "blob":
703
- case "text":
704
- emptyData = await response[parseAs]();
705
- break;
706
- case "formData":
707
- emptyData = new FormData();
708
- break;
709
- case "stream":
710
- emptyData = response.body;
711
- break;
712
- case "json":
713
- default:
714
- emptyData = {};
715
- break;
716
- }
717
- return opts.responseStyle === "data" ? emptyData : {
718
- data: emptyData,
719
- ...result
720
- };
721
- }
722
- let data;
723
- switch (parseAs) {
724
- case "arrayBuffer":
725
- case "blob":
726
- case "formData":
727
- case "text":
728
- data = await response[parseAs]();
729
- break;
730
- case "json": {
731
- const text = await response.text();
732
- data = text ? JSON.parse(text) : {};
733
- break;
734
- }
735
- case "stream":
736
- return opts.responseStyle === "data" ? response.body : {
737
- data: response.body,
738
- ...result
739
- };
740
- }
741
- if (parseAs === "json") {
742
- if (opts.responseValidator) {
743
- await opts.responseValidator(data);
744
- }
745
- if (opts.responseTransformer) {
746
- data = await opts.responseTransformer(data);
747
- }
748
- }
749
- return opts.responseStyle === "data" ? data : {
750
- data,
751
- ...result
752
- };
753
- }
754
- const textError = await response.text();
755
- let jsonError;
756
- try {
757
- jsonError = JSON.parse(textError);
758
- } catch {
759
- }
760
- throw jsonError ?? textError;
761
- } catch (error) {
762
- let finalError = error;
763
- for (const fn of interceptors.error.fns) {
764
- if (fn) {
765
- finalError = await fn(finalError, response, request2, options);
766
- }
767
- }
768
- finalError = finalError || {};
769
- if (throwOnError) {
770
- throw finalError;
771
- }
772
- return responseStyle === "data" ? void 0 : {
773
- error: finalError,
774
- request: request2,
775
- response
776
- };
777
- }
778
- }, "request");
779
- const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
780
- const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
781
- const { opts, url } = await beforeRequest(options);
782
- return createSseClient({
783
- ...opts,
784
- body: opts.body,
785
- method,
786
- onRequest: /* @__PURE__ */ __name(async (url2, init) => {
787
- let request2 = new Request(url2, init);
788
- for (const fn of interceptors.request.fns) {
789
- if (fn) {
790
- request2 = await fn(request2, opts);
791
- }
792
- }
793
- return request2;
794
- }, "onRequest"),
795
- serializedBody: getValidRequestBody(opts),
796
- url
797
- });
798
- }, "makeSseFn");
799
- const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
800
- return {
801
- buildUrl: _buildUrl,
802
- connect: makeMethodFn("CONNECT"),
803
- delete: makeMethodFn("DELETE"),
804
- get: makeMethodFn("GET"),
805
- getConfig,
806
- head: makeMethodFn("HEAD"),
807
- interceptors,
808
- options: makeMethodFn("OPTIONS"),
809
- patch: makeMethodFn("PATCH"),
810
- post: makeMethodFn("POST"),
811
- put: makeMethodFn("PUT"),
812
- request,
813
- setConfig,
814
- sse: {
815
- connect: makeSseFn("CONNECT"),
816
- delete: makeSseFn("DELETE"),
817
- get: makeSseFn("GET"),
818
- head: makeSseFn("HEAD"),
819
- options: makeSseFn("OPTIONS"),
820
- patch: makeSseFn("PATCH"),
821
- post: makeSseFn("POST"),
822
- put: makeSseFn("PUT"),
823
- trace: makeSseFn("TRACE")
824
- },
825
- trace: makeMethodFn("TRACE")
826
- };
827
- }, "createClient");
828
-
829
- // src/_api/generated/client.gen.ts
830
- var client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
831
-
832
33
  // src/_api/generated/helpers/auth.ts
833
34
  var ACCESS_KEY = "cfg.access_token";
834
35
  var REFRESH_KEY = "cfg.refresh_token";
@@ -921,15 +122,21 @@ var _apiKeyOverride = null;
921
122
  var _baseUrlOverride = null;
922
123
  var _withCredentials = true;
923
124
  var _onUnauthorized = null;
125
+ var _refreshHandler = null;
126
+ var _client = null;
127
+ function pushClientConfig() {
128
+ if (!_client) return;
129
+ _client.setConfig({
130
+ baseUrl: auth.getBaseUrl(),
131
+ credentials: _withCredentials ? "include" : "same-origin"
132
+ });
133
+ }
134
+ __name(pushClientConfig, "pushClientConfig");
924
135
  var auth = {
925
136
  // ── Storage mode ──────────────────────────────────────────────────
926
137
  getStorageMode() {
927
138
  return _storageMode;
928
139
  },
929
- /**
930
- * Switch the storage backend. Existing values in the *previous*
931
- * backend are NOT migrated — set fresh values after switching.
932
- */
933
140
  setStorageMode(mode) {
934
141
  _storageMode = mode;
935
142
  _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
@@ -955,15 +162,12 @@ var auth = {
955
162
  return _storage.get(ACCESS_KEY) !== null;
956
163
  },
957
164
  // ── API key ───────────────────────────────────────────────────────
958
- /** In-memory API key. Falls back to storage, then NEXT_PUBLIC_API_KEY. */
959
165
  getApiKey() {
960
166
  return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
961
167
  },
962
- /** In-memory only (cleared on reload). */
963
168
  setApiKey(key) {
964
169
  _apiKeyOverride = key;
965
170
  },
966
- /** Persist to active storage backend (localStorage or cookie). */
967
171
  setApiKeyPersist(key) {
968
172
  _apiKeyOverride = key;
969
173
  _storage.set(API_KEY_KEY, key);
@@ -973,7 +177,6 @@ var auth = {
973
177
  _storage.set(API_KEY_KEY, null);
974
178
  },
975
179
  // ── Locale ────────────────────────────────────────────────────────
976
- /** Override locale → falls back to NEXT_LOCALE cookie / navigator.language. */
977
180
  getLocale() {
978
181
  return _localeOverride ?? detectLocale();
979
182
  },
@@ -987,48 +190,43 @@ var auth = {
987
190
  },
988
191
  setBaseUrl(url) {
989
192
  _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
990
- client.setConfig({ baseUrl: this.getBaseUrl() });
193
+ pushClientConfig();
991
194
  },
992
- // ── Credentials toggle (Django session/CSRF cross-origin) ─────────
195
+ // ── Credentials toggle ────────────────────────────────────────────
993
196
  getWithCredentials() {
994
197
  return _withCredentials;
995
198
  },
996
199
  setWithCredentials(value) {
997
200
  _withCredentials = value;
998
- client.setConfig({ credentials: value ? "include" : "same-origin" });
201
+ pushClientConfig();
999
202
  },
1000
203
  // ── 401 handler ───────────────────────────────────────────────────
1001
204
  /**
1002
- * Register a callback fired on every 401 response. Use this to wire
1003
- * a token-refresh flow or a forced logout. Setting `null` removes
1004
- * the handler.
205
+ * Fired when the server returns 401 AND no refresh path recovers it
206
+ * (no refresh token, no refresh handler, refresh failed, or retry
207
+ * still 401). The app should clear local state and redirect to login.
208
+ *
209
+ * NOT fired for 401 that gets transparently recovered by the refresh
210
+ * handler — those are invisible to callers.
1005
211
  */
1006
212
  onUnauthorized(cb) {
1007
213
  _onUnauthorized = cb;
214
+ },
215
+ /**
216
+ * Register the refresh strategy. The handler receives the current
217
+ * refresh token and must call your refresh endpoint, returning
218
+ * `{ access, refresh? }` on success or `null` on failure.
219
+ *
220
+ * @example
221
+ * auth.setRefreshHandler(async (refresh) => {
222
+ * const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
223
+ * return data ? { access: data.access, refresh: data.refresh } : null;
224
+ * });
225
+ */
226
+ setRefreshHandler(fn) {
227
+ _refreshHandler = fn;
1008
228
  }
1009
229
  };
1010
- client.setConfig({
1011
- baseUrl: auth.getBaseUrl(),
1012
- credentials: _withCredentials ? "include" : "same-origin"
1013
- });
1014
- client.interceptors.request.use((request) => {
1015
- const token = auth.getToken();
1016
- if (token) request.headers.set("Authorization", `Bearer ${token}`);
1017
- const locale = auth.getLocale();
1018
- if (locale) request.headers.set("Accept-Language", locale);
1019
- const apiKey = auth.getApiKey();
1020
- if (apiKey) request.headers.set("X-API-Key", apiKey);
1021
- return request;
1022
- });
1023
- client.interceptors.response.use((response) => {
1024
- if (response.status === 401 && _onUnauthorized) {
1025
- try {
1026
- _onUnauthorized(response);
1027
- } catch {
1028
- }
1029
- }
1030
- return response;
1031
- });
1032
230
 
1033
231
  // src/_api/generated/helpers/logger.ts
1034
232
  var import_consola = require("consola");
@@ -1176,6 +374,15 @@ var API = class {
1176
374
  setApiKey(key) {
1177
375
  auth.setApiKey(key);
1178
376
  }
377
+ // ── 401 handling ────────────────────────────────────────────────────────
378
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
379
+ onUnauthorized(cb) {
380
+ auth.onUnauthorized(cb);
381
+ }
382
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
383
+ setRefreshHandler(fn) {
384
+ auth.setRefreshHandler(fn);
385
+ }
1179
386
  };
1180
387
 
1181
388
  // src/_api/generated/_cfg_centrifugo/api.ts
@@ -1230,6 +437,15 @@ var API2 = class {
1230
437
  setApiKey(key) {
1231
438
  auth.setApiKey(key);
1232
439
  }
440
+ // ── 401 handling ────────────────────────────────────────────────────────
441
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
442
+ onUnauthorized(cb) {
443
+ auth.onUnauthorized(cb);
444
+ }
445
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
446
+ setRefreshHandler(fn) {
447
+ auth.setRefreshHandler(fn);
448
+ }
1233
449
  };
1234
450
 
1235
451
  // src/_api/generated/_cfg_totp/api.ts
@@ -1284,6 +500,15 @@ var API3 = class {
1284
500
  setApiKey(key) {
1285
501
  auth.setApiKey(key);
1286
502
  }
503
+ // ── 401 handling ────────────────────────────────────────────────────────
504
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
505
+ onUnauthorized(cb) {
506
+ auth.onUnauthorized(cb);
507
+ }
508
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
509
+ setRefreshHandler(fn) {
510
+ auth.setRefreshHandler(fn);
511
+ }
1287
512
  };
1288
513
 
1289
514
  // src/_api/generated/index.ts