@ahoo-wang/fetcher-storage 2.9.1 → 2.9.2

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/index.es.js CHANGED
@@ -1,4 +1,5 @@
1
- class $ {
1
+ import { nameGenerator as i, SerialTypedEventBus as n } from "@ahoo-wang/fetcher-eventbus";
2
+ class a {
2
3
  constructor() {
3
4
  this.store = /* @__PURE__ */ new Map();
4
5
  }
@@ -47,11 +48,11 @@ class $ {
47
48
  this.store.set(e, t);
48
49
  }
49
50
  }
50
- function B() {
51
+ function l() {
51
52
  return typeof window < "u";
52
53
  }
53
- const V = () => B() ? window.localStorage : new $();
54
- class k {
54
+ const o = () => l() ? window.localStorage : new a();
55
+ class h {
55
56
  /**
56
57
  * Serializes a value to a JSON string
57
58
  * @param value The value to serialize
@@ -69,7 +70,7 @@ class k {
69
70
  return JSON.parse(e);
70
71
  }
71
72
  }
72
- class G {
73
+ class u {
73
74
  /**
74
75
  * Returns the value as-is without serialization
75
76
  * @param value The value to pass through
@@ -87,1322 +88,22 @@ class G {
87
88
  return e;
88
89
  }
89
90
  }
90
- const ve = new k(), U = new G();
91
- function L() {
92
- return U;
91
+ const d = new h(), c = new u();
92
+ function y() {
93
+ return c;
93
94
  }
94
- function j(r) {
95
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(r);
96
- }
97
- function X(r, e) {
98
- return j(e) ? e : e ? r.replace(/\/?\/$/, "") + "/" + e.replace(/^\/+/, "") : r;
99
- }
100
- function D(r) {
101
- return r === 1 ? Y : K;
102
- }
103
- function x(r, e, t) {
104
- return t ? r.replace(e, (s, n) => {
105
- const a = t[n];
106
- if (a === void 0)
107
- throw new Error(`Missing required path parameter: ${n}`);
108
- return encodeURIComponent(a);
109
- }) : r;
110
- }
111
- function b(r, e) {
112
- const t = [];
113
- let s;
114
- for (; (s = e.exec(r)) !== null; )
115
- t.push(s[1]);
116
- return t;
117
- }
118
- const v = class p {
119
- /**
120
- * Extracts path parameters from a URL string.
121
- *
122
- * @param urlTemplate - The URL string to extract path parameters from
123
- * @returns An array of path parameter names without the curly braces, or an empty array if no matches found
124
- *
125
- * @example
126
- * ```typescript
127
- * const resolver = uriTemplateResolver;
128
- *
129
- * // Extract multiple parameters
130
- * const params = resolver.extractPathParams('/users/{id}/posts/{postId}');
131
- * // params = ['id', 'postId']
132
- *
133
- * // Extract parameters from full URLs
134
- * const urlParams = resolver.extractPathParams('https://api.example.com/{resource}/{id}');
135
- * // urlParams = ['resource', 'id']
136
- *
137
- * // No parameters
138
- * const noParams = resolver.extractPathParams('/users/profile');
139
- * // noParams = []
140
- * ```
141
- */
142
- extractPathParams(e) {
143
- return b(
144
- e,
145
- p.PATH_PARAM_REGEX
146
- );
147
- }
148
- /**
149
- * Replaces placeholders in the URL with path parameters.
150
- *
151
- * @param urlTemplate - Path string containing placeholders, e.g., "http://localhost/users/{id}/posts/{postId}"
152
- * @param pathParams - Path parameter object used to replace placeholders in the URL
153
- * @returns Path string with placeholders replaced
154
- * @throws Error when required path parameters are missing
155
- *
156
- * @example
157
- * ```typescript
158
- * const resolver = uriTemplateResolver;
159
- *
160
- * // Replace parameters
161
- * const url = resolver.resolve('/users/{id}/posts/{postId}', { id: 123, postId: 456 });
162
- * // url = '/users/123/posts/456'
163
- *
164
- * // Handle string parameter values
165
- * const stringUrl = resolver.resolve('/users/{username}', { username: 'john_doe' });
166
- * // stringUrl = '/users/john_doe'
167
- *
168
- * // URL encode parameter values
169
- * const encodedUrl = resolver.resolve('/search/{query}', { query: 'hello world' });
170
- * // encodedUrl = '/search/hello%20world'
171
- * ```
172
- *
173
- * @example
174
- * ```typescript
175
- * // Missing required parameter throws an error
176
- * const resolver = uriTemplateResolver;
177
- * try {
178
- * resolver.resolve('/users/{id}', { name: 'John' });
179
- * } catch (error) {
180
- * console.error(error.message); // "Missing required path parameter: id"
181
- * }
182
- * ```
183
- */
184
- resolve(e, t) {
185
- return x(
186
- e,
187
- p.PATH_PARAM_REGEX,
188
- t
189
- );
190
- }
191
- };
192
- v.PATH_PARAM_REGEX = /{([^}]+)}/g;
193
- let J = v;
194
- const K = new J(), S = class m {
195
- /**
196
- * Extracts path parameters from an Express-style URL string.
197
- *
198
- * @param urlTemplate - The URL string with Express-style parameter placeholders
199
- * @returns An array of parameter names extracted from the URL template
200
- *
201
- * @example
202
- * ```typescript
203
- * const resolver = new expressUrlTemplateResolver;
204
- *
205
- * // Extract multiple parameters
206
- * const params = resolver.extractPathParams('/users/:id/posts/:postId');
207
- * // params = ['id', 'postId']
208
- *
209
- * // No parameters
210
- * const noParams = resolver.extractPathParams('/users/profile');
211
- * // noParams = []
212
- * ```
213
- */
214
- extractPathParams(e) {
215
- return b(
216
- e,
217
- m.PATH_PARAM_REGEX
218
- );
219
- }
220
- /**
221
- * Replaces Express-style placeholders in the URL with path parameters.
222
- *
223
- * @param urlTemplate - Path string containing Express-style placeholders
224
- * @param pathParams - Object containing parameter values to replace placeholders
225
- * @returns Path string with placeholders replaced
226
- * @throws Error when required path parameters are missing
227
- *
228
- * @example
229
- * ```typescript
230
- * const resolver = expressUrlTemplateResolver;
231
- *
232
- * // Replace parameters
233
- * const url = resolver.resolve('/users/:id/posts/:postId', { id: 123, postId: 456 });
234
- * // url = '/users/123/posts/456'
235
- *
236
- * // Handle string parameter values
237
- * const stringUrl = resolver.resolve('/users/:username', { username: 'john_doe' });
238
- * // stringUrl = '/users/john_doe'
239
- * ```
240
- *
241
- * @example
242
- * ```typescript
243
- * // Missing required parameter throws an error
244
- * const resolver = expressUrlTemplateResolver;
245
- * try {
246
- * resolver.resolve('/users/:id', { name: 'John' });
247
- * } catch (error) {
248
- * console.error(error.message); // "Missing required path parameter: id"
249
- * }
250
- * ```
251
- */
252
- resolve(e, t) {
253
- return x(
254
- e,
255
- m.PATH_PARAM_REGEX,
256
- t
257
- );
258
- }
259
- };
260
- S.PATH_PARAM_REGEX = /:([^/]+)/g;
261
- let Q = S;
262
- const Y = new Q();
263
- class W {
264
- /**
265
- * Initializes a new UrlBuilder instance.
266
- *
267
- * @param baseURL - Base URL that all constructed URLs will be based on
268
- * @param urlTemplateStyle - Optional style configuration for URL template resolution.
269
- * Determines how path parameters are parsed and resolved.
270
- * Defaults to UriTemplate style if not specified.
271
- *
272
- * @example
273
- * ```typescript
274
- * // Create a URL builder with default URI template style
275
- * const urlBuilder = new UrlBuilder('https://api.example.com');
276
- *
277
- * // Create a URL builder with Express-style template resolution
278
- * const expressUrlBuilder = new UrlBuilder('https://api.example.com', UrlTemplateStyle.Express);
279
- * ```
280
- */
281
- constructor(e, t) {
282
- this.baseURL = e, this.urlTemplateResolver = D(t);
283
- }
284
- /**
285
- * Builds a complete URL, including path parameter replacement and query parameter addition.
286
- *
287
- * @param url - URL path to build (e.g., '/users/{id}/posts')
288
- * @param params - URL parameters including path and query parameters
289
- * @returns Complete URL string with base URL, path parameters interpolated, and query string appended
290
- * @throws Error when required path parameters are missing
291
- *
292
- * @example
293
- * ```typescript
294
- * const urlBuilder = new UrlBuilder('https://api.example.com');
295
- * const url = urlBuilder.build('/users/{id}/posts/{postId}', {
296
- * path: { id: 123, postId: 456 },
297
- * query: { filter: 'active', limit: 10 }
298
- * });
299
- * // Result: https://api.example.com/users/123/posts/456?filter=active&limit=10
300
- * ```
301
- */
302
- build(e, t) {
303
- const s = t?.path, n = t?.query, a = X(this.baseURL, e);
304
- let i = this.urlTemplateResolver.resolve(a, s);
305
- if (n) {
306
- const c = new URLSearchParams(n).toString();
307
- c && (i += "?" + c);
308
- }
309
- return i;
310
- }
311
- /**
312
- * Resolves a complete URL from a FetchRequest.
313
- *
314
- * Used internally by the Fetcher to build the final URL for a request
315
- * by combining the request URL with its URL parameters using this UrlBuilder.
316
- *
317
- * @param request - The FetchRequest containing URL and URL parameters
318
- * @returns Complete resolved URL string
319
- */
320
- resolveRequestUrl(e) {
321
- return this.build(e.url, e.urlParams);
322
- }
323
- }
324
- let I = class H extends Error {
325
- /**
326
- * Creates a new FetcherError instance.
327
- *
328
- * @param errorMsg - Optional error message. If not provided, will use the cause's message or a default message.
329
- * @param cause - Optional underlying error that caused this error.
330
- */
331
- constructor(e, t) {
332
- const s = e || t?.message || "An error occurred in the fetcher";
333
- super(s), this.cause = t, this.name = "FetcherError", t?.stack && (this.stack = t.stack), Object.setPrototypeOf(this, H.prototype);
334
- }
335
- }, g = class O extends I {
336
- /**
337
- * Creates a new ExchangeError instance.
338
- *
339
- * @param exchange - The FetchExchange object containing request/response/error information.
340
- * @param errorMsg - An optional error message.
341
- */
342
- constructor(e, t) {
343
- const s = t || e.error?.message || e.response?.statusText || `Request to ${e.request.url} failed during exchange`;
344
- super(s, e.error), this.exchange = e, this.name = "ExchangeError", Object.setPrototypeOf(this, O.prototype);
345
- }
346
- };
347
- class w extends I {
348
- /**
349
- * Creates a new FetchTimeoutError instance.
350
- *
351
- * @param request - The request options that timed out
352
- */
353
- constructor(e) {
354
- const t = e.method || "GET", s = `Request timeout of ${e.timeout}ms exceeded for ${t} ${e.url}`;
355
- super(s), this.name = "FetchTimeoutError", this.request = e, Object.setPrototypeOf(this, w.prototype);
356
- }
357
- }
358
- function Z(r, e) {
359
- return typeof r < "u" ? r : e;
360
- }
361
- async function ee(r) {
362
- const e = r.url, t = r.timeout, s = r;
363
- if (r.signal)
364
- return await fetch(e, s);
365
- if (!t)
366
- return r.abortController && (s.signal = r.abortController.signal), await fetch(e, s);
367
- const n = r.abortController ?? new AbortController();
368
- r.abortController = n, s.signal = n.signal;
369
- let a = null;
370
- const i = new Promise((c, M) => {
371
- a = setTimeout(() => {
372
- a && clearTimeout(a);
373
- const T = new w(r);
374
- n.abort(T), M(T);
375
- }, t);
376
- });
377
- try {
378
- return await Promise.race([fetch(e, s), i]);
379
- } finally {
380
- a && clearTimeout(a);
381
- }
382
- }
383
- const te = (r) => r, re = (r) => r.requiredResponse, R = {
384
- /**
385
- * Returns the original FetchExchange object
386
- */
387
- Exchange: te,
388
- /**
389
- * Extracts the raw Response object
390
- */
391
- Response: re
392
- };
393
- function se(r, e) {
394
- if (e ??= /* @__PURE__ */ new Map(), !r)
395
- return e;
396
- if (r instanceof Map) {
397
- for (const [t, s] of r)
398
- e.set(t, s);
399
- return e;
400
- }
401
- for (const [t, s] of Object.entries(r))
402
- e.set(t, s);
403
- return e;
404
- }
405
- class ne {
406
- constructor(e) {
407
- this.fetcher = e.fetcher, this.request = e.request, this.resultExtractor = e.resultExtractor ?? R.Exchange, this.attributes = se(e.attributes), this._response = e.response, this.error = e.error;
408
- }
409
- /**
410
- * Ensures that request headers object exists, creating it if necessary.
411
- *
412
- * This method checks if the request headers object is present and initializes
413
- * it as an empty object if it's missing. This guarantees that headers can
414
- * be safely accessed and modified after calling this method.
415
- *
416
- * @returns The request headers object, guaranteed to be non-null
417
- */
418
- ensureRequestHeaders() {
419
- return this.request.headers || (this.request.headers = {}), this.request.headers;
420
- }
421
- /**
422
- * Ensures that request URL parameters object exists with all required properties,
423
- * creating them if necessary.
424
- *
425
- * This method checks if the request URL parameters object is present and initializes
426
- * it with empty path and query objects if it's missing. It also ensures that both
427
- * path and query sub-objects exist. This guarantees that URL parameters can be
428
- * safely accessed and modified after calling this method.
429
- *
430
- * @returns The request URL parameters object with guaranteed non-null path and query properties
431
- */
432
- ensureRequestUrlParams() {
433
- return this.request.urlParams || (this.request.urlParams = {
434
- path: {},
435
- query: {}
436
- }), this.request.urlParams.path || (this.request.urlParams.path = {}), this.request.urlParams.query || (this.request.urlParams.query = {}), this.request.urlParams;
437
- }
438
- /**
439
- * Checks if the exchange has an error.
440
- *
441
- * @returns true if an error is present, false otherwise
442
- */
443
- hasError() {
444
- return !!this.error;
445
- }
446
- /**
447
- * Sets the response object for this exchange.
448
- * Also invalidates the cached extracted result to ensure data consistency
449
- * when the response changes.
450
- *
451
- * @param response - The Response object to set, or undefined to clear the response
452
- */
453
- set response(e) {
454
- this._response = e, this.cachedExtractedResult = void 0;
455
- }
456
- /**
457
- * Gets the response object for this exchange.
458
- *
459
- * @returns The response object if available, undefined otherwise
460
- */
461
- get response() {
462
- return this._response;
463
- }
464
- /**
465
- * Checks if the exchange has a response.
466
- *
467
- * @returns true if a response is present, false otherwise
468
- */
469
- hasResponse() {
470
- return !!this.response;
471
- }
472
- /**
473
- * Gets the required response object, throwing an error if no response is available.
474
- *
475
- * This getter ensures that a response object is available, and throws an ExchangeError
476
- * with details about the request if no response was received. This is useful for
477
- * guaranteeing that downstream code always has a valid Response object to work with.
478
- *
479
- * @throws {ExchangeError} If no response is available for the current exchange
480
- * @returns The Response object for this exchange
481
- */
482
- get requiredResponse() {
483
- if (!this.response)
484
- throw new g(
485
- this,
486
- `Request to ${this.request.url} failed with no response`
487
- );
488
- return this.response;
489
- }
490
- /**
491
- * Extracts the result by applying the result extractor to the exchange.
492
- * The result is cached after the first computation to avoid repeated computations.
493
- *
494
- * @returns The extracted result
495
- */
496
- async extractResult() {
497
- return this.cachedExtractedResult !== void 0 ? await this.cachedExtractedResult : (this.cachedExtractedResult = this.resultExtractor(this), await this.cachedExtractedResult);
498
- }
499
- }
500
- var o = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r.TRACE = "TRACE", r))(o || {});
501
- const h = "Content-Type", f = class {
502
- };
503
- f.APPLICATION_JSON = "application/json", f.TEXT_EVENT_STREAM = "text/event-stream";
504
- let C = f;
505
- const ae = "UrlResolveInterceptor", N = Number.MIN_SAFE_INTEGER + 1e3;
506
- class oe {
507
- constructor() {
508
- this.name = ae, this.order = N;
509
- }
510
- /**
511
- * Resolves the final URL by combining the base URL, path parameters, and query parameters.
512
- *
513
- * @param exchange - The fetch exchange containing the request information
514
- */
515
- intercept(e) {
516
- const t = e.request;
517
- t.url = e.fetcher.urlBuilder.resolveRequestUrl(t);
518
- }
519
- }
520
- const ie = "RequestBodyInterceptor", ue = N + 1e3;
521
- class ce {
522
- constructor() {
523
- this.name = ie, this.order = ue;
524
- }
525
- /**
526
- * Checks if the provided body is of a supported complex type that doesn't require JSON serialization.
527
- *
528
- * @param body - The request body to check
529
- * @returns True if the body is an ArrayBuffer, TypedArray, DataView or ReadableStream, false otherwise
530
- */
531
- isSupportedComplexBodyType(e) {
532
- return e instanceof ArrayBuffer || ArrayBuffer.isView(e) || e instanceof ReadableStream;
533
- }
534
- /**
535
- * Checks if the provided body is of a type that automatically appends Content-Type header.
536
- *
537
- * @param body - The request body to check
538
- * @returns True if the body is a Blob, File, FormData or URLSearchParams, false otherwise
539
- */
540
- isAutoAppendContentType(e) {
541
- return e instanceof Blob || e instanceof File || e instanceof FormData || e instanceof URLSearchParams;
542
- }
543
- /**
544
- * Attempts to convert request body to a valid fetch API body type.
545
- *
546
- * This method follows a specific processing order to handle different types of request bodies:
547
- * 1. Check if the body is null or undefined and return early if so
548
- * 2. Check if the body is a non-object type and return early if so
549
- * 3. Check if the body is a type that automatically appends Content-Type header
550
- * 4. Check if the body is a supported complex type that doesn't require JSON serialization
551
- * 5. For plain objects, convert to JSON string and set Content-Type header to application/json
552
- *
553
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#setting_a_body}
554
- *
555
- * Supported types:
556
- * - a string
557
- * - ArrayBuffer
558
- * - TypedArray
559
- * - DataView
560
- * - Blob
561
- * - File
562
- * - URLSearchParams
563
- * - FormData
564
- * - ReadableStream
565
- *
566
- * For unsupported object types (like plain objects), they will be automatically
567
- * converted to JSON strings.
568
- *
569
- * @param exchange - The exchange object containing the request to process
570
- *
571
- * @example
572
- * // Plain object body will be converted to JSON
573
- * const fetcher = new Fetcher();
574
- * const exchange = new FetchExchange(
575
- * fetcher,
576
- * {
577
- * body: { name: 'John', age: 30 }
578
- * }
579
- * );
580
- * interceptor.intercept(exchange);
581
- * // exchange.request.body will be '{"name":"John","age":30}'
582
- * // exchange.request.headers will include 'Content-Type: application/json'
583
- */
584
- intercept(e) {
585
- const t = e.request;
586
- if (t.body === void 0 || t.body === null || typeof t.body != "object")
587
- return;
588
- const s = e.ensureRequestHeaders();
589
- if (this.isAutoAppendContentType(t.body)) {
590
- s[h] && delete s[h];
591
- return;
592
- }
593
- this.isSupportedComplexBodyType(t.body) || (e.request.body = JSON.stringify(t.body), s[h] || (s[h] = C.APPLICATION_JSON));
594
- }
595
- }
596
- const he = "FetchInterceptor", le = Number.MAX_SAFE_INTEGER - 1e3;
597
- class de {
598
- constructor() {
599
- this.name = he, this.order = le;
600
- }
601
- /**
602
- * Intercept and process HTTP requests.
603
- *
604
- * Executes the actual HTTP request and applies timeout control. This is the final
605
- * step in the request processing chain, responsible for calling the timeoutFetch
606
- * function to send the network request.
607
- *
608
- * @param exchange - Exchange object containing request information
609
- *
610
- * @throws {FetchTimeoutError} Throws timeout exception when request times out
611
- *
612
- * @example
613
- * // Usually called internally by Fetcher
614
- * const fetcher = new Fetcher();
615
- * const exchange = new FetchExchange(
616
- * fetcher,
617
- * {
618
- * url: 'https://api.example.com/users',
619
- * method: 'GET',
620
- * timeout: 5000
621
- * }
622
- * );
623
- * await fetchInterceptor.intercept(exchange);
624
- * console.log(exchange.response); // HTTP response object
625
- */
626
- async intercept(e) {
627
- e.response = await ee(e.request);
628
- }
629
- }
630
- const P = 0;
631
- function A(r, e) {
632
- return (r.order ?? P) - (e.order ?? P);
633
- }
634
- function u(r, e) {
635
- return e ? r.filter(e).sort(A) : [...r].sort(A);
636
- }
637
- class l {
638
- /**
639
- * Initializes a new InterceptorRegistry instance.
640
- *
641
- * @param interceptors - Initial array of interceptors to manage
642
- *
643
- * @remarks
644
- * The provided interceptors will be sorted by their order property immediately
645
- * upon construction.
646
- */
647
- constructor(e = []) {
648
- this.sortedInterceptors = [], this.sortedInterceptors = u(e);
649
- }
650
- /**
651
- * Gets the name of this interceptor registry.
652
- *
653
- * @returns The constructor name of this class
654
- */
655
- get name() {
656
- return this.constructor.name;
657
- }
658
- /**
659
- * Gets the order of this interceptor registry.
660
- *
661
- * @returns Number.MIN_SAFE_INTEGER, indicating this registry should execute early
662
- */
663
- get order() {
664
- return Number.MIN_SAFE_INTEGER;
665
- }
666
- /**
667
- * Returns an array of all interceptors in the registry.
668
- */
669
- get interceptors() {
670
- return [...this.sortedInterceptors];
671
- }
672
- /**
673
- * Adds an interceptor to this registry.
674
- *
675
- * @param interceptor - The interceptor to add
676
- * @returns True if the interceptor was added, false if an interceptor with the
677
- * same name already exists
678
- *
679
- * @remarks
680
- * Interceptors are uniquely identified by their name property. Attempting to add
681
- * an interceptor with a name that already exists in the registry will fail.
682
- *
683
- * After adding, interceptors are automatically sorted by their order property.
684
- */
685
- use(e) {
686
- return this.sortedInterceptors.some((t) => t.name === e.name) ? !1 : (this.sortedInterceptors = u([
687
- ...this.sortedInterceptors,
688
- e
689
- ]), !0);
690
- }
691
- /**
692
- * Removes an interceptor by name.
693
- *
694
- * @param name - The name of the interceptor to remove
695
- * @returns True if an interceptor was removed, false if no interceptor with the
696
- * given name was found
697
- */
698
- eject(e) {
699
- const t = this.sortedInterceptors;
700
- return this.sortedInterceptors = u(
701
- t,
702
- (s) => s.name !== e
703
- ), t.length !== this.sortedInterceptors.length;
704
- }
705
- /**
706
- * Removes all interceptors from this registry.
707
- */
708
- clear() {
709
- this.sortedInterceptors = [];
710
- }
711
- /**
712
- * Executes all managed interceptors on the given exchange object.
713
- *
714
- * @param exchange - The exchange object to process
715
- * @returns A promise that resolves when all interceptors have been executed
716
- *
717
- * @remarks
718
- * Interceptors are executed in order, with each interceptor receiving the result
719
- * of the previous interceptor. The first interceptor receives the original
720
- * exchange object.
721
- *
722
- * If any interceptor throws an error, the execution chain is broken and the error
723
- * is propagated to the caller.
724
- */
725
- async intercept(e) {
726
- for (const t of this.sortedInterceptors)
727
- await t.intercept(e);
728
- }
729
- }
730
- let pe = class _ extends g {
731
- constructor(e) {
732
- super(
733
- e,
734
- `Request failed with status code ${e.response?.status} for ${e.request.url}`
735
- ), this.name = "HttpStatusValidationError", Object.setPrototypeOf(this, _.prototype);
736
- }
737
- };
738
- const me = (r) => r >= 200 && r < 300, fe = "ValidateStatusInterceptor", ye = Number.MAX_SAFE_INTEGER - 1e3;
739
- class Ee {
740
- /**
741
- * Creates a new ValidateStatusInterceptor instance.
742
- *
743
- * @param validateStatus - Function that determines if a status code is valid
744
- */
745
- constructor(e = me) {
746
- this.validateStatus = e;
747
- }
748
- /**
749
- * Gets the name of this interceptor.
750
- *
751
- * @returns The name of this interceptor
752
- */
753
- get name() {
754
- return fe;
755
- }
756
- /**
757
- * Gets the order of this interceptor.
758
- *
759
- * @returns VALIDATE_STATUS_INTERCEPTOR_ORDER, indicating this interceptor should execute early
760
- */
761
- get order() {
762
- return ye;
763
- }
764
- /**
765
- * Validates the response status code.
766
- *
767
- * @param exchange - The exchange containing the response to validate
768
- * @throws HttpStatusValidationError if the status code is not valid
769
- *
770
- * @remarks
771
- * This method runs at the beginning of the response interceptor chain to ensure
772
- * status validation happens before any other response processing. Invalid responses
773
- * are caught and converted to HttpStatusValidationError early in the pipeline,
774
- * preventing other response handlers from attempting to process them. Valid responses
775
- * proceed through the rest of the response interceptor chain normally.
776
- */
777
- intercept(e) {
778
- if (!e.response)
779
- return;
780
- const t = e.response.status;
781
- if (!this.validateStatus(t))
782
- throw new pe(e);
783
- }
784
- }
785
- class ge {
786
- constructor() {
787
- this.request = new l([
788
- new oe(),
789
- new ce(),
790
- new de()
791
- ]), this.response = new l([
792
- new Ee()
793
- ]), this.error = new l();
794
- }
795
- /**
796
- * Processes a FetchExchange through the interceptor pipeline.
797
- *
798
- * This method is the core of the Fetcher's interceptor system. It executes the three
799
- * phases of interceptors in sequence:
800
- * 1. Request interceptors - Process the request before sending
801
- * 2. Response interceptors - Process the response after receiving
802
- * 3. Error interceptors - Handle any errors that occurred during the process
803
- *
804
- * The interceptor pipeline follows the Chain of Responsibility pattern, where each
805
- * interceptor can modify the exchange object and decide whether to continue or
806
- * terminate the chain.
807
- *
808
- * @param fetchExchange - The exchange object containing request, response, and error information
809
- * @returns Promise that resolves to the processed FetchExchange
810
- * @throws ExchangeError if an unhandled error occurs during processing
811
- *
812
- * @remarks
813
- * The method handles three distinct phases:
814
- *
815
- * 1. Request Phase: Executes request interceptors which can modify headers, URL, body, etc.
816
- * Built-in interceptors handle URL resolution, body serialization, and actual HTTP execution.
817
- *
818
- * 2. Response Phase: Executes response interceptors which can transform or validate responses.
819
- * These interceptors only run if the request phase completed without throwing.
820
- *
821
- * 3. Error Phase: Executes error interceptors when any phase throws an error. Error interceptors
822
- * can handle errors by clearing the error property. If error interceptors clear the error,
823
- * the exchange is returned successfully.
824
- *
825
- * Error Handling:
826
- * - If any interceptor throws an error, the error phase is triggered
827
- * - Error interceptors can "fix" errors by clearing the error property on the exchange
828
- * - If errors remain after error interceptors run, they are wrapped in ExchangeError
829
- *
830
- * Order of Execution:
831
- * 1. Request interceptors (sorted by order property, ascending)
832
- * 2. Response interceptors (sorted by order property, ascending) - only if no error in request phase
833
- * 3. Error interceptors (sorted by order property, ascending) - only if an error occurred
834
- *
835
- * @example
836
- * ```typescript
837
- * // Create a fetcher with custom interceptors
838
- * const fetcher = new Fetcher();
839
- *
840
- * // Add a request interceptor
841
- * fetcher.interceptors.request.use({
842
- * name: 'AuthInterceptor',
843
- * order: 100,
844
- * async intercept(exchange: FetchExchange) {
845
- * exchange.request.headers = {
846
- * ...exchange.request.headers,
847
- * 'Authorization': 'Bearer ' + getToken()
848
- * };
849
- * }
850
- * });
851
- *
852
- * // Add a response interceptor
853
- * fetcher.interceptors.response.use({
854
- * name: 'ResponseLogger',
855
- * order: 100,
856
- * async intercept(exchange: FetchExchange) {
857
- * console.log(`Response status: ${exchange.response?.status}`);
858
- * }
859
- * });
860
- *
861
- * // Add an error interceptor
862
- * fetcher.interceptors.error.use({
863
- * name: 'ErrorLogger',
864
- * order: 100,
865
- * async intercept(exchange: FetchExchange) {
866
- * console.error(`Request to ${exchange.request.url} failed:`, exchange.error);
867
- * // Clear the error to indicate it's been handled
868
- * exchange.error = undefined;
869
- * }
870
- * });
871
- *
872
- * // Create and process an exchange
873
- * const request: FetchRequest = {
874
- * url: '/api/users',
875
- * method: HttpMethod.GET
876
- * };
877
- * const exchange = new FetchExchange(fetcher, request);
878
- * const result = await fetcher.exchange(exchange);
879
- * ```
880
- */
881
- async exchange(e) {
882
- try {
883
- return await this.request.intercept(e), await this.response.intercept(e), e;
884
- } catch (t) {
885
- if (e.error = t, await this.error.intercept(e), !e.hasError())
886
- return e;
887
- throw new g(e);
888
- }
889
- }
890
- }
891
- function d(r, e) {
892
- return e && e.resultExtractor && e.attributes ? e : {
893
- resultExtractor: e?.resultExtractor ?? r?.resultExtractor ?? z.resultExtractor,
894
- attributes: e?.attributes ?? r?.attributes
895
- };
896
- }
897
- const y = {
898
- [h]: C.APPLICATION_JSON
899
- }, F = {
900
- baseURL: "",
901
- headers: y
902
- }, z = {
903
- resultExtractor: R.Exchange
904
- }, q = {
905
- resultExtractor: R.Response
906
- };
907
- class we {
908
- /**
909
- * Initializes a new Fetcher instance with optional configuration.
910
- *
911
- * Creates a Fetcher with default settings that can be overridden through the options parameter.
912
- * If no interceptors are provided, a default set of interceptors will be used.
913
- *
914
- * @param options - Configuration options for the Fetcher instance
915
- * @param options.baseURL - The base URL to prepend to all requests. Defaults to empty string.
916
- * @param options.headers - Default headers to include in all requests. Defaults to JSON content type.
917
- * @param options.timeout - Default timeout for requests in milliseconds. No timeout by default.
918
- * @param options.urlTemplateStyle - Style for URL template parameter interpolation.
919
- * @param options.interceptors - Interceptor manager for processing requests and responses.
920
- */
921
- constructor(e = F) {
922
- this.headers = y, this.urlBuilder = new W(e.baseURL, e.urlTemplateStyle), this.headers = e.headers ?? y, this.timeout = e.timeout, this.interceptors = e.interceptors ?? new ge();
923
- }
924
- /**
925
- * Processes an HTTP request through the Fetcher's internal workflow.
926
- *
927
- * This method creates a FetchExchange object and passes it through the interceptor chain.
928
- * It handles header merging, timeout resolution, and result extractor configuration.
929
- *
930
- * @param request - The HTTP request configuration to process
931
- * @param options - Optional request options including result extractor and attributes
932
- * @returns Promise that resolves to the processed FetchExchange object
933
- */
934
- async exchange(e, t) {
935
- const s = {
936
- ...this.headers,
937
- ...e.headers
938
- }, n = {
939
- ...e,
940
- headers: s,
941
- timeout: Z(e.timeout, this.timeout)
942
- }, { resultExtractor: a, attributes: i } = d(
943
- z,
944
- t
945
- ), c = new ne({
946
- fetcher: this,
947
- request: n,
948
- resultExtractor: a,
949
- attributes: i
950
- });
951
- return await this.interceptors.exchange(c);
952
- }
953
- /**
954
- * Processes an HTTP request through the Fetcher's internal workflow.
955
- *
956
- * This method prepares the request by merging headers and timeout settings,
957
- * creates a FetchExchange object, and passes it through the exchange method
958
- * for interceptor processing.
959
- *
960
- * @template R - The type of the result to be returned
961
- * @param request - Complete request configuration object
962
- * @param options - Request options including result extractor and attributes
963
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
964
- * Defaults to ExchangeResultExtractor which returns the entire exchange object.
965
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
966
- * throughout the request lifecycle. These attributes allow passing
967
- * custom data between different interceptors.
968
- * @returns Promise that resolves to the extracted result based on resultExtractor
969
- * @throws Error if an unhandled error occurs during request processing
970
- */
971
- async request(e, t) {
972
- return await (await this.exchange(e, t)).extractResult();
973
- }
974
- /**
975
- * Executes an HTTP request with the specified URL and options.
976
- *
977
- * This is the primary method for making HTTP requests. It processes the request
978
- * through the interceptor chain and returns the resulting Response.
979
- *
980
- * @template R - The type of the result to be returned
981
- * @param url - The URL path for the request (relative to baseURL if set)
982
- * @param request - Request configuration including headers, body, parameters, etc.
983
- * @param options - Request options including result extractor and attributes
984
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
985
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
986
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
987
- * throughout the request lifecycle. These attributes allow passing
988
- * custom data between different interceptors.
989
- * @returns Promise that resolves to the HTTP response
990
- * @throws FetchError if the request fails and no response is generated
991
- */
992
- async fetch(e, t = {}, s) {
993
- const n = {
994
- ...t,
995
- url: e
996
- };
997
- return await this.request(
998
- n,
999
- d(q, s)
1000
- );
1001
- }
1002
- /**
1003
- * Internal helper method for making HTTP requests with a specific method.
1004
- *
1005
- * This private method is used by the public HTTP method methods (get, post, etc.)
1006
- * to execute requests with the appropriate HTTP verb.
1007
- *
1008
- * @template R - The type of the result to be returned
1009
- * @param method - The HTTP method to use for the request
1010
- * @param url - The URL path for the request
1011
- * @param request - Additional request options
1012
- * @param options - Request options including result extractor and attributes
1013
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1014
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1015
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1016
- * throughout the request lifecycle. These attributes allow passing
1017
- * custom data between different interceptors.
1018
- * @returns Promise that resolves to the HTTP response
1019
- */
1020
- async methodFetch(e, t, s = {}, n) {
1021
- const a = {
1022
- ...s,
1023
- url: t,
1024
- method: e
1025
- };
1026
- return await this.request(
1027
- a,
1028
- d(q, n)
1029
- );
1030
- }
1031
- /**
1032
- * Makes a GET HTTP request.
1033
- *
1034
- * Convenience method for making GET requests. The request body is omitted
1035
- * as GET requests should not contain a body according to HTTP specification.
1036
- *
1037
- * @template R - The type of the result to be returned
1038
- * @param url - The URL path for the request
1039
- * @param request - Request options excluding method and body
1040
- * @param options - Request options including result extractor and attributes
1041
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1042
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1043
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1044
- * throughout the request lifecycle. These attributes allow passing
1045
- * custom data between different interceptors.
1046
- * @returns Promise that resolves to the HTTP response
1047
- */
1048
- async get(e, t = {}, s) {
1049
- return await this.methodFetch(o.GET, e, t, s);
1050
- }
1051
- /**
1052
- * Makes a PUT HTTP request.
1053
- *
1054
- * Convenience method for making PUT requests, commonly used for updating resources.
1055
- *
1056
- * @template R - The type of the result to be returned
1057
- * @param url - The URL path for the request
1058
- * @param request - Request options including body and other parameters
1059
- * @param options - Request options including result extractor and attributes
1060
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1061
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1062
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1063
- * throughout the request lifecycle. These attributes allow passing
1064
- * custom data between different interceptors.
1065
- * @returns Promise that resolves to the HTTP response
1066
- */
1067
- async put(e, t = {}, s) {
1068
- return await this.methodFetch(o.PUT, e, t, s);
1069
- }
1070
- /**
1071
- * Makes a POST HTTP request.
1072
- *
1073
- * Convenience method for making POST requests, commonly used for creating resources.
1074
- *
1075
- * @template R - The type of the result to be returned
1076
- * @param url - The URL path for the request
1077
- * @param request - Request options including body and other parameters
1078
- * @param options - Request options including result extractor and attributes
1079
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1080
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1081
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1082
- * throughout the request lifecycle. These attributes allow passing
1083
- * custom data between different interceptors.
1084
- * @returns Promise that resolves to the HTTP response
1085
- */
1086
- async post(e, t = {}, s) {
1087
- return await this.methodFetch(o.POST, e, t, s);
1088
- }
1089
- /**
1090
- * Makes a PATCH HTTP request.
1091
- *
1092
- * Convenience method for making PATCH requests, commonly used for partial updates.
1093
- *
1094
- * @template R - The type of the result to be returned
1095
- * @param url - The URL path for the request
1096
- * @param request - Request options including body and other parameters
1097
- * @param options - Request options including result extractor and attributes
1098
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1099
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1100
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1101
- * throughout the request lifecycle. These attributes allow passing
1102
- * custom data between different interceptors.
1103
- * @returns Promise that resolves to the HTTP response
1104
- */
1105
- async patch(e, t = {}, s) {
1106
- return await this.methodFetch(o.PATCH, e, t, s);
1107
- }
1108
- /**
1109
- * Makes a DELETE HTTP request.
1110
- *
1111
- * Convenience method for making DELETE requests, commonly used for deleting resources.
1112
- *
1113
- * @template R - The type of the result to be returned
1114
- * @param url - The URL path for the request
1115
- * @param request - Request options excluding method and body
1116
- * @param options - Request options including result extractor and attributes
1117
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1118
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1119
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1120
- * throughout the request lifecycle. These attributes allow passing
1121
- * custom data between different interceptors.
1122
- * @returns Promise that resolves to the HTTP response
1123
- */
1124
- async delete(e, t = {}, s) {
1125
- return await this.methodFetch(o.DELETE, e, t, s);
1126
- }
1127
- /**
1128
- * Makes a HEAD HTTP request.
1129
- *
1130
- * Convenience method for making HEAD requests, which retrieve headers only.
1131
- * The request body is omitted as HEAD requests should not contain a body.
1132
- *
1133
- * @template R - The type of the result to be returned
1134
- * @param url - The URL path for the request
1135
- * @param request - Request options excluding method and body
1136
- * @param options - Request options including result extractor and attributes
1137
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1138
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1139
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1140
- * throughout the request lifecycle. These attributes allow passing
1141
- * custom data between different interceptors.
1142
- * @returns Promise that resolves to the HTTP response
1143
- */
1144
- async head(e, t = {}, s) {
1145
- return await this.methodFetch(o.HEAD, e, t, s);
1146
- }
1147
- /**
1148
- * Makes an OPTIONS HTTP request.
1149
- *
1150
- * Convenience method for making OPTIONS requests, commonly used for CORS preflight.
1151
- * The request body is omitted as OPTIONS requests typically don't contain a body.
1152
- *
1153
- * @template R - The type of the result to be returned
1154
- * @param url - The URL path for the request
1155
- * @param request - Request options excluding method and body
1156
- * @param options - Request options including result extractor and attributes
1157
- * @param options.resultExtractor - Function to extract the desired result from the exchange.
1158
- * Defaults to ResponseResultExtractor which returns the entire exchange object.
1159
- * @param options.attributes - Optional shared attributes that can be accessed by interceptors
1160
- * throughout the request lifecycle. These attributes allow passing
1161
- * custom data between different interceptors.
1162
- * @returns Promise that resolves to the HTTP response
1163
- */
1164
- async options(e, t = {}, s) {
1165
- return await this.methodFetch(o.OPTIONS, e, t, s);
1166
- }
1167
- /**
1168
- * Sends an HTTP TRACE request to the specified URL and returns the response.
1169
- *
1170
- * The TRACE method is used to echo the received request for debugging purposes.
1171
- * This method automatically sets the HTTP method to TRACE and omits the request body
1172
- * since TRACE requests must not have a body according to the HTTP specification.
1173
- *
1174
- * @param url - The target URL for the TRACE request. Must be a valid absolute or relative URL.
1175
- * @param request - Request configuration options excluding 'method' and 'body' properties.
1176
- * Defaults to an empty object. Common properties include headers, cache settings, etc.
1177
- * @param options - Optional additional request parameters for extended functionality.
1178
- * May include custom handling logic or metadata for the request pipeline.
1179
- * @returns A Promise resolving to the response object of type R (defaults to Response).
1180
- * The response contains status, headers, and body data from the TRACE request.
1181
- */
1182
- async trace(e, t = {}, s) {
1183
- return await this.methodFetch(o.TRACE, e, t, s);
1184
- }
1185
- }
1186
- const E = "default";
1187
- class Re {
1188
- constructor() {
1189
- this.registrar = /* @__PURE__ */ new Map();
1190
- }
1191
- /**
1192
- * Register a Fetcher instance with a given name
1193
- *
1194
- * @param name - The name to register the fetcher under
1195
- * @param fetcher - The Fetcher instance to register
1196
- * @example
1197
- * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
1198
- * fetcherRegistrar.register('api', fetcher);
1199
- */
1200
- register(e, t) {
1201
- this.registrar.set(e, t);
1202
- }
1203
- /**
1204
- * Unregister a Fetcher instance by name
1205
- *
1206
- * @param name - The name of the fetcher to unregister
1207
- * @returns boolean - True if the fetcher was successfully unregistered, false otherwise
1208
- * @example
1209
- * const success = fetcherRegistrar.unregister('api');
1210
- * if (success) {
1211
- * console.log('Fetcher unregistered successfully');
1212
- * }
1213
- */
1214
- unregister(e) {
1215
- return this.registrar.delete(e);
1216
- }
1217
- /**
1218
- * Get a Fetcher instance by name
1219
- *
1220
- * @param name - The name of the fetcher to retrieve
1221
- * @returns Fetcher | undefined - The Fetcher instance if found, undefined otherwise
1222
- * @example
1223
- * const fetcher = fetcherRegistrar.get('api');
1224
- * if (fetcher) {
1225
- * // Use the fetcher
1226
- * }
1227
- */
1228
- get(e) {
1229
- return this.registrar.get(e);
1230
- }
1231
- /**
1232
- * Get a Fetcher instance by name, throwing an error if not found
1233
- *
1234
- * @param name - The name of the fetcher to retrieve
1235
- * @returns Fetcher - The Fetcher instance
1236
- * @throws Error - If no fetcher is registered with the given name
1237
- * @example
1238
- * try {
1239
- * const fetcher = fetcherRegistrar.requiredGet('api');
1240
- * // Use the fetcher
1241
- * } catch (error) {
1242
- * console.error('Fetcher not found:', error.message);
1243
- * }
1244
- */
1245
- requiredGet(e) {
1246
- const t = this.get(e);
1247
- if (!t)
1248
- throw new Error(`Fetcher ${e} not found`);
1249
- return t;
1250
- }
1251
- /**
1252
- * Get the default Fetcher instance
1253
- *
1254
- * @returns Fetcher - The default Fetcher instance
1255
- * @throws Error - If no default fetcher is registered
1256
- * @example
1257
- * const defaultFetcher = fetcherRegistrar.default;
1258
- */
1259
- get default() {
1260
- return this.requiredGet(E);
1261
- }
1262
- /**
1263
- * Set the default Fetcher instance
1264
- *
1265
- * @param fetcher - The Fetcher instance to set as default
1266
- * @example
1267
- * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
1268
- * fetcherRegistrar.default = fetcher;
1269
- */
1270
- set default(e) {
1271
- this.register(E, e);
1272
- }
1273
- /**
1274
- * Get a copy of all registered fetchers
1275
- *
1276
- * @returns Map<string, Fetcher> - A copy of the internal registrar map
1277
- * @example
1278
- * const allFetchers = fetcherRegistrar.fetchers;
1279
- * for (const [name, fetcher] of allFetchers) {
1280
- * console.log(`Fetcher ${name}:`, fetcher);
1281
- * }
1282
- */
1283
- get fetchers() {
1284
- return new Map(this.registrar);
1285
- }
1286
- }
1287
- const Te = new Re();
1288
- class Pe extends we {
1289
- /**
1290
- * Create a NamedFetcher instance and automatically register it with the global fetcherRegistrar
1291
- *
1292
- * @param name - The name to register this fetcher under
1293
- * @param options - Fetcher configuration options (same as Fetcher constructor)
1294
- *
1295
- * @example
1296
- * // Create with default options
1297
- * const fetcher1 = new NamedFetcher('default');
1298
- *
1299
- * // Create with custom options
1300
- * const fetcher2 = new NamedFetcher('api', {
1301
- * baseURL: 'https://api.example.com',
1302
- * timeout: 5000,
1303
- * headers: { 'Authorization': 'Bearer token' }
1304
- * });
1305
- */
1306
- constructor(e, t = F) {
1307
- super(t), this.name = e, Te.register(e, this);
1308
- }
1309
- }
1310
- new Pe(E);
1311
- class Ae {
1312
- constructor() {
1313
- this.eventHandlers = [];
1314
- }
1315
- /**
1316
- * Gets a copy of all registered event handlers, sorted by order
1317
- */
1318
- get handlers() {
1319
- return [...this.eventHandlers];
1320
- }
1321
- destroy() {
1322
- this.eventHandlers = [];
1323
- }
1324
- async handleEvent(e, t) {
1325
- try {
1326
- e.handle(t);
1327
- } catch (s) {
1328
- console.warn(`Event handler error for ${e.name}:`, s);
1329
- }
1330
- }
1331
- }
1332
- class qe extends Ae {
1333
- /**
1334
- * Creates an in-memory typed event bus
1335
- *
1336
- * @param type - The event type identifier for this bus
1337
- */
1338
- constructor(e) {
1339
- super(), this.type = e;
1340
- }
1341
- /**
1342
- * Emits an event to all registered handlers serially
1343
- *
1344
- * Handlers are executed in order of their priority. Once-only handlers are removed after execution.
1345
- * Errors in individual handlers are logged but do not stop other handlers.
1346
- *
1347
- * @param event - The event to emit
1348
- */
1349
- async emit(e) {
1350
- const t = [];
1351
- for (const s of this.eventHandlers)
1352
- await this.handleEvent(s, e), s.once && t.push(s);
1353
- t.length > 0 && (this.eventHandlers = u(
1354
- this.eventHandlers.filter((s) => !t.includes(s))
1355
- ));
1356
- }
1357
- /**
1358
- * Removes an event handler by name
1359
- *
1360
- * @param name - The name of the handler to remove
1361
- * @returns true if a handler was removed, false otherwise
1362
- */
1363
- off(e) {
1364
- const t = this.eventHandlers;
1365
- return t.some((s) => s.name === e) ? (this.eventHandlers = u(t, (s) => s.name !== e), !0) : !1;
1366
- }
1367
- /**
1368
- * Adds an event handler if not already present
1369
- *
1370
- * Handlers are sorted by their order property after addition.
1371
- *
1372
- * @param handler - The event handler to add
1373
- * @returns true if the handler was added, false if a handler with the same name already exists
1374
- */
1375
- on(e) {
1376
- const t = this.eventHandlers;
1377
- return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = u([...t, e]), !0);
1378
- }
1379
- }
1380
- class xe {
1381
- constructor() {
1382
- this.namingCounter = 0;
1383
- }
1384
- /**
1385
- * Generates a unique name by appending an incrementing counter to the prefix
1386
- * @param prefix - The prefix for the generated name
1387
- * @returns The generated unique name
1388
- */
1389
- generate(e) {
1390
- return this.namingCounter++, `${e}_${this.namingCounter}`;
1391
- }
1392
- }
1393
- const be = new xe();
1394
- class Ie {
95
+ class m {
1395
96
  /**
1396
97
  * Creates a new KeyStorage instance
1397
98
  * @param options Configuration options for the storage
1398
99
  */
1399
100
  constructor(e) {
1400
101
  this.cacheValue = null, this.keyStorageHandler = {
1401
- name: be.generate("KeyStorage"),
102
+ name: i.generate("KeyStorage"),
1402
103
  handle: (t) => {
1403
104
  this.cacheValue = t.newValue ?? null;
1404
105
  }
1405
- }, this.key = e.key, this.serializer = e.serializer ?? L(), this.storage = e.storage ?? V(), this.eventBus = e.eventBus ?? new qe(
106
+ }, this.key = e.key, this.serializer = e.serializer ?? y(), this.storage = e.storage ?? o(), this.eventBus = e.eventBus ?? new n(
1406
107
  `KeyStorage:${this.key}`
1407
108
  ), this.eventBus.on(this.keyStorageHandler);
1408
109
  }
@@ -1434,14 +135,14 @@ class Ie {
1434
135
  }
1435
136
  }
1436
137
  export {
1437
- G as IdentitySerializer,
1438
- $ as InMemoryStorage,
1439
- k as JsonSerializer,
1440
- Ie as KeyStorage,
1441
- V as getStorage,
1442
- U as identitySerializer,
1443
- B as isBrowser,
1444
- ve as jsonSerializer,
1445
- L as typedIdentitySerializer
138
+ u as IdentitySerializer,
139
+ a as InMemoryStorage,
140
+ h as JsonSerializer,
141
+ m as KeyStorage,
142
+ o as getStorage,
143
+ c as identitySerializer,
144
+ l as isBrowser,
145
+ d as jsonSerializer,
146
+ y as typedIdentitySerializer
1446
147
  };
1447
148
  //# sourceMappingURL=index.es.js.map