@bereasoftware/nexa 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,934 @@
1
+ /*! Nexa v0.0.1 | (c) 2026 Berea-Soft | MIT License | https://github.com/Berea-Soft/Nexa */
2
+ //#region src/types/index.ts
3
+ var e = (e) => ({
4
+ ok: !0,
5
+ value: e
6
+ }), t = (e) => ({
7
+ ok: !1,
8
+ error: e
9
+ });
10
+ //#endregion
11
+ //#region src/utils/index.ts
12
+ function n(n) {
13
+ return { validate(r) {
14
+ let i = r;
15
+ for (let [e, r] of Object.entries(n)) if (!r(i[e])) return t({
16
+ message: `Validation failed: field "${e}" is invalid`,
17
+ code: "VALIDATION_ERROR"
18
+ });
19
+ return e(r);
20
+ } };
21
+ }
22
+ function r(n) {
23
+ return { validate(r) {
24
+ let i = r, a = n.filter((e) => !(e in i));
25
+ return a.length > 0 ? t({
26
+ message: `Validation failed: missing fields: ${a.join(", ")}`,
27
+ code: "VALIDATION_ERROR"
28
+ }) : e(r);
29
+ } };
30
+ }
31
+ var i = { validate(n) {
32
+ return Array.isArray(n) ? e(n) : t({
33
+ message: "Expected array response",
34
+ code: "VALIDATION_ERROR"
35
+ });
36
+ } }, a = { validate(n) {
37
+ return n && typeof n == "object" && !Array.isArray(n) ? e(n) : t({
38
+ message: "Expected object response",
39
+ code: "VALIDATION_ERROR"
40
+ });
41
+ } }, o = { transform(e) {
42
+ return g(e, m);
43
+ } }, s = { transform(e) {
44
+ return g(e, h);
45
+ } }, c = { transform(e) {
46
+ return _(e);
47
+ } };
48
+ function l(e) {
49
+ return { transform(t) {
50
+ return Array.isArray(t) ? t.map((t) => v(t, e)) : v(t, e);
51
+ } };
52
+ }
53
+ function u(e) {
54
+ return { transform(t) {
55
+ return { [e]: t };
56
+ } };
57
+ }
58
+ var d = class {
59
+ maxAttempts;
60
+ constructor(e = 5) {
61
+ this.maxAttempts = e;
62
+ }
63
+ shouldRetry(e) {
64
+ return e < this.maxAttempts;
65
+ }
66
+ delayMs(e) {
67
+ return e * 50;
68
+ }
69
+ }, f = class {
70
+ retryableStatuses = [
71
+ 408,
72
+ 429,
73
+ 500,
74
+ 502,
75
+ 503,
76
+ 504
77
+ ];
78
+ maxAttempts;
79
+ constructor(e = 3) {
80
+ this.maxAttempts = e;
81
+ }
82
+ shouldRetry(e, t) {
83
+ return e >= this.maxAttempts ? !1 : this.retryableStatuses.includes(t.status ?? 0) || t.code === "TIMEOUT";
84
+ }
85
+ delayMs(e) {
86
+ return Math.min(1e3 * 2 ** (e - 1), 1e4);
87
+ }
88
+ }, p = class {
89
+ failureCount = 0;
90
+ lastFailureTime = 0;
91
+ maxAttempts;
92
+ failureThreshold;
93
+ resetTimeMs;
94
+ constructor(e = 3, t = 5, n = 6e4) {
95
+ this.maxAttempts = e, this.failureThreshold = t, this.resetTimeMs = n;
96
+ }
97
+ shouldRetry(e) {
98
+ return e >= this.maxAttempts || (Date.now() - this.lastFailureTime > this.resetTimeMs && (this.failureCount = 0), this.failureCount >= this.failureThreshold) ? !1 : (this.failureCount++, this.lastFailureTime = Date.now(), !0);
99
+ }
100
+ delayMs(e) {
101
+ return 100 * 2 ** (e - 1);
102
+ }
103
+ reset() {
104
+ this.failureCount = 0, this.lastFailureTime = 0;
105
+ }
106
+ };
107
+ function m(e) {
108
+ return e.replace(/_([a-z])/g, (e, t) => t.toUpperCase());
109
+ }
110
+ function h(e) {
111
+ return e.replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
112
+ }
113
+ function g(e, t) {
114
+ if (!e || typeof e != "object") return e;
115
+ if (Array.isArray(e)) return e.map((e) => g(e, t));
116
+ let n = {};
117
+ for (let [r, i] of Object.entries(e)) n[t(r)] = g(i, t);
118
+ return n;
119
+ }
120
+ function _(e, t = "") {
121
+ let n = {};
122
+ if (Array.isArray(e)) e.forEach((e, r) => {
123
+ let i = t ? `${t}[${r}]` : `[${r}]`;
124
+ Object.assign(n, _(e, i));
125
+ });
126
+ else if (e && typeof e == "object") for (let [r, i] of Object.entries(e)) {
127
+ let e = t ? `${t}.${r}` : r;
128
+ i && typeof i == "object" && !Array.isArray(i) ? Object.assign(n, _(i, e)) : n[e] = i;
129
+ }
130
+ return n;
131
+ }
132
+ function v(e, t) {
133
+ if (!e || typeof e != "object") return {};
134
+ let n = e, r = {};
135
+ for (let e of t) e in n && (r[e] = n[e]);
136
+ return r;
137
+ }
138
+ function y(e) {
139
+ let t = new AbortController(), n = setTimeout(() => t.abort(), e);
140
+ return t.signal.addEventListener("abort", () => clearTimeout(n), { once: !0 }), t;
141
+ }
142
+ async function b(e, t = 3) {
143
+ try {
144
+ return await e();
145
+ } catch (n) {
146
+ if (t <= 0) throw n;
147
+ return b(e, t - 1);
148
+ }
149
+ }
150
+ var x = class {
151
+ cache = /* @__PURE__ */ new Map();
152
+ get(e) {
153
+ let t = this.cache.get(e);
154
+ return t ? Date.now() - t.timestamp > t.ttlMs ? (this.cache.delete(e), null) : t.data : null;
155
+ }
156
+ set(e, t, n = 6e4) {
157
+ this.cache.set(e, {
158
+ data: t,
159
+ timestamp: Date.now(),
160
+ ttlMs: n
161
+ });
162
+ }
163
+ clear() {
164
+ this.cache.clear();
165
+ }
166
+ has(e) {
167
+ let t = this.cache.get(e);
168
+ return t ? Date.now() - t.timestamp > t.ttlMs ? (this.cache.delete(e), !1) : !0 : !1;
169
+ }
170
+ delete(e) {
171
+ this.cache.delete(e);
172
+ }
173
+ };
174
+ function S(e = {}) {
175
+ let t = e.cache || new x(), n = e.ttlMs || 6e4, r = e.cacheableStatuses || [200, 304];
176
+ return async (e, i) => {
177
+ let a = (e.request.method || "GET").toUpperCase(), o = a === "GET", s = `${a}:${e.request.url}`;
178
+ if (o && t.has(s)) {
179
+ let n = t.get(s);
180
+ if (n) {
181
+ e.response = n, e.state.cacheHit = !0;
182
+ return;
183
+ }
184
+ }
185
+ await i(), o && e.response && r.includes(e.response.status) && (t.set(s, e.response, n), e.state.cacheMiss = !0);
186
+ };
187
+ }
188
+ var C = S(), w = class {
189
+ pending = /* @__PURE__ */ new Map();
190
+ async execute(e, t) {
191
+ if (this.pending.has(e)) return this.pending.get(e);
192
+ let n = t().finally(() => {
193
+ this.pending.delete(e);
194
+ });
195
+ return this.pending.set(e, n), n;
196
+ }
197
+ clear() {
198
+ this.pending.clear();
199
+ }
200
+ };
201
+ function T(e = {}) {
202
+ let t = e.deduplicator || new w(), n = e.includeBody ?? !1, r = e.methods || ["GET"];
203
+ return async (e, i) => {
204
+ let a = (e.request.method || "GET").toUpperCase();
205
+ if (!r.includes(a)) {
206
+ await i();
207
+ return;
208
+ }
209
+ let o = `${a}:${e.request.url}`;
210
+ n && e.request.body && (o += `:${JSON.stringify(e.request.body)}`);
211
+ try {
212
+ e.response = await t.execute(o, async () => (await i(), e.response)), e.state.deduped = !0;
213
+ } catch (t) {
214
+ throw e.error = t, t;
215
+ }
216
+ };
217
+ }
218
+ var E = T();
219
+ function D(e) {
220
+ return async (t) => {
221
+ let n = -1;
222
+ async function r(i) {
223
+ if (i <= n) throw Error("next() called multiple times");
224
+ n = i;
225
+ let a = e[i];
226
+ a && await a(t, () => r(i + 1));
227
+ }
228
+ await r(0);
229
+ };
230
+ }
231
+ var O = class {
232
+ middlewares = [];
233
+ use(e) {
234
+ return this.middlewares.push(e), this;
235
+ }
236
+ async execute(e) {
237
+ if (e && typeof e == "object" && "request" in e && "response" in e) {
238
+ let t = e;
239
+ return await D(this.middlewares.map((e) => typeof e == "function" && e.length === 2 ? e : async (t, n) => {
240
+ let r = e;
241
+ t.response.body = await r(t.response.body), await n();
242
+ }))(t), t.response.body;
243
+ }
244
+ let t = e;
245
+ for (let e of this.middlewares) t = await e(t);
246
+ return t;
247
+ }
248
+ clear() {
249
+ this.middlewares = [];
250
+ }
251
+ };
252
+ function k(e, t, n, r = {}) {
253
+ return {
254
+ ok: e >= 200 && e < 300,
255
+ data: t,
256
+ error: n,
257
+ status: e,
258
+ headers: r
259
+ };
260
+ }
261
+ function A(e) {
262
+ return async (t, n) => {
263
+ let r = e.path, i;
264
+ switch (e.method) {
265
+ case "GET":
266
+ i = await t.get(r);
267
+ break;
268
+ case "POST":
269
+ i = await t.post(r, n);
270
+ break;
271
+ case "PUT":
272
+ i = await t.put(r, n);
273
+ break;
274
+ case "PATCH":
275
+ i = await t.patch(r, n);
276
+ break;
277
+ case "DELETE":
278
+ i = await t.delete(r);
279
+ break;
280
+ default: throw Error(`Unsupported method: ${e.method}`);
281
+ }
282
+ return i;
283
+ };
284
+ }
285
+ function j(e) {
286
+ return { request: async (t, n, r) => {
287
+ let i = e[n];
288
+ return await A(i)(t, r);
289
+ } };
290
+ }
291
+ var M = class e {
292
+ subscribers = [];
293
+ errorSubscribers = [];
294
+ completeSubscribers = [];
295
+ subscribe(e, t, n) {
296
+ return e && this.subscribers.push(e), t && this.errorSubscribers.push(t), n && this.completeSubscribers.push(n), { unsubscribe: () => {
297
+ this.subscribers = this.subscribers.filter((t) => t !== e), this.errorSubscribers = this.errorSubscribers.filter((e) => e !== t), this.completeSubscribers = this.completeSubscribers.filter((e) => e !== n);
298
+ } };
299
+ }
300
+ next(e) {
301
+ this.subscribers.forEach((t) => t(e));
302
+ }
303
+ error(e) {
304
+ this.errorSubscribers.forEach((t) => t(e));
305
+ }
306
+ complete() {
307
+ this.completeSubscribers.forEach((e) => e());
308
+ }
309
+ map(t) {
310
+ let n = new e();
311
+ return this.subscribe((e) => n.next(t(e)), (e) => n.error(e), () => n.complete()), n;
312
+ }
313
+ filter(t) {
314
+ let n = new e();
315
+ return this.subscribe((e) => {
316
+ t(e) && n.next(e);
317
+ }, (e) => n.error(e), () => n.complete()), n;
318
+ }
319
+ };
320
+ function N(e) {
321
+ return (t) => {
322
+ if (!e(t)) throw TypeError("Value does not match expected type");
323
+ return t;
324
+ };
325
+ }
326
+ function P(e) {
327
+ return e;
328
+ }
329
+ function F(e) {
330
+ return P(e);
331
+ }
332
+ var I = class {
333
+ _promise;
334
+ resolveFunc;
335
+ rejectFunc;
336
+ constructor() {
337
+ this._promise = new Promise((e, t) => {
338
+ this.resolveFunc = e, this.rejectFunc = t;
339
+ });
340
+ }
341
+ resolve(e) {
342
+ this.resolveFunc(e);
343
+ }
344
+ reject(e) {
345
+ this.rejectFunc(e);
346
+ }
347
+ get promise() {
348
+ return this._promise;
349
+ }
350
+ promise_() {
351
+ return this._promise;
352
+ }
353
+ };
354
+ async function L(e, t = {}) {
355
+ let n = e.body?.getReader();
356
+ if (!n) throw Error("Response body is not readable");
357
+ let r = [], i = 0, a = parseInt(e.headers.get("content-length") || "0", 10);
358
+ for (;;) {
359
+ let { done: e, value: o } = await n.read();
360
+ if (e) break;
361
+ r.push(o), i += o.length, t.onChunk && await t.onChunk(o), t.onProgress && a > 0 && t.onProgress(i, a);
362
+ }
363
+ return R(r, i);
364
+ }
365
+ function R(e, t) {
366
+ let n = new Uint8Array(t), r = 0;
367
+ for (let t of e) n.set(t, r), r += t.byteLength;
368
+ return n;
369
+ }
370
+ async function z(e, t) {
371
+ let n = await L(e);
372
+ if (typeof window > "u") await (await import("fs").then((e) => e.promises)).writeFile(t, n);
373
+ else {
374
+ let e = new Blob([n.buffer], { type: "application/octet-stream" }), r = URL.createObjectURL(e), i = document.createElement("a");
375
+ i.href = r, i.download = t, i.click(), URL.revokeObjectURL(r);
376
+ }
377
+ }
378
+ function B(e = {}) {
379
+ return async (t, n) => {
380
+ if (await n(), t.response && t.response.body && typeof t.response.body == "object" && "getReader" in t.response.body) {
381
+ let n = t.response.body.getReader(), r = [], i = 0, a = parseInt(t.response.headers?.["content-length"] || "0", 10);
382
+ try {
383
+ for (;;) {
384
+ let { done: o, value: s } = await n.read();
385
+ if (o) break;
386
+ r.push(s), i += s.length, e.onChunk && await e.onChunk(s), e.onProgress && a > 0 && e.onProgress(i, a), t.state.streamedChunks = t.state.streamedChunks || [], t.state.streamedChunks.push(s);
387
+ }
388
+ let o = R(r, i);
389
+ t.response.body = o, t.state.streaming = !0, t.state.streamedBytes = i;
390
+ } finally {
391
+ n.releaseLock();
392
+ }
393
+ }
394
+ };
395
+ }
396
+ var V = B({ onProgress: (e, t) => {
397
+ if (t > 0) {
398
+ let n = Math.round(e / t * 100);
399
+ console.log(`⬇️ Streaming: ${n}% (${e}/${t} bytes)`);
400
+ }
401
+ } }), H = class {
402
+ plugins = [];
403
+ cache = new x();
404
+ deduplicator = new w();
405
+ middlewares = [];
406
+ listeners = /* @__PURE__ */ new Map();
407
+ register(e) {
408
+ return this.plugins.push(e), e.setup(this), this.emit("plugin:registered", e.name), this;
409
+ }
410
+ addMiddleware(e) {
411
+ return this.middlewares.push(e), this;
412
+ }
413
+ getCache() {
414
+ return this.cache;
415
+ }
416
+ getDeduplicator() {
417
+ return this.deduplicator;
418
+ }
419
+ getPipeline() {
420
+ return D(this.middlewares);
421
+ }
422
+ async executePipeline(e) {
423
+ await this.getPipeline()(e);
424
+ }
425
+ on(e, t) {
426
+ return this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e)?.add(t), this;
427
+ }
428
+ emit(e, ...t) {
429
+ let n = this.listeners.get(e);
430
+ if (n) for (let e of n) e(...t);
431
+ }
432
+ off(e, t) {
433
+ return this.listeners.get(e)?.delete(t), this;
434
+ }
435
+ getPlugins() {
436
+ return [...this.plugins];
437
+ }
438
+ clear() {
439
+ this.plugins = [], this.middlewares = [], this.listeners.clear(), this.cache.clear(), this.deduplicator.clear();
440
+ }
441
+ }, U = {
442
+ name: "logger",
443
+ setup(e) {
444
+ e.on("request:start", (...e) => {
445
+ let t = e[0];
446
+ console.log(`📤 Request started: ${t}`);
447
+ }), e.on("request:success", (...e) => {
448
+ let t = e[0], n = e[1];
449
+ console.log(`✅ Request succeeded: ${t} (${n})`);
450
+ }), e.on("request:error", (...e) => {
451
+ let t = e[0], n = e[1];
452
+ console.error(`❌ Request failed: ${t}`, n);
453
+ });
454
+ }
455
+ }, W = class {
456
+ name = "metrics";
457
+ metrics = {
458
+ requests: 0,
459
+ errors: 0,
460
+ totalTime: 0,
461
+ avgTime: 0
462
+ };
463
+ setup(e) {
464
+ e.on("request:complete", (...e) => {
465
+ let t = e[0], n = e[1];
466
+ this.metrics.requests++, this.metrics.totalTime += t, this.metrics.avgTime = this.metrics.totalTime / this.metrics.requests, n || this.metrics.errors++;
467
+ });
468
+ }
469
+ getMetrics() {
470
+ return { ...this.metrics };
471
+ }
472
+ }, G = class {
473
+ name = "cache";
474
+ ttlMs;
475
+ constructor(e = 6e4) {
476
+ this.ttlMs = e;
477
+ }
478
+ setup(e) {
479
+ e.addMiddleware(S({ ttlMs: this.ttlMs }));
480
+ }
481
+ }, K = class {
482
+ name = "dedupe";
483
+ setup(e) {
484
+ e.addMiddleware(T());
485
+ }
486
+ }, q = class {
487
+ store = new x();
488
+ get(e) {
489
+ return this.store.get(e);
490
+ }
491
+ set(e, t, n = 6e4) {
492
+ this.store.set(e, t, n);
493
+ }
494
+ has(e) {
495
+ return this.store.has(e);
496
+ }
497
+ clear() {
498
+ this.store.clear();
499
+ }
500
+ }, J = class {
501
+ maxAttempts;
502
+ baseDelayMs;
503
+ constructor(e = 3, t = 100) {
504
+ this.maxAttempts = e, this.baseDelayMs = t;
505
+ }
506
+ shouldRetry(e, t) {
507
+ let n = t.status !== void 0 && t.status >= 500, r = t.code === "NETWORK_ERROR";
508
+ return e < this.maxAttempts && (n || r || t.code === "TIMEOUT");
509
+ }
510
+ delayMs(e) {
511
+ let t = this.baseDelayMs * 2 ** (e - 1), n = Math.random() * t * .1;
512
+ return Math.min(t + n, 3e4);
513
+ }
514
+ }, Y = class {
515
+ running = 0;
516
+ queue = [];
517
+ maxConcurrent;
518
+ constructor(e) {
519
+ this.maxConcurrent = e;
520
+ }
521
+ async acquire() {
522
+ if (this.running < this.maxConcurrent) {
523
+ this.running++;
524
+ return;
525
+ }
526
+ return new Promise((e) => {
527
+ this.queue.push(() => {
528
+ this.running++, e();
529
+ });
530
+ });
531
+ }
532
+ release() {
533
+ this.running--;
534
+ let e = this.queue.shift();
535
+ e && e();
536
+ }
537
+ get pending() {
538
+ return this.queue.length;
539
+ }
540
+ get active() {
541
+ return this.running;
542
+ }
543
+ };
544
+ function X(e) {
545
+ return e == null ? {
546
+ serialized: void 0,
547
+ contentType: null
548
+ } : typeof FormData < "u" && e instanceof FormData ? {
549
+ serialized: e,
550
+ contentType: null
551
+ } : typeof URLSearchParams < "u" && e instanceof URLSearchParams ? {
552
+ serialized: e,
553
+ contentType: "application/x-www-form-urlencoded"
554
+ } : typeof Blob < "u" && e instanceof Blob ? {
555
+ serialized: e,
556
+ contentType: e.type || "application/octet-stream"
557
+ } : e instanceof ArrayBuffer || ArrayBuffer.isView(e) || typeof ReadableStream < "u" && e instanceof ReadableStream ? {
558
+ serialized: e,
559
+ contentType: "application/octet-stream"
560
+ } : typeof e == "string" ? {
561
+ serialized: e,
562
+ contentType: "text/plain"
563
+ } : {
564
+ serialized: JSON.stringify(e),
565
+ contentType: "application/json"
566
+ };
567
+ }
568
+ function Z(e, t) {
569
+ return t ? e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (e, n) => {
570
+ let r = t[n];
571
+ if (r === void 0) throw Error(`Missing path parameter: :${n}`);
572
+ return encodeURIComponent(String(r));
573
+ }) : e;
574
+ }
575
+ var Q = class n {
576
+ requestInterceptors = [];
577
+ responseInterceptors = [];
578
+ cache;
579
+ config;
580
+ requestQueue;
581
+ pendingRequests = /* @__PURE__ */ new Map();
582
+ constructor(e = {}) {
583
+ this.config = {
584
+ baseURL: e.baseURL ?? "",
585
+ defaultHeaders: e.defaultHeaders ?? { "Content-Type": "application/json" },
586
+ defaultTimeout: e.defaultTimeout ?? 3e4,
587
+ validateStatus: e.validateStatus ?? ((e) => e >= 200 && e < 300),
588
+ cacheStrategy: e.cacheStrategy ?? new q(),
589
+ maxConcurrent: e.maxConcurrent ?? 0,
590
+ defaultResponseType: e.defaultResponseType ?? "auto",
591
+ defaultHooks: e.defaultHooks ?? {}
592
+ }, this.cache = this.config.cacheStrategy, this.requestQueue = this.config.maxConcurrent > 0 ? new Y(this.config.maxConcurrent) : null;
593
+ }
594
+ async request(n) {
595
+ let r = {
596
+ ...this.config.defaultHooks,
597
+ ...n.hooks
598
+ }, i = this.getMaxAttempts(n.retry), a = this.getRetryStrategy(n.retry), o = Symbol("request");
599
+ r.onStart?.(this.buildRequest(n)), this.requestQueue && await this.requestQueue.acquire();
600
+ try {
601
+ for (let s = 1; s <= i; s++) try {
602
+ if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
603
+ let t = this.getCacheKey(n), i = this.cache.get(t);
604
+ if (i) {
605
+ let t = i;
606
+ return r.onSuccess?.(t), r.onFinally?.(), e(t);
607
+ }
608
+ }
609
+ let t = this.buildRequest(n);
610
+ for (let e of this.requestInterceptors) t = await e.onRequest(t);
611
+ let i = new AbortController();
612
+ this.pendingRequests.set(o, i), n.signal && n.signal.addEventListener("abort", () => i.abort(), { once: !0 });
613
+ let a = performance.now(), s = await this.fetchWithTimeout(t, n.timeout ?? this.config.defaultTimeout, i), c = performance.now() - a, l = s;
614
+ n.onDownloadProgress && s.body && (l = this.trackDownloadProgress(s, n.onDownloadProgress));
615
+ let u = n.responseType ?? this.config.defaultResponseType, d = await this.parseResponse(l, t, c, u);
616
+ if (!this.config.validateStatus(d.status)) throw {
617
+ message: `Request failed with status ${d.status}`,
618
+ status: d.status,
619
+ statusText: d.statusText,
620
+ code: "HTTP_ERROR"
621
+ };
622
+ if (n.validate) {
623
+ let e = n.validate.validate(d.data);
624
+ if (!e.ok) return e;
625
+ }
626
+ n.transform && (d.data = n.transform.transform(d.data));
627
+ let f = d;
628
+ for (let e of this.responseInterceptors) f = await e.onResponse(f);
629
+ if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
630
+ let e = this.getCacheKey(n);
631
+ this.cache.set(e, f, n.cache.ttlMs);
632
+ }
633
+ return r.onSuccess?.(f), this.pendingRequests.delete(o), e(f);
634
+ } catch (e) {
635
+ let n = this.isHttpErrorDetails(e) ? e : this.normalizeError(e);
636
+ if (s < i && a.shouldRetry(s, n)) {
637
+ r.onRetry?.(s, n);
638
+ let e = a.delayMs(s);
639
+ await this.delay(e);
640
+ continue;
641
+ }
642
+ let c = n;
643
+ for (let e of this.responseInterceptors) e.onError && (c = await e.onError(c));
644
+ return r.onError?.(c), this.pendingRequests.delete(o), t(c);
645
+ }
646
+ let s = {
647
+ message: "Max retries exceeded",
648
+ code: "MAX_RETRIES"
649
+ };
650
+ return r.onError?.(s), t(s);
651
+ } finally {
652
+ r.onFinally?.(), this.requestQueue && this.requestQueue.release();
653
+ }
654
+ }
655
+ get(e, t) {
656
+ return this.request({
657
+ ...t,
658
+ url: e,
659
+ method: "GET"
660
+ });
661
+ }
662
+ post(e, t, n) {
663
+ return this.request({
664
+ ...n,
665
+ url: e,
666
+ method: "POST",
667
+ body: t
668
+ });
669
+ }
670
+ put(e, t, n) {
671
+ return this.request({
672
+ ...n,
673
+ url: e,
674
+ method: "PUT",
675
+ body: t
676
+ });
677
+ }
678
+ patch(e, t, n) {
679
+ return this.request({
680
+ ...n,
681
+ url: e,
682
+ method: "PATCH",
683
+ body: t
684
+ });
685
+ }
686
+ delete(e, t) {
687
+ return this.request({
688
+ ...t,
689
+ url: e,
690
+ method: "DELETE"
691
+ });
692
+ }
693
+ head(e, t) {
694
+ return this.request({
695
+ ...t,
696
+ url: e,
697
+ method: "HEAD"
698
+ });
699
+ }
700
+ options(e, t) {
701
+ return this.request({
702
+ ...t,
703
+ url: e,
704
+ method: "OPTIONS"
705
+ });
706
+ }
707
+ addRequestInterceptor(e) {
708
+ return this.requestInterceptors.push(e), () => {
709
+ let t = this.requestInterceptors.indexOf(e);
710
+ t !== -1 && this.requestInterceptors.splice(t, 1);
711
+ };
712
+ }
713
+ addResponseInterceptor(e) {
714
+ return this.responseInterceptors.push(e), () => {
715
+ let t = this.responseInterceptors.indexOf(e);
716
+ t !== -1 && this.responseInterceptors.splice(t, 1);
717
+ };
718
+ }
719
+ clearInterceptors() {
720
+ this.requestInterceptors = [], this.responseInterceptors = [];
721
+ }
722
+ clearCache() {
723
+ this.cache.clear();
724
+ }
725
+ cancelAll() {
726
+ for (let e of this.pendingRequests.values()) e.abort();
727
+ this.pendingRequests.clear();
728
+ }
729
+ get activeRequests() {
730
+ return this.pendingRequests.size;
731
+ }
732
+ get queueStats() {
733
+ return {
734
+ active: this.requestQueue?.active ?? this.pendingRequests.size,
735
+ pending: this.requestQueue?.pending ?? 0
736
+ };
737
+ }
738
+ extend(e = {}) {
739
+ let t = new n({
740
+ baseURL: e.baseURL ?? this.config.baseURL,
741
+ defaultHeaders: {
742
+ ...this.config.defaultHeaders,
743
+ ...e.defaultHeaders
744
+ },
745
+ defaultTimeout: e.defaultTimeout ?? this.config.defaultTimeout,
746
+ validateStatus: e.validateStatus ?? this.config.validateStatus,
747
+ cacheStrategy: e.cacheStrategy ?? this.cache,
748
+ maxConcurrent: e.maxConcurrent ?? this.config.maxConcurrent,
749
+ defaultResponseType: e.defaultResponseType ?? this.config.defaultResponseType,
750
+ defaultHooks: {
751
+ ...this.config.defaultHooks,
752
+ ...e.defaultHooks
753
+ }
754
+ });
755
+ for (let e of this.requestInterceptors) t.addRequestInterceptor(e);
756
+ for (let e of this.responseInterceptors) t.addResponseInterceptor(e);
757
+ return t;
758
+ }
759
+ async *paginate(e, t, n = {}) {
760
+ let r = { ...n };
761
+ for (;;) {
762
+ let n = await this.get(e, r);
763
+ if (!n.ok) break;
764
+ yield t.getItems(n.value.data);
765
+ let i = t.getNextPage(n.value.data, r);
766
+ if (!i) break;
767
+ r = i;
768
+ }
769
+ }
770
+ async poll(e, n, r = {}) {
771
+ let i = n.maxAttempts ?? 0;
772
+ for (let t = 1; i === 0 || t <= i; t++) {
773
+ let a = await this.get(e, r);
774
+ if (!a.ok || (n.onPoll?.(a.value.data, t), n.until(a.value.data))) return a;
775
+ if (i > 0 && t >= i) break;
776
+ await this.delay(n.intervalMs);
777
+ }
778
+ return t({
779
+ message: `Polling exhausted after ${i} attempts`,
780
+ code: "POLL_EXHAUSTED"
781
+ });
782
+ }
783
+ buildRequest(e) {
784
+ let t = Z(e.url, e.params);
785
+ return {
786
+ url: this.buildUrl(t, e.query),
787
+ method: e.method ?? "GET",
788
+ headers: {
789
+ ...this.config.defaultHeaders,
790
+ ...e.headers
791
+ },
792
+ body: e.body,
793
+ params: e.params
794
+ };
795
+ }
796
+ buildUrl(e, t) {
797
+ let n = this.config.baseURL + e;
798
+ if (t && Object.keys(t).length > 0) {
799
+ let e = new URLSearchParams();
800
+ Object.entries(t).forEach(([t, n]) => {
801
+ e.append(t, String(n));
802
+ }), n += `?${e.toString()}`;
803
+ }
804
+ return n;
805
+ }
806
+ getCacheKey(e) {
807
+ let t = Z(e.url, e.params), n = e.query ? JSON.stringify(e.query) : "";
808
+ return `${e.method ?? "GET"}:${t}${n ? ":" + n : ""}`;
809
+ }
810
+ fetchWithTimeout(e, t, n) {
811
+ let { serialized: r, contentType: i } = X(e.body), a = { ...e.headers };
812
+ return i ? a["Content-Type"] = i : i === null && r instanceof FormData && delete a["Content-Type"], new Promise((i, o) => {
813
+ let s = setTimeout(() => {
814
+ n.abort();
815
+ let e = /* @__PURE__ */ Error("Request timed out");
816
+ e.name = "TimeoutError", o(e);
817
+ }, t);
818
+ fetch(e.url, {
819
+ method: e.method,
820
+ headers: a,
821
+ body: r,
822
+ signal: n.signal
823
+ }).then((e) => {
824
+ clearTimeout(s), i(e);
825
+ }, (e) => {
826
+ clearTimeout(s), o(e);
827
+ });
828
+ });
829
+ }
830
+ trackDownloadProgress(e, t) {
831
+ let n = parseInt(e.headers.get("content-length") || "0", 10), r = e.body?.getReader();
832
+ if (!r) return e;
833
+ let i = 0, a = new ReadableStream({ async pull(e) {
834
+ let { done: a, value: o } = await r.read();
835
+ if (a) {
836
+ e.close();
837
+ return;
838
+ }
839
+ i += o.byteLength, t({
840
+ loaded: i,
841
+ total: n,
842
+ percent: n > 0 ? Math.round(i / n * 100) : 0
843
+ }), e.enqueue(o);
844
+ } });
845
+ return new Response(a, {
846
+ headers: e.headers,
847
+ status: e.status,
848
+ statusText: e.statusText
849
+ });
850
+ }
851
+ async parseResponse(e, t, n, r) {
852
+ let i = await this.parseBody(e, r);
853
+ return {
854
+ status: e.status,
855
+ statusText: e.statusText,
856
+ headers: e.headers,
857
+ data: i,
858
+ request: t,
859
+ duration: n
860
+ };
861
+ }
862
+ async parseBody(e, t) {
863
+ switch (t) {
864
+ case "json": return await e.json();
865
+ case "text": return await e.text();
866
+ case "blob": return await e.blob();
867
+ case "arrayBuffer": return await e.arrayBuffer();
868
+ case "formData": return await e.formData();
869
+ case "stream": return e.body;
870
+ default: {
871
+ let t = e.headers.get("content-type") ?? "";
872
+ if (t.includes("application/json")) return await e.json();
873
+ if (t.includes("text/")) return await e.text();
874
+ if (t.includes("multipart/form-data")) return await e.formData();
875
+ if (t.includes("application/octet-stream") || t.includes("image/") || t.includes("audio/") || t.includes("video/")) return await e.blob();
876
+ try {
877
+ return await e.json();
878
+ } catch {
879
+ return await e.text();
880
+ }
881
+ }
882
+ }
883
+ }
884
+ normalizeError(e) {
885
+ return e instanceof Error && e.name === "TimeoutError" ? {
886
+ message: "Request timed out",
887
+ code: "TIMEOUT"
888
+ } : e instanceof DOMException && e.name === "AbortError" ? {
889
+ message: "Request aborted",
890
+ code: "ABORTED"
891
+ } : e instanceof Error ? e.name === "AbortError" || e.message.includes("abort") ? {
892
+ message: "Request aborted",
893
+ code: "ABORTED"
894
+ } : {
895
+ message: e.message,
896
+ code: e.name === "TypeError" ? "NETWORK_ERROR" : "UNKNOWN_ERROR",
897
+ originalError: e
898
+ } : {
899
+ message: String(e),
900
+ code: "UNKNOWN_ERROR",
901
+ originalError: e
902
+ };
903
+ }
904
+ isHttpErrorDetails(e) {
905
+ return typeof e == "object" && !!e && "message" in e && "code" in e;
906
+ }
907
+ getMaxAttempts(e) {
908
+ return e ? "maxAttempts" in e ? e.maxAttempts : 100 : 1;
909
+ }
910
+ getRetryStrategy(e) {
911
+ return e ? "shouldRetry" in e ? e : new J(e.maxAttempts, e.backoffMs) : {
912
+ shouldRetry: () => !1,
913
+ delayMs: () => 0
914
+ };
915
+ }
916
+ delay(e) {
917
+ return new Promise((t) => setTimeout(t, e));
918
+ }
919
+ }, $ = class extends Error {
920
+ status;
921
+ code;
922
+ response;
923
+ constructor(e, t, n, r) {
924
+ super(e), this.name = "HttpError", this.status = t, this.code = n, this.response = r;
925
+ }
926
+ };
927
+ function ee(e) {
928
+ return e instanceof $;
929
+ }
930
+ function te(e) {
931
+ return new Q(e);
932
+ }
933
+ //#endregion
934
+ export { d as AggressiveRetry, G as CachePlugin, x as CacheStore, p as CircuitBreakerRetry, f as ConservativeRetry, K as DedupePlugin, I as Defer, t as Err, Q as HttpClient, $ as HttpError, U as LoggerPlugin, W as MetricsPlugin, O as MiddlewarePipeline, e as Ok, H as PluginManager, w as RequestDeduplicator, M as TypedObservable, C as cacheMiddleware, F as createApiUrl, S as createCacheMiddleware, T as createDedupeMiddleware, te as createHttpClient, D as createPipeline, l as createProjectionTransformer, r as createRequiredFieldsValidator, n as createSchemaValidator, B as createStreamingMiddleware, N as createTypeGuard, j as createTypedApiClient, A as createTypedRequest, k as createTypedResponse, P as createUrl, u as createWrapperTransformer, E as dedupeMiddleware, L as handleStream, ee as isHttpError, b as retry, z as streamToFile, V as streamingMiddleware, s as transformCamelToSnake, c as transformFlatten, o as transformSnakeToCamel, i as validatorIsArray, a as validatorIsObject, y as withTimeout };