@npora/request 0.1.2 → 0.2.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.
package/dist/index.cjs CHANGED
@@ -24,6 +24,7 @@ __export(index_exports, {
24
24
  FetchAdapter: () => FetchAdapter,
25
25
  InterceptorManager: () => InterceptorManager,
26
26
  MockAdapter: () => MockAdapter,
27
+ PluginError: () => PluginError,
27
28
  RequestError: () => RequestError,
28
29
  authPlugin: () => authPlugin,
29
30
  cachePlugin: () => cachePlugin,
@@ -42,7 +43,10 @@ var RequestError = class extends Error {
42
43
  super(message);
43
44
  this.name = "RequestError";
44
45
  this.code = options.code;
45
- this.status = options.status;
46
+ this.status = options.status ?? options.response?.status;
47
+ this.data = options.data ?? options.response?.data;
48
+ this.response = options.response;
49
+ this.config = options.config ?? options.response?.config;
46
50
  this.cause = options.cause;
47
51
  Object.setPrototypeOf(this, new.target.prototype);
48
52
  }
@@ -57,7 +61,20 @@ function createTimeoutSignal(signal, timeout) {
57
61
  };
58
62
  }
59
63
  const controller = new AbortController();
60
- const timer = setTimeout(() => {
64
+ let timer;
65
+ let onAbort;
66
+ const clear = () => {
67
+ if (timer !== void 0) {
68
+ clearTimeout(timer);
69
+ timer = void 0;
70
+ }
71
+ if (signal && onAbort) {
72
+ signal.removeEventListener("abort", onAbort);
73
+ onAbort = void 0;
74
+ }
75
+ };
76
+ timer = setTimeout(() => {
77
+ clear();
61
78
  controller.abort(
62
79
  new RequestError(`Request timeout after ${timeout}ms`, {
63
80
  code: "TIMEOUT_ERROR"
@@ -66,17 +83,20 @@ function createTimeoutSignal(signal, timeout) {
66
83
  }, timeout);
67
84
  if (signal) {
68
85
  if (signal.aborted) {
86
+ clear();
69
87
  controller.abort(signal.reason);
70
88
  } else {
89
+ onAbort = () => {
90
+ clear();
91
+ controller.abort(
92
+ signal.reason ?? new RequestError("Request aborted", {
93
+ code: "ABORT_ERROR"
94
+ })
95
+ );
96
+ };
71
97
  signal.addEventListener(
72
98
  "abort",
73
- () => {
74
- controller.abort(
75
- signal.reason ?? new RequestError("Request aborted", {
76
- code: "ABORT_ERROR"
77
- })
78
- );
79
- },
99
+ onAbort,
80
100
  {
81
101
  once: true
82
102
  }
@@ -85,9 +105,7 @@ function createTimeoutSignal(signal, timeout) {
85
105
  }
86
106
  return {
87
107
  signal: controller.signal,
88
- clear: () => {
89
- clearTimeout(timer);
90
- }
108
+ clear
91
109
  };
92
110
  }
93
111
  function noop() {
@@ -96,11 +114,15 @@ function noop() {
96
114
  // src/utils/buildRequest.ts
97
115
  function buildRequest(config) {
98
116
  const headers = new Headers(config.headers);
117
+ return buildRequestWithHeaders(config, headers);
118
+ }
119
+ function buildRequestWithHeaders(config, headers) {
99
120
  const body = buildBody(config, headers);
100
121
  const timeoutSignal = createTimeoutSignal(config.signal, config.timeout);
101
122
  return {
102
123
  url: buildURL(config),
103
124
  init: {
125
+ ...config.fetchOptions,
104
126
  method: config.method ?? "GET",
105
127
  headers,
106
128
  body,
@@ -110,8 +132,7 @@ function buildRequest(config) {
110
132
  };
111
133
  }
112
134
  function buildURL(config) {
113
- const baseURL = config.baseURL ?? "";
114
- const url = `${baseURL}${config.url}`;
135
+ const url = joinURL(config.baseURL, config.url);
115
136
  if (!config.query) {
116
137
  return url;
117
138
  }
@@ -119,12 +140,47 @@ function buildURL(config) {
119
140
  if (!query) {
120
141
  return url;
121
142
  }
122
- return url.includes("?") ? `${url}&${query}` : `${url}?${query}`;
143
+ const hashIndex = url.indexOf("#");
144
+ const target = hashIndex === -1 ? url : url.slice(0, hashIndex);
145
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
146
+ const separator = target.includes("?") ? "&" : "?";
147
+ return `${target}${separator}${query}${hash}`;
148
+ }
149
+ function joinURL(baseURL, url) {
150
+ if (!baseURL || isAbsoluteURL(url)) {
151
+ return url;
152
+ }
153
+ if (!url) {
154
+ return baseURL;
155
+ }
156
+ let baseEnd = baseURL.length;
157
+ let urlStart = 0;
158
+ while (baseEnd > 0 && baseURL.charCodeAt(baseEnd - 1) === 47) {
159
+ baseEnd -= 1;
160
+ }
161
+ while (urlStart < url.length && url.charCodeAt(urlStart) === 47) {
162
+ urlStart += 1;
163
+ }
164
+ return `${baseURL.slice(0, baseEnd)}/${url.slice(urlStart)}`;
165
+ }
166
+ function isAbsoluteURL(url) {
167
+ if (url.startsWith("//")) {
168
+ return true;
169
+ }
170
+ const colon = url.indexOf(":");
171
+ if (colon <= 0) {
172
+ return false;
173
+ }
174
+ return /^[a-z][a-z\d+\-.]*$/i.test(
175
+ url.slice(0, colon)
176
+ );
123
177
  }
124
178
  function stringifyQuery(query) {
125
179
  const params = new URLSearchParams();
126
- for (const [key, value] of Object.entries(query)) {
127
- appendQuery(params, key, value);
180
+ for (const key in query) {
181
+ if (Object.prototype.hasOwnProperty.call(query, key)) {
182
+ appendQuery(params, key, query[key]);
183
+ }
128
184
  }
129
185
  return params.toString();
130
186
  }
@@ -134,7 +190,9 @@ function appendQuery(params, key, value) {
134
190
  }
135
191
  if (Array.isArray(value)) {
136
192
  for (const item of value) {
137
- appendQuery(params, key, item);
193
+ if (item !== null && item !== void 0) {
194
+ params.append(key, String(item));
195
+ }
138
196
  }
139
197
  return;
140
198
  }
@@ -169,8 +227,10 @@ function buildURLSearchParams(form) {
169
227
  return form;
170
228
  }
171
229
  const params = new URLSearchParams();
172
- for (const [key, value] of Object.entries(form)) {
173
- appendQuery(params, key, value);
230
+ for (const key in form) {
231
+ if (Object.prototype.hasOwnProperty.call(form, key)) {
232
+ appendQuery(params, key, form[key]);
233
+ }
174
234
  }
175
235
  return params;
176
236
  }
@@ -179,8 +239,10 @@ function buildFormData(input) {
179
239
  return input;
180
240
  }
181
241
  const formData = new FormData();
182
- for (const [key, value] of Object.entries(input)) {
183
- appendFormDataValue(formData, key, value);
242
+ for (const key in input) {
243
+ if (Object.prototype.hasOwnProperty.call(input, key)) {
244
+ appendFormDataValue(formData, key, input[key]);
245
+ }
184
246
  }
185
247
  return formData;
186
248
  }
@@ -211,7 +273,7 @@ function isPlainObject(value) {
211
273
 
212
274
  // src/utils/parseResponse.ts
213
275
  async function parseResponse(response, config) {
214
- if (response.status === 204 || response.status === 205) {
276
+ if (config.method === "HEAD" || response.status === 204 || response.status === 205) {
215
277
  return void 0;
216
278
  }
217
279
  const responseType = config.responseType ?? detectResponseType(response);
@@ -234,6 +296,7 @@ async function parseResponse(response, config) {
234
296
  throw new RequestError("Failed to parse response", {
235
297
  code: "PARSER_ERROR",
236
298
  status: response.status,
299
+ config,
237
300
  cause: error
238
301
  });
239
302
  }
@@ -246,21 +309,104 @@ function detectResponseType(response) {
246
309
  return "text";
247
310
  }
248
311
 
312
+ // src/utils/validateRequestConfig.ts
313
+ var BODY_FIELDS = [
314
+ "body",
315
+ "json",
316
+ "form",
317
+ "formData"
318
+ ];
319
+ function validateRequestConfig(config) {
320
+ validateURL(config);
321
+ validateTimeout(config);
322
+ const headers = validateHeaders(config);
323
+ validateBody(config);
324
+ return headers;
325
+ }
326
+ function validateURL(config) {
327
+ if (typeof config.url !== "string") {
328
+ throw configError("Request url must be a string", config);
329
+ }
330
+ }
331
+ function validateTimeout(config) {
332
+ if (config.timeout === void 0) {
333
+ return;
334
+ }
335
+ if (!Number.isFinite(config.timeout) || config.timeout < 0) {
336
+ throw configError(
337
+ "Request timeout must be a finite, non-negative number",
338
+ config
339
+ );
340
+ }
341
+ }
342
+ function validateHeaders(config) {
343
+ try {
344
+ return new Headers(config.headers);
345
+ } catch (error) {
346
+ throw configError("Request headers are invalid", config, error);
347
+ }
348
+ }
349
+ function validateBody(config) {
350
+ let activeField;
351
+ for (const key of BODY_FIELDS) {
352
+ const value = config[key];
353
+ if (value === void 0 || value === null) {
354
+ continue;
355
+ }
356
+ if (activeField) {
357
+ const activeFields = BODY_FIELDS.filter((field) => {
358
+ const fieldValue = config[field];
359
+ return fieldValue !== void 0 && fieldValue !== null;
360
+ });
361
+ throw configError(
362
+ `Request body options are mutually exclusive: ${activeFields.join(", ")}`,
363
+ config
364
+ );
365
+ }
366
+ activeField = key;
367
+ }
368
+ const method = config.method ?? "GET";
369
+ if (activeField && (method === "GET" || method === "HEAD")) {
370
+ throw configError(
371
+ `${method} requests cannot include a body`,
372
+ config
373
+ );
374
+ }
375
+ }
376
+ function configError(message, config, cause) {
377
+ return new RequestError(message, {
378
+ code: "CONFIG_ERROR",
379
+ config,
380
+ cause
381
+ });
382
+ }
383
+
249
384
  // src/adapters/FetchAdapter.ts
250
385
  var FetchAdapter = class {
251
386
  async request(config) {
252
- const request = buildRequest(config);
387
+ return this.execute(
388
+ config,
389
+ validateRequestConfig(config),
390
+ true
391
+ );
392
+ }
393
+ requestValidated(config, validatedHeaders, preserveRaw = true) {
394
+ return this.execute(
395
+ config,
396
+ validatedHeaders,
397
+ preserveRaw
398
+ );
399
+ }
400
+ async execute(config, headers, preserveRaw) {
401
+ let request;
253
402
  try {
403
+ request = buildRequestWithHeaders(config, headers);
254
404
  const response = await fetch(request.url, request.init);
255
405
  const validateStatus = config.validateStatus ?? defaultValidateStatus;
256
- if (!validateStatus(response.status)) {
257
- throw new RequestError(response.statusText || "Request failed", {
258
- code: "HTTP_ERROR",
259
- status: response.status
260
- });
261
- }
262
- const data = await parseResponse(response, config);
263
- return {
406
+ const validStatus = validateStatus(response.status);
407
+ const parseTarget = config.responseType === "stream" || !preserveRaw && validStatus ? response : response.clone();
408
+ const data = await parseResponse(parseTarget, config);
409
+ const nporaResponse = {
264
410
  data,
265
411
  status: response.status,
266
412
  statusText: response.statusText,
@@ -268,27 +414,50 @@ var FetchAdapter = class {
268
414
  config,
269
415
  raw: response
270
416
  };
417
+ if (!validStatus) {
418
+ throw new RequestError(response.statusText || "Request failed", {
419
+ code: "HTTP_ERROR",
420
+ response: nporaResponse
421
+ });
422
+ }
423
+ return nporaResponse;
271
424
  } catch (error) {
272
425
  if (error instanceof RequestError) {
273
426
  throw error;
274
427
  }
428
+ if (!request) {
429
+ throw new RequestError("Failed to build request", {
430
+ code: "CONFIG_ERROR",
431
+ config,
432
+ cause: error
433
+ });
434
+ }
275
435
  const signal = request.init.signal;
276
436
  const reason = signal?.reason;
277
437
  if (signal?.aborted) {
278
438
  if (reason instanceof RequestError) {
279
- throw reason;
439
+ throw new RequestError(reason.message, {
440
+ code: reason.code,
441
+ status: reason.status,
442
+ data: reason.data,
443
+ response: reason.response,
444
+ config: reason.config ?? config,
445
+ cause: reason
446
+ });
280
447
  }
281
448
  throw new RequestError("Request aborted", {
282
449
  code: "ABORT_ERROR",
450
+ config,
283
451
  cause: error
284
452
  });
285
453
  }
286
454
  throw new RequestError("Network request failed", {
287
455
  code: "NETWORK_ERROR",
456
+ config,
288
457
  cause: error
289
458
  });
290
459
  } finally {
291
- request.clear();
460
+ request?.clear();
292
461
  }
293
462
  }
294
463
  };
@@ -336,13 +505,94 @@ var ConfigMerger = class {
336
505
  * Merge request configuration.
337
506
  */
338
507
  static merge(defaults, config) {
339
- return {
508
+ return this.mergeConfig(defaults, config);
509
+ }
510
+ /**
511
+ * Merge two sets of client defaults.
512
+ */
513
+ static mergeDefaults(defaults, overrides) {
514
+ return this.mergeConfig(defaults, overrides);
515
+ }
516
+ static mergeConfig(defaults, config) {
517
+ const result = {
340
518
  ...defaults,
341
- ...config,
342
- headers: this.mergeHeaders(
519
+ ...config
520
+ };
521
+ if (defaults.fetchOptions || config.fetchOptions) {
522
+ result.fetchOptions = this.mergeFetchOptions(
523
+ defaults.fetchOptions,
524
+ config.fetchOptions
525
+ );
526
+ }
527
+ if (defaults.headers || config.headers) {
528
+ result.headers = this.mergeHeaders(
343
529
  defaults.headers,
344
530
  config.headers
345
- )
531
+ );
532
+ }
533
+ if (defaults.query || config.query) {
534
+ result.query = this.mergeObject(
535
+ defaults.query,
536
+ config.query
537
+ );
538
+ }
539
+ if (defaults.extensions || config.extensions) {
540
+ result.extensions = this.mergeExtensions(
541
+ defaults.extensions,
542
+ config.extensions
543
+ );
544
+ }
545
+ if (defaults.retry !== void 0 || config.retry !== void 0) {
546
+ result.retry = this.mergeRetry(
547
+ defaults.retry,
548
+ config.retry
549
+ );
550
+ }
551
+ if (defaults.cache || config.cache) {
552
+ result.cache = this.mergeObject(
553
+ defaults.cache,
554
+ config.cache
555
+ );
556
+ }
557
+ if (defaults.auth || config.auth) {
558
+ result.auth = this.mergeObject(
559
+ defaults.auth,
560
+ config.auth
561
+ );
562
+ }
563
+ if (defaults.logger || config.logger) {
564
+ result.logger = this.mergeObject(
565
+ defaults.logger,
566
+ config.logger
567
+ );
568
+ }
569
+ if (defaults.upload || config.upload) {
570
+ result.upload = this.mergeObject(
571
+ defaults.upload,
572
+ config.upload
573
+ );
574
+ }
575
+ if (defaults.download || config.download) {
576
+ result.download = this.mergeObject(
577
+ defaults.download,
578
+ config.download
579
+ );
580
+ }
581
+ if (this.hasBodyConfig(defaults) || this.hasBodyConfig(config)) {
582
+ Object.assign(
583
+ result,
584
+ this.mergeBodyConfig(defaults, config)
585
+ );
586
+ }
587
+ return result;
588
+ }
589
+ static mergeFetchOptions(defaults, options) {
590
+ if (!defaults && !options) {
591
+ return void 0;
592
+ }
593
+ return {
594
+ ...defaults,
595
+ ...options
346
596
  };
347
597
  }
348
598
  /**
@@ -352,31 +602,135 @@ var ConfigMerger = class {
352
602
  if (!defaults && !headers) {
353
603
  return void 0;
354
604
  }
355
- return {
356
- ...this.normalizeHeaders(defaults),
357
- ...this.normalizeHeaders(headers)
358
- };
605
+ const result = {};
606
+ this.appendHeaders(result, defaults);
607
+ this.appendHeaders(result, headers);
608
+ return result;
359
609
  }
360
- /**
361
- * Normalize headers.
362
- */
363
- static normalizeHeaders(headers) {
610
+ static appendHeaders(result, headers) {
364
611
  if (!headers) {
365
- return {};
612
+ return;
366
613
  }
367
614
  if (headers instanceof Headers) {
368
- const result = {};
369
615
  headers.forEach((value, key) => {
370
- result[key] = value;
616
+ setHeader(result, key, value);
371
617
  });
372
- return result;
618
+ return;
373
619
  }
374
620
  if (Array.isArray(headers)) {
375
- return Object.fromEntries(headers);
621
+ for (const [key, value] of headers) {
622
+ setHeader(
623
+ result,
624
+ key.toLowerCase(),
625
+ String(value)
626
+ );
627
+ }
628
+ return;
629
+ }
630
+ for (const key in headers) {
631
+ if (Object.prototype.hasOwnProperty.call(headers, key)) {
632
+ setHeader(
633
+ result,
634
+ key.toLowerCase(),
635
+ String(headers[key])
636
+ );
637
+ }
638
+ }
639
+ }
640
+ static mergeObject(defaults, value) {
641
+ if (!defaults && !value) {
642
+ return void 0;
643
+ }
644
+ return {
645
+ ...defaults,
646
+ ...value
647
+ };
648
+ }
649
+ static mergeRetry(defaults, retry) {
650
+ if (retry === void 0) {
651
+ return defaults;
652
+ }
653
+ if (typeof retry === "number") {
654
+ return retry;
655
+ }
656
+ const normalizedDefaults = typeof defaults === "number" ? {
657
+ retries: defaults
658
+ } : defaults;
659
+ return {
660
+ ...normalizedDefaults,
661
+ ...retry
662
+ };
663
+ }
664
+ static mergeExtensions(defaults, extensions) {
665
+ if (!defaults && !extensions) {
666
+ return void 0;
667
+ }
668
+ const result = {
669
+ ...defaults,
670
+ ...extensions
671
+ };
672
+ for (const key in extensions) {
673
+ if (!Object.prototype.hasOwnProperty.call(
674
+ extensions,
675
+ key
676
+ )) {
677
+ continue;
678
+ }
679
+ const defaultValue = defaults?.[key];
680
+ const requestValue = extensions?.[key];
681
+ if (isPlainObject2(defaultValue) && isPlainObject2(requestValue)) {
682
+ result[key] = {
683
+ ...defaultValue,
684
+ ...requestValue
685
+ };
686
+ }
687
+ }
688
+ return result;
689
+ }
690
+ static hasBodyConfig(config) {
691
+ return config.body !== void 0 || config.json !== void 0 || config.form !== void 0 || config.formData !== void 0 || Object.prototype.hasOwnProperty.call(config, "body") || Object.prototype.hasOwnProperty.call(config, "json") || Object.prototype.hasOwnProperty.call(config, "form") || Object.prototype.hasOwnProperty.call(config, "formData");
692
+ }
693
+ static mergeBodyConfig(defaults, config) {
694
+ const keys = [
695
+ "body",
696
+ "json",
697
+ "form",
698
+ "formData"
699
+ ];
700
+ const hasRequestBodyConfig = keys.some((key) => {
701
+ return Object.prototype.hasOwnProperty.call(config, key);
702
+ });
703
+ if (!hasRequestBodyConfig) {
704
+ return {
705
+ body: defaults.body,
706
+ json: defaults.json,
707
+ form: defaults.form,
708
+ formData: defaults.formData
709
+ };
376
710
  }
377
- return headers;
711
+ return {
712
+ body: config.body,
713
+ json: config.json,
714
+ form: config.form,
715
+ formData: config.formData
716
+ };
378
717
  }
379
718
  };
719
+ function isPlainObject2(value) {
720
+ return Object.prototype.toString.call(value) === "[object Object]";
721
+ }
722
+ function setHeader(headers, key, value) {
723
+ if (key === "__proto__") {
724
+ Object.defineProperty(headers, key, {
725
+ value,
726
+ enumerable: true,
727
+ configurable: true,
728
+ writable: true
729
+ });
730
+ return;
731
+ }
732
+ headers[key] = value;
733
+ }
380
734
 
381
735
  // src/core/RequestContext.ts
382
736
  var RequestContext = class {
@@ -393,36 +747,75 @@ var Pipeline = class {
393
747
  this.interceptors = interceptors;
394
748
  this.hooks = hooks;
395
749
  }
396
- async execute(config) {
750
+ async execute(config, preserveRaw = true) {
397
751
  const context = new RequestContext(config);
752
+ let validatedHeaders;
398
753
  try {
399
- context.config = await this.interceptors.request.run(context.config);
400
- await this.hooks.runRequest(context);
754
+ try {
755
+ if (this.interceptors.request.active) {
756
+ context.config = await this.interceptors.request.run(
757
+ context.config
758
+ );
759
+ }
760
+ let headers = validateRequestConfig(context.config);
761
+ if (this.hooks.hasRequestHooks) {
762
+ await this.hooks.runRequest(context);
763
+ headers = validateRequestConfig(context.config);
764
+ }
765
+ validatedHeaders = headers;
766
+ } catch (error) {
767
+ return this.fail(context, error);
768
+ }
401
769
  if (context.response) {
402
- return context.response;
770
+ try {
771
+ return await this.processResponse(context);
772
+ } catch (error) {
773
+ return this.fail(context, error);
774
+ }
403
775
  }
404
776
  let attempt = 0;
405
777
  while (true) {
406
778
  try {
407
- context.response = await this.adapter.request(context.config);
408
- context.response = await this.interceptors.response.run(
409
- context.response
779
+ const headers = validatedHeaders;
780
+ validatedHeaders = void 0;
781
+ context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(
782
+ context.config,
783
+ headers,
784
+ preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active
785
+ ) : await this.adapter.request(
786
+ context.config
410
787
  );
411
- await this.hooks.runResponse(context);
412
- return context.response;
788
+ return await this.processResponse(context);
413
789
  } catch (error) {
414
- context.error = error;
415
- await this.hooks.runError(context);
416
- const decision = await this.hooks.resolveRetry(context, attempt);
790
+ const errorHooksSucceeded = await this.notifyError(
791
+ context,
792
+ error
793
+ );
794
+ if (!errorHooksSucceeded) {
795
+ return this.fail(context, context.error, false);
796
+ }
797
+ if (!this.hooks.hasRetryHooks) {
798
+ return this.fail(context, context.error, false);
799
+ }
800
+ let decision;
801
+ try {
802
+ decision = await this.hooks.resolveRetry(context, attempt);
803
+ } catch (retryError) {
804
+ return this.fail(context, retryError);
805
+ }
417
806
  if (!decision.retry) {
418
- context.error = await this.interceptors.error.run(context.error);
419
- throw context.error;
807
+ return this.fail(context, context.error, false);
420
808
  }
421
809
  context.error = void 0;
422
810
  context.response = void 0;
423
811
  attempt += 1;
424
- if (decision.delay && decision.delay > 0) {
425
- await sleep(decision.delay);
812
+ try {
813
+ await waitForRetry(
814
+ decision.delay ?? 0,
815
+ context.config
816
+ );
817
+ } catch (waitError) {
818
+ return this.fail(context, waitError);
426
819
  }
427
820
  }
428
821
  }
@@ -430,10 +823,85 @@ var Pipeline = class {
430
823
  context.endTime = Date.now();
431
824
  }
432
825
  }
826
+ async processResponse(context) {
827
+ if (this.hooks.hasResponseHooks) {
828
+ await this.hooks.runResponse(context);
829
+ }
830
+ if (this.interceptors.response.active) {
831
+ context.response = await this.interceptors.response.run(
832
+ context.response
833
+ );
834
+ }
835
+ return context.response;
836
+ }
837
+ async notifyError(context, error) {
838
+ context.error = error;
839
+ if (this.hooks.hasErrorHooks) {
840
+ try {
841
+ await this.hooks.runError(context);
842
+ return true;
843
+ } catch (hookError) {
844
+ context.error = hookError;
845
+ return false;
846
+ }
847
+ }
848
+ return true;
849
+ }
850
+ async fail(context, error, notifyHooks = true) {
851
+ if (notifyHooks) {
852
+ await this.notifyError(context, error);
853
+ } else {
854
+ context.error = error;
855
+ }
856
+ if (this.interceptors.error.active) {
857
+ context.error = await this.interceptors.error.run(
858
+ context.error
859
+ );
860
+ }
861
+ throw context.error;
862
+ }
433
863
  };
434
- function sleep(milliseconds) {
435
- return new Promise((resolve) => {
436
- setTimeout(resolve, milliseconds);
864
+ function waitForRetry(milliseconds, config) {
865
+ const signal = config.signal;
866
+ if (signal?.aborted) {
867
+ return Promise.reject(createAbortError(signal.reason, config));
868
+ }
869
+ if (milliseconds <= 0) {
870
+ return Promise.resolve();
871
+ }
872
+ return new Promise((resolve, reject) => {
873
+ const timer = setTimeout(() => {
874
+ cleanup();
875
+ resolve();
876
+ }, milliseconds);
877
+ const onAbort = () => {
878
+ clearTimeout(timer);
879
+ cleanup();
880
+ reject(createAbortError(signal?.reason, config));
881
+ };
882
+ const cleanup = () => {
883
+ signal?.removeEventListener("abort", onAbort);
884
+ };
885
+ signal?.addEventListener("abort", onAbort, {
886
+ once: true
887
+ });
888
+ });
889
+ }
890
+ function createAbortError(reason, config) {
891
+ if (reason instanceof RequestError) {
892
+ return new RequestError(reason.message, {
893
+ code: reason.code,
894
+ status: reason.status,
895
+ data: reason.data,
896
+ response: reason.response,
897
+ config: reason.config ?? config,
898
+ cause: reason
899
+ });
900
+ }
901
+ return new RequestError("Request aborted during retry delay", {
902
+ code: "ABORT_ERROR",
903
+ config,
904
+ cause: reason
437
905
  });
438
906
  }
439
907
 
@@ -442,64 +910,100 @@ var InterceptorManager = class {
442
910
  constructor() {
443
911
  this.id = 0;
444
912
  this.interceptors = /* @__PURE__ */ new Map();
913
+ this.orderedInterceptors = [];
445
914
  }
446
- use(interceptor) {
915
+ get active() {
916
+ return this.orderedInterceptors.length > 0;
917
+ }
918
+ use(interceptor, options = {}) {
447
919
  const id = this.id++;
448
- this.interceptors.set(id, interceptor);
920
+ this.interceptors.set(id, {
921
+ id,
922
+ interceptor,
923
+ priority: normalizePriority(options.priority)
924
+ });
925
+ this.refreshOrder();
449
926
  return id;
450
927
  }
451
928
  eject(id) {
452
- this.interceptors.delete(id);
929
+ if (this.interceptors.delete(id)) {
930
+ this.refreshOrder();
931
+ }
453
932
  }
454
933
  clear() {
455
934
  this.interceptors.clear();
935
+ this.orderedInterceptors = [];
456
936
  }
457
937
  async run(value) {
458
938
  let result = value;
459
- for (const interceptor of this.interceptors.values()) {
460
- result = await interceptor(result);
939
+ for (const entry of this.orderedInterceptors) {
940
+ result = await entry.interceptor(result);
461
941
  }
462
942
  return result;
463
943
  }
944
+ refreshOrder() {
945
+ this.orderedInterceptors = [
946
+ ...this.interceptors.values()
947
+ ].sort(
948
+ (first, second) => {
949
+ return second.priority - first.priority || first.id - second.id;
950
+ }
951
+ );
952
+ }
464
953
  };
954
+ function normalizePriority(priority) {
955
+ return Number.isFinite(priority) ? priority ?? 0 : 0;
956
+ }
465
957
 
466
958
  // src/interceptors/PluginHooks.ts
467
959
  var PluginHooks = class {
468
960
  constructor() {
469
- this.requestHooks = [];
470
- this.responseHooks = [];
471
- this.errorHooks = [];
472
- this.retryHooks = [];
961
+ this.requestHooks = new HookRegistry();
962
+ this.responseHooks = new HookRegistry();
963
+ this.errorHooks = new HookRegistry();
964
+ this.retryHooks = new HookRegistry();
965
+ }
966
+ get hasRequestHooks() {
967
+ return this.requestHooks.active;
473
968
  }
474
- onRequest(hook) {
475
- this.requestHooks.push(hook);
969
+ get hasResponseHooks() {
970
+ return this.responseHooks.active;
476
971
  }
477
- onResponse(hook) {
478
- this.responseHooks.push(hook);
972
+ get hasErrorHooks() {
973
+ return this.errorHooks.active;
479
974
  }
480
- onError(hook) {
481
- this.errorHooks.push(hook);
975
+ get hasRetryHooks() {
976
+ return this.retryHooks.active;
482
977
  }
483
- onRetry(hook) {
484
- this.retryHooks.push(hook);
978
+ onRequest(hook, options = {}) {
979
+ return this.requestHooks.register(hook, options);
980
+ }
981
+ onResponse(hook, options = {}) {
982
+ return this.responseHooks.register(hook, options);
983
+ }
984
+ onError(hook, options = {}) {
985
+ return this.errorHooks.register(hook, options);
986
+ }
987
+ onRetry(hook, options = {}) {
988
+ return this.retryHooks.register(hook, options);
485
989
  }
486
990
  async runRequest(context) {
487
- for (const hook of this.requestHooks) {
991
+ for (const hook of this.requestHooks.values()) {
488
992
  await hook(context);
489
993
  }
490
994
  }
491
995
  async runResponse(context) {
492
- for (const hook of this.responseHooks) {
996
+ for (const hook of this.responseHooks.values()) {
493
997
  await hook(context);
494
998
  }
495
999
  }
496
1000
  async runError(context) {
497
- for (const hook of this.errorHooks) {
1001
+ for (const hook of this.errorHooks.values()) {
498
1002
  await hook(context);
499
1003
  }
500
1004
  }
501
1005
  async resolveRetry(context, attempt) {
502
- for (const hook of this.retryHooks) {
1006
+ for (const hook of this.retryHooks.values()) {
503
1007
  const decision = await hook(context, attempt);
504
1008
  if (decision) {
505
1009
  return decision;
@@ -511,11 +1015,175 @@ var PluginHooks = class {
511
1015
  };
512
1016
  }
513
1017
  };
1018
+ var HookRegistry = class {
1019
+ constructor() {
1020
+ this.id = 0;
1021
+ this.hooks = /* @__PURE__ */ new Map();
1022
+ this.orderedHooks = [];
1023
+ }
1024
+ get active() {
1025
+ return this.orderedHooks.length > 0;
1026
+ }
1027
+ register(hook, options) {
1028
+ const id = this.id++;
1029
+ this.hooks.set(id, {
1030
+ id,
1031
+ hook,
1032
+ priority: normalizePriority2(options.priority)
1033
+ });
1034
+ this.refreshOrder();
1035
+ return () => {
1036
+ if (this.hooks.delete(id)) {
1037
+ this.refreshOrder();
1038
+ }
1039
+ };
1040
+ }
1041
+ values() {
1042
+ return this.orderedHooks;
1043
+ }
1044
+ refreshOrder() {
1045
+ this.orderedHooks = [
1046
+ ...this.hooks.values()
1047
+ ].sort((first, second) => {
1048
+ return second.priority - first.priority || first.id - second.id;
1049
+ }).map((entry) => entry.hook);
1050
+ }
1051
+ };
1052
+ function normalizePriority2(priority) {
1053
+ return Number.isFinite(priority) ? priority ?? 0 : 0;
1054
+ }
1055
+
1056
+ // src/plugins/PluginError.ts
1057
+ var PluginError = class extends Error {
1058
+ constructor(message, options) {
1059
+ super(message);
1060
+ this.name = "PluginError";
1061
+ this.code = options.code;
1062
+ this.plugin = options.plugin;
1063
+ this.relatedPlugin = options.relatedPlugin;
1064
+ Object.setPrototypeOf(this, new.target.prototype);
1065
+ }
1066
+ };
1067
+
1068
+ // src/plugins/PluginScope.ts
1069
+ function createPluginScope(interceptors, hooks, priority = 0) {
1070
+ const cleanups = [];
1071
+ const context = {
1072
+ interceptors: {
1073
+ request: createScopedInterceptor(
1074
+ interceptors.request,
1075
+ priority,
1076
+ cleanups
1077
+ ),
1078
+ response: createScopedInterceptor(
1079
+ interceptors.response,
1080
+ priority,
1081
+ cleanups
1082
+ ),
1083
+ error: createScopedInterceptor(
1084
+ interceptors.error,
1085
+ priority,
1086
+ cleanups
1087
+ )
1088
+ },
1089
+ hooks: createScopedHooks(hooks, priority, cleanups)
1090
+ };
1091
+ return {
1092
+ context,
1093
+ addCleanup(cleanup) {
1094
+ cleanups.push(once(cleanup));
1095
+ },
1096
+ cleanup() {
1097
+ let firstError;
1098
+ for (const cleanup of [...cleanups].reverse()) {
1099
+ try {
1100
+ cleanup();
1101
+ } catch (error) {
1102
+ firstError ?? (firstError = error);
1103
+ }
1104
+ }
1105
+ cleanups.length = 0;
1106
+ if (firstError !== void 0) {
1107
+ throw firstError;
1108
+ }
1109
+ }
1110
+ };
1111
+ }
1112
+ function createScopedInterceptor(manager, pluginPriority, cleanups) {
1113
+ const ids = /* @__PURE__ */ new Set();
1114
+ cleanups.push(() => {
1115
+ for (const id of ids) {
1116
+ manager.eject(id);
1117
+ }
1118
+ ids.clear();
1119
+ });
1120
+ return {
1121
+ use(interceptor, options = {}) {
1122
+ const id = manager.use(interceptor, {
1123
+ priority: options.priority ?? pluginPriority
1124
+ });
1125
+ ids.add(id);
1126
+ return id;
1127
+ },
1128
+ eject(id) {
1129
+ manager.eject(id);
1130
+ ids.delete(id);
1131
+ }
1132
+ };
1133
+ }
1134
+ function createScopedHooks(hooks, pluginPriority, cleanups) {
1135
+ return {
1136
+ onRequest(hook, options) {
1137
+ return trackHook(
1138
+ hooks.onRequest(hook, withPriority(options, pluginPriority)),
1139
+ cleanups
1140
+ );
1141
+ },
1142
+ onResponse(hook, options) {
1143
+ return trackHook(
1144
+ hooks.onResponse(hook, withPriority(options, pluginPriority)),
1145
+ cleanups
1146
+ );
1147
+ },
1148
+ onError(hook, options) {
1149
+ return trackHook(
1150
+ hooks.onError(hook, withPriority(options, pluginPriority)),
1151
+ cleanups
1152
+ );
1153
+ },
1154
+ onRetry(hook, options) {
1155
+ return trackHook(
1156
+ hooks.onRetry(hook, withPriority(options, pluginPriority)),
1157
+ cleanups
1158
+ );
1159
+ }
1160
+ };
1161
+ }
1162
+ function trackHook(dispose, cleanups) {
1163
+ const trackedDispose = once(dispose);
1164
+ cleanups.push(trackedDispose);
1165
+ return trackedDispose;
1166
+ }
1167
+ function withPriority(options, pluginPriority) {
1168
+ return {
1169
+ priority: options?.priority ?? pluginPriority
1170
+ };
1171
+ }
1172
+ function once(cleanup) {
1173
+ let active = true;
1174
+ return () => {
1175
+ if (!active) {
1176
+ return;
1177
+ }
1178
+ active = false;
1179
+ cleanup();
1180
+ };
1181
+ }
514
1182
 
515
1183
  // src/client/Client.ts
516
- var Client = class {
1184
+ var Client = class _Client {
517
1185
  constructor(options = {}) {
518
- this.installedPlugins = /* @__PURE__ */ new Set();
1186
+ this.installedPlugins = /* @__PURE__ */ new Map();
519
1187
  this.hooks = new PluginHooks();
520
1188
  this.interceptors = {
521
1189
  request: new InterceptorManager(),
@@ -524,24 +1192,95 @@ var Client = class {
524
1192
  };
525
1193
  const { adapter = new FetchAdapter(), ...defaults } = options;
526
1194
  this.defaults = defaults;
1195
+ this.adapter = adapter;
527
1196
  this.pipeline = this.createPipeline(adapter);
528
1197
  }
1198
+ /**
1199
+ * Create an isolated client that inherits this client's defaults.
1200
+ */
1201
+ extend(options = {}) {
1202
+ const {
1203
+ adapter = this.adapter,
1204
+ ...overrides
1205
+ } = options;
1206
+ const defaults = ConfigMerger.mergeDefaults(
1207
+ this.defaults,
1208
+ overrides
1209
+ );
1210
+ return new _Client({
1211
+ ...defaults,
1212
+ adapter
1213
+ });
1214
+ }
529
1215
  use(plugin) {
530
1216
  if (this.installedPlugins.has(plugin.name)) {
531
1217
  return this;
532
1218
  }
533
- plugin.install({
534
- interceptors: this.interceptors,
535
- hooks: this.hooks
536
- });
537
- this.installedPlugins.add(plugin.name);
1219
+ this.validatePlugin(plugin);
1220
+ const scope = createPluginScope(
1221
+ this.interceptors,
1222
+ this.hooks,
1223
+ plugin.priority
1224
+ );
1225
+ try {
1226
+ const cleanup = plugin.install(scope.context);
1227
+ if (cleanup) {
1228
+ scope.addCleanup(cleanup);
1229
+ }
1230
+ this.installedPlugins.set(plugin.name, {
1231
+ plugin,
1232
+ cleanup: scope.cleanup
1233
+ });
1234
+ } catch (error) {
1235
+ try {
1236
+ scope.cleanup();
1237
+ } catch {
1238
+ }
1239
+ throw error;
1240
+ }
1241
+ return this;
1242
+ }
1243
+ unuse(pluginName) {
1244
+ const installed = this.installedPlugins.get(pluginName);
1245
+ if (!installed) {
1246
+ return this;
1247
+ }
1248
+ const dependent = this.findDependent(pluginName);
1249
+ if (dependent) {
1250
+ throw new PluginError(
1251
+ `Cannot remove plugin "${pluginName}" while "${dependent}" depends on it`,
1252
+ {
1253
+ code: "DEPENDENCY_IN_USE",
1254
+ plugin: pluginName,
1255
+ relatedPlugin: dependent
1256
+ }
1257
+ );
1258
+ }
1259
+ try {
1260
+ installed.cleanup();
1261
+ } finally {
1262
+ this.installedPlugins.delete(pluginName);
1263
+ }
538
1264
  return this;
539
1265
  }
1266
+ hasPlugin(pluginName) {
1267
+ return this.installedPlugins.has(pluginName);
1268
+ }
540
1269
  async request(config) {
541
- const mergedConfig = ConfigMerger.merge(this.defaults, config);
542
- const response = await this.pipeline.execute(mergedConfig);
1270
+ const mergedConfig = ConfigMerger.merge(
1271
+ this.defaults,
1272
+ config
1273
+ );
1274
+ const response = await this.pipeline.execute(
1275
+ mergedConfig,
1276
+ false
1277
+ );
543
1278
  return response.data;
544
1279
  }
1280
+ async requestResponse(config) {
1281
+ const mergedConfig = ConfigMerger.merge(this.defaults, config);
1282
+ return this.pipeline.execute(mergedConfig);
1283
+ }
545
1284
  get(url, config = {}) {
546
1285
  return this.request({
547
1286
  ...config,
@@ -549,6 +1288,13 @@ var Client = class {
549
1288
  method: "GET"
550
1289
  });
551
1290
  }
1291
+ getResponse(url, config = {}) {
1292
+ return this.requestResponse({
1293
+ ...config,
1294
+ url,
1295
+ method: "GET"
1296
+ });
1297
+ }
552
1298
  post(url, config = {}) {
553
1299
  return this.request({
554
1300
  ...config,
@@ -556,6 +1302,13 @@ var Client = class {
556
1302
  method: "POST"
557
1303
  });
558
1304
  }
1305
+ postResponse(url, config = {}) {
1306
+ return this.requestResponse({
1307
+ ...config,
1308
+ url,
1309
+ method: "POST"
1310
+ });
1311
+ }
559
1312
  put(url, config = {}) {
560
1313
  return this.request({
561
1314
  ...config,
@@ -563,6 +1316,13 @@ var Client = class {
563
1316
  method: "PUT"
564
1317
  });
565
1318
  }
1319
+ putResponse(url, config = {}) {
1320
+ return this.requestResponse({
1321
+ ...config,
1322
+ url,
1323
+ method: "PUT"
1324
+ });
1325
+ }
566
1326
  patch(url, config = {}) {
567
1327
  return this.request({
568
1328
  ...config,
@@ -570,6 +1330,13 @@ var Client = class {
570
1330
  method: "PATCH"
571
1331
  });
572
1332
  }
1333
+ patchResponse(url, config = {}) {
1334
+ return this.requestResponse({
1335
+ ...config,
1336
+ url,
1337
+ method: "PATCH"
1338
+ });
1339
+ }
573
1340
  delete(url, config = {}) {
574
1341
  return this.request({
575
1342
  ...config,
@@ -577,9 +1344,92 @@ var Client = class {
577
1344
  method: "DELETE"
578
1345
  });
579
1346
  }
1347
+ deleteResponse(url, config = {}) {
1348
+ return this.requestResponse({
1349
+ ...config,
1350
+ url,
1351
+ method: "DELETE"
1352
+ });
1353
+ }
1354
+ head(url, config = {}) {
1355
+ return this.request({
1356
+ ...config,
1357
+ url,
1358
+ method: "HEAD"
1359
+ });
1360
+ }
1361
+ headResponse(url, config = {}) {
1362
+ return this.requestResponse({
1363
+ ...config,
1364
+ url,
1365
+ method: "HEAD"
1366
+ });
1367
+ }
1368
+ options(url, config = {}) {
1369
+ return this.request({
1370
+ ...config,
1371
+ url,
1372
+ method: "OPTIONS"
1373
+ });
1374
+ }
1375
+ optionsResponse(url, config = {}) {
1376
+ return this.requestResponse({
1377
+ ...config,
1378
+ url,
1379
+ method: "OPTIONS"
1380
+ });
1381
+ }
580
1382
  createPipeline(adapter) {
581
1383
  return new Pipeline(adapter, this.interceptors, this.hooks);
582
1384
  }
1385
+ validatePlugin(plugin) {
1386
+ const missingDependency = plugin.requires?.find((name) => {
1387
+ return !this.installedPlugins.has(name);
1388
+ });
1389
+ if (missingDependency) {
1390
+ throw new PluginError(
1391
+ `Plugin "${plugin.name}" requires "${missingDependency}"`,
1392
+ {
1393
+ code: "MISSING_DEPENDENCY",
1394
+ plugin: plugin.name,
1395
+ relatedPlugin: missingDependency
1396
+ }
1397
+ );
1398
+ }
1399
+ const directConflict = plugin.conflicts?.find((name) => {
1400
+ return this.installedPlugins.has(name);
1401
+ });
1402
+ if (directConflict) {
1403
+ throw new PluginError(
1404
+ `Plugin "${plugin.name}" conflicts with "${directConflict}"`,
1405
+ {
1406
+ code: "PLUGIN_CONFLICT",
1407
+ plugin: plugin.name,
1408
+ relatedPlugin: directConflict
1409
+ }
1410
+ );
1411
+ }
1412
+ for (const installed of this.installedPlugins.values()) {
1413
+ if (installed.plugin.conflicts?.includes(plugin.name)) {
1414
+ throw new PluginError(
1415
+ `Plugin "${plugin.name}" conflicts with "${installed.plugin.name}"`,
1416
+ {
1417
+ code: "PLUGIN_CONFLICT",
1418
+ plugin: plugin.name,
1419
+ relatedPlugin: installed.plugin.name
1420
+ }
1421
+ );
1422
+ }
1423
+ }
1424
+ }
1425
+ findDependent(pluginName) {
1426
+ for (const installed of this.installedPlugins.values()) {
1427
+ if (installed.plugin.requires?.includes(pluginName)) {
1428
+ return installed.plugin.name;
1429
+ }
1430
+ }
1431
+ return void 0;
1432
+ }
583
1433
  };
584
1434
 
585
1435
  // src/client/createClient.ts
@@ -587,6 +1437,11 @@ function createClient(options = {}) {
587
1437
  return new Client(options);
588
1438
  }
589
1439
 
1440
+ // src/plugins/resolveExtensionConfig.ts
1441
+ function resolveExtensionConfig(config, key, legacy) {
1442
+ return config.extensions?.[key] ?? legacy;
1443
+ }
1444
+
590
1445
  // src/plugins/authPlugin.ts
591
1446
  function authPlugin(options = {}) {
592
1447
  let refreshPromise;
@@ -613,17 +1468,18 @@ function authPlugin(options = {}) {
613
1468
  const refreshedToken = await refreshAccessToken(
614
1469
  options.refreshToken
615
1470
  );
616
- if (refreshedToken) {
617
- await options.storage?.set(refreshedToken);
618
- }
619
- const token = refreshedToken || await resolvePluginToken(options);
620
- if (!token) {
1471
+ const authorization = await resolveAuthorization(
1472
+ requestContext.config,
1473
+ options,
1474
+ typeof refreshedToken === "string" ? refreshedToken : void 0
1475
+ );
1476
+ if (!authorization.token) {
621
1477
  return void 0;
622
1478
  }
623
1479
  requestContext.config = setAuthorizationHeader(
624
1480
  requestContext.config,
625
- token,
626
- options.scheme
1481
+ authorization.token,
1482
+ authorization.scheme
627
1483
  );
628
1484
  return {
629
1485
  retry: true,
@@ -637,7 +1493,12 @@ function authPlugin(options = {}) {
637
1493
  };
638
1494
  async function refreshAccessToken(refreshToken) {
639
1495
  if (!refreshPromise) {
640
- refreshPromise = Promise.resolve(refreshToken()).finally(() => {
1496
+ refreshPromise = Promise.resolve(refreshToken()).then(async (token) => {
1497
+ if (token) {
1498
+ await options.storage?.set(token);
1499
+ }
1500
+ return token;
1501
+ }).finally(() => {
641
1502
  refreshPromise = void 0;
642
1503
  });
643
1504
  }
@@ -645,17 +1506,28 @@ function authPlugin(options = {}) {
645
1506
  }
646
1507
  }
647
1508
  async function applyAuthorization(config, options) {
648
- const requestAuth = config.auth;
649
- const token = requestAuth?.token ? await resolveToken(requestAuth.token) : await resolvePluginToken(options);
650
- if (!token) {
1509
+ const authorization = await resolveAuthorization(config, options);
1510
+ if (!authorization.token) {
651
1511
  return config;
652
1512
  }
653
1513
  return setAuthorizationHeader(
654
1514
  config,
655
- token,
656
- requestAuth?.scheme ?? options.scheme
1515
+ authorization.token,
1516
+ authorization.scheme
657
1517
  );
658
1518
  }
1519
+ async function resolveAuthorization(config, options, tokenOverride) {
1520
+ const requestAuth = resolveExtensionConfig(
1521
+ config,
1522
+ "auth",
1523
+ config.auth
1524
+ );
1525
+ const token = tokenOverride ?? (requestAuth?.token ? await resolveToken(requestAuth.token) : await resolvePluginToken(options));
1526
+ return {
1527
+ token,
1528
+ scheme: requestAuth?.scheme ?? options.scheme
1529
+ };
1530
+ }
659
1531
  async function resolvePluginToken(options) {
660
1532
  const configuredToken = await resolveToken(options.token);
661
1533
  if (configuredToken) {
@@ -683,17 +1555,47 @@ function defaultShouldRefresh(error) {
683
1555
  }
684
1556
 
685
1557
  // src/plugins/cachePlugin.ts
686
- var cacheStore = /* @__PURE__ */ new Map();
687
- function cachePlugin() {
688
- return {
1558
+ var DEFAULT_CACHE_METHODS = [
1559
+ "GET",
1560
+ "HEAD"
1561
+ ];
1562
+ var DEFAULT_VARY_HEADERS = [
1563
+ "authorization",
1564
+ "cookie",
1565
+ "accept",
1566
+ "accept-language"
1567
+ ];
1568
+ var cacheGeneration = 0;
1569
+ function cachePlugin(options = {}) {
1570
+ const cacheStore = /* @__PURE__ */ new Map();
1571
+ const cacheHits = /* @__PURE__ */ new WeakSet();
1572
+ const methods = new Set(
1573
+ options.methods ?? DEFAULT_CACHE_METHODS
1574
+ );
1575
+ const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
1576
+ let localGeneration = cacheGeneration;
1577
+ const plugin = {
689
1578
  name: "cache",
1579
+ clear() {
1580
+ cacheStore.clear();
1581
+ localGeneration = cacheGeneration;
1582
+ },
690
1583
  install(context) {
691
1584
  context.hooks.onRequest((requestContext) => {
692
- const cache = requestContext.config.cache;
693
- if (!cache?.enabled) {
1585
+ syncGeneration();
1586
+ const cache = resolveExtensionConfig(
1587
+ requestContext.config,
1588
+ "cache",
1589
+ requestContext.config.cache
1590
+ );
1591
+ if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) {
694
1592
  return;
695
1593
  }
696
- const key = createCacheKey(requestContext.config);
1594
+ const key = createCacheKey(
1595
+ requestContext.config,
1596
+ cache,
1597
+ varyHeaders
1598
+ );
697
1599
  const record = cacheStore.get(key);
698
1600
  if (!record) {
699
1601
  return;
@@ -703,72 +1605,472 @@ function cachePlugin() {
703
1605
  return;
704
1606
  }
705
1607
  requestContext.response = {
706
- data: record.data,
707
- status: 200,
708
- statusText: "OK",
709
- headers: new Headers(),
1608
+ data: cloneCacheValue(record.data),
1609
+ status: record.status,
1610
+ statusText: record.statusText,
1611
+ headers: new Headers(record.headers),
710
1612
  config: requestContext.config,
711
- raw: new Response()
1613
+ raw: cloneRawResponse(record)
712
1614
  };
1615
+ cacheHits.add(requestContext);
713
1616
  });
714
1617
  context.hooks.onResponse((requestContext) => {
715
- const cache = requestContext.config.cache;
716
- if (!cache?.enabled || !requestContext.response) {
1618
+ syncGeneration();
1619
+ if (cacheHits.has(requestContext)) {
1620
+ return;
1621
+ }
1622
+ const cache = resolveExtensionConfig(
1623
+ requestContext.config,
1624
+ "cache",
1625
+ requestContext.config.cache
1626
+ );
1627
+ if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) {
717
1628
  return;
718
1629
  }
719
- const key = createCacheKey(requestContext.config);
1630
+ const key = createCacheKey(
1631
+ requestContext.config,
1632
+ cache,
1633
+ varyHeaders
1634
+ );
720
1635
  const ttl = cache.ttl ?? 3e4;
1636
+ if (ttl <= 0) {
1637
+ cacheStore.delete(key);
1638
+ return;
1639
+ }
721
1640
  cacheStore.set(key, {
722
- data: requestContext.response.data,
723
- expiresAt: Date.now() + ttl
1641
+ data: cloneCacheValue(requestContext.response.data),
1642
+ expiresAt: Date.now() + ttl,
1643
+ status: requestContext.response.status,
1644
+ statusText: requestContext.response.statusText,
1645
+ headers: new Headers(requestContext.response.headers),
1646
+ raw: cloneResponse(requestContext.response.raw)
724
1647
  });
725
1648
  });
726
1649
  }
727
1650
  };
1651
+ return plugin;
1652
+ function syncGeneration() {
1653
+ if (localGeneration === cacheGeneration) {
1654
+ return;
1655
+ }
1656
+ cacheStore.clear();
1657
+ localGeneration = cacheGeneration;
1658
+ }
728
1659
  }
729
1660
  function clearCache() {
730
- cacheStore.clear();
1661
+ cacheGeneration += 1;
1662
+ }
1663
+ function isCacheableRequest(config, methods) {
1664
+ return methods.has(config.method ?? "GET") && config.responseType !== "stream";
731
1665
  }
732
- function createCacheKey(config) {
733
- if (config.cache?.key) {
734
- return config.cache.key;
1666
+ function createCacheKey(config, cache, varyHeaders) {
1667
+ if (cache.key) {
1668
+ return cache.key;
735
1669
  }
1670
+ const headers = new Headers(config.headers);
736
1671
  return JSON.stringify({
737
1672
  method: config.method ?? "GET",
738
1673
  baseURL: config.baseURL,
739
1674
  url: config.url,
740
- query: config.query
1675
+ query: normalizeQuery(config.query),
1676
+ responseType: config.responseType ?? "auto",
1677
+ headers: Object.fromEntries(
1678
+ varyHeaders.map((name) => [
1679
+ name.toLowerCase(),
1680
+ headers.get(name)
1681
+ ])
1682
+ )
1683
+ });
1684
+ }
1685
+ function normalizeQuery(query) {
1686
+ if (!query) {
1687
+ return [];
1688
+ }
1689
+ const entries = [];
1690
+ for (const key of Object.keys(query).sort()) {
1691
+ appendQueryValue(entries, key, query[key]);
1692
+ }
1693
+ return entries;
1694
+ }
1695
+ function appendQueryValue(entries, key, value) {
1696
+ if (value === null || value === void 0) {
1697
+ return;
1698
+ }
1699
+ if (Array.isArray(value)) {
1700
+ for (const item of value) {
1701
+ appendQueryValue(entries, key, item);
1702
+ }
1703
+ return;
1704
+ }
1705
+ entries.push([key, String(value)]);
1706
+ }
1707
+ function cloneRawResponse(record) {
1708
+ if (record.raw) {
1709
+ const cloned = cloneResponse(record.raw);
1710
+ if (cloned) {
1711
+ return cloned;
1712
+ }
1713
+ }
1714
+ return new Response(null, {
1715
+ status: record.status,
1716
+ statusText: record.statusText,
1717
+ headers: record.headers
1718
+ });
1719
+ }
1720
+ function cloneResponse(response) {
1721
+ try {
1722
+ return response.clone();
1723
+ } catch {
1724
+ return void 0;
1725
+ }
1726
+ }
1727
+ function cloneCacheValue(value) {
1728
+ if (typeof structuredClone !== "function") {
1729
+ return value;
1730
+ }
1731
+ try {
1732
+ return structuredClone(value);
1733
+ } catch {
1734
+ return value;
1735
+ }
1736
+ }
1737
+
1738
+ // src/plugins/xhrTransport.ts
1739
+ function xhrRequest(config, options = {}) {
1740
+ let request;
1741
+ let xhr;
1742
+ try {
1743
+ request = buildRequest(config);
1744
+ xhr = new XMLHttpRequest();
1745
+ } catch (error) {
1746
+ request?.clear();
1747
+ return Promise.reject(
1748
+ createConfigError(config, error)
1749
+ );
1750
+ }
1751
+ const signal = request.init.signal;
1752
+ return new Promise((resolve, reject) => {
1753
+ let settled = false;
1754
+ const cleanup = () => {
1755
+ signal?.removeEventListener("abort", onSignalAbort);
1756
+ request.clear();
1757
+ xhr.onload = null;
1758
+ xhr.onerror = null;
1759
+ xhr.onabort = null;
1760
+ xhr.onprogress = null;
1761
+ if (xhr.upload) {
1762
+ xhr.upload.onprogress = null;
1763
+ }
1764
+ };
1765
+ const resolveOnce = (response) => {
1766
+ if (settled) {
1767
+ return;
1768
+ }
1769
+ settled = true;
1770
+ cleanup();
1771
+ resolve(response);
1772
+ };
1773
+ const rejectOnce = (error) => {
1774
+ if (settled) {
1775
+ return;
1776
+ }
1777
+ settled = true;
1778
+ cleanup();
1779
+ reject(error);
1780
+ };
1781
+ const abortWith = (error) => {
1782
+ rejectOnce(error);
1783
+ xhr.abort();
1784
+ };
1785
+ const onSignalAbort = () => {
1786
+ abortWith(
1787
+ createAbortError2(signal?.reason, config)
1788
+ );
1789
+ };
1790
+ xhr.onload = () => {
1791
+ void processResponse(xhr, config).then(
1792
+ resolveOnce,
1793
+ rejectOnce
1794
+ );
1795
+ };
1796
+ xhr.onerror = () => {
1797
+ rejectOnce(
1798
+ new RequestError("Network request failed", {
1799
+ code: "NETWORK_ERROR",
1800
+ config
1801
+ })
1802
+ );
1803
+ };
1804
+ xhr.onabort = () => {
1805
+ rejectOnce(
1806
+ createAbortError2(signal?.reason, config)
1807
+ );
1808
+ };
1809
+ xhr.onprogress = createProgressHandler(
1810
+ options.onDownloadProgress,
1811
+ abortWith
1812
+ );
1813
+ if (xhr.upload) {
1814
+ xhr.upload.onprogress = createProgressHandler(
1815
+ options.onUploadProgress,
1816
+ abortWith
1817
+ );
1818
+ }
1819
+ try {
1820
+ xhr.open(
1821
+ request.init.method ?? "GET",
1822
+ request.url,
1823
+ true
1824
+ );
1825
+ xhr.responseType = "blob";
1826
+ xhr.withCredentials = request.init.credentials === "include";
1827
+ new Headers(request.init.headers).forEach(
1828
+ (value, name) => {
1829
+ xhr.setRequestHeader(name, value);
1830
+ }
1831
+ );
1832
+ if (signal?.aborted) {
1833
+ onSignalAbort();
1834
+ return;
1835
+ }
1836
+ signal?.addEventListener("abort", onSignalAbort, {
1837
+ once: true
1838
+ });
1839
+ const body = request.init.body;
1840
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) {
1841
+ abortWith(
1842
+ new RequestError(
1843
+ "XMLHttpRequest cannot send a ReadableStream body",
1844
+ {
1845
+ code: "CONFIG_ERROR",
1846
+ config
1847
+ }
1848
+ )
1849
+ );
1850
+ return;
1851
+ }
1852
+ xhr.send(body);
1853
+ } catch (error) {
1854
+ abortWith(createConfigError(config, error));
1855
+ }
741
1856
  });
742
1857
  }
1858
+ async function processResponse(xhr, config) {
1859
+ if (xhr.status === 0) {
1860
+ throw new RequestError("Network request failed", {
1861
+ code: "NETWORK_ERROR",
1862
+ config
1863
+ });
1864
+ }
1865
+ try {
1866
+ const headers = parseHeaders(
1867
+ xhr.getAllResponseHeaders()
1868
+ );
1869
+ const blob = xhr.response instanceof Blob ? xhr.response : new Blob(
1870
+ xhr.response === null ? [] : [xhr.response],
1871
+ {
1872
+ type: headers.get("content-type") ?? ""
1873
+ }
1874
+ );
1875
+ const raw = new Response(
1876
+ isNullBodyStatus(xhr.status) ? null : blob,
1877
+ {
1878
+ status: xhr.status,
1879
+ statusText: xhr.statusText,
1880
+ headers
1881
+ }
1882
+ );
1883
+ const parseTarget = config.responseType === "stream" ? raw : raw.clone();
1884
+ const data = await parseResponse(
1885
+ parseTarget,
1886
+ config
1887
+ );
1888
+ const response = {
1889
+ data,
1890
+ status: xhr.status,
1891
+ statusText: xhr.statusText,
1892
+ headers,
1893
+ config,
1894
+ raw
1895
+ };
1896
+ const validateStatus = config.validateStatus ?? defaultValidateStatus2;
1897
+ if (!validateStatus(xhr.status)) {
1898
+ throw new RequestError(
1899
+ xhr.statusText || "Request failed",
1900
+ {
1901
+ code: "HTTP_ERROR",
1902
+ response
1903
+ }
1904
+ );
1905
+ }
1906
+ return response;
1907
+ } catch (error) {
1908
+ if (error instanceof RequestError) {
1909
+ throw error;
1910
+ }
1911
+ throw new RequestError(
1912
+ "Failed to process XMLHttpRequest response",
1913
+ {
1914
+ code: "PARSER_ERROR",
1915
+ config,
1916
+ cause: error
1917
+ }
1918
+ );
1919
+ }
1920
+ }
1921
+ function createProgressHandler(callback, abortWith) {
1922
+ if (!callback) {
1923
+ return null;
1924
+ }
1925
+ return (event) => {
1926
+ try {
1927
+ callback(
1928
+ createProgress(
1929
+ event.loaded,
1930
+ event.lengthComputable ? event.total : void 0
1931
+ )
1932
+ );
1933
+ } catch (error) {
1934
+ abortWith(error);
1935
+ }
1936
+ };
1937
+ }
1938
+ function createProgress(loaded, total) {
1939
+ if (total === void 0 || total === 0) {
1940
+ return {
1941
+ loaded,
1942
+ total
1943
+ };
1944
+ }
1945
+ return {
1946
+ loaded,
1947
+ total,
1948
+ progress: Math.min(loaded / total, 1)
1949
+ };
1950
+ }
1951
+ function parseHeaders(value) {
1952
+ const headers = new Headers();
1953
+ for (const line of value.split(/\r?\n/)) {
1954
+ const separator = line.indexOf(":");
1955
+ if (separator > 0) {
1956
+ headers.append(
1957
+ line.slice(0, separator).trim(),
1958
+ line.slice(separator + 1).trim()
1959
+ );
1960
+ }
1961
+ }
1962
+ return headers;
1963
+ }
1964
+ function createAbortError2(reason, config) {
1965
+ if (reason instanceof RequestError) {
1966
+ return new RequestError(reason.message, {
1967
+ code: reason.code,
1968
+ status: reason.status,
1969
+ data: reason.data,
1970
+ response: reason.response,
1971
+ config: reason.config ?? config,
1972
+ cause: reason
1973
+ });
1974
+ }
1975
+ return new RequestError("Request aborted", {
1976
+ code: "ABORT_ERROR",
1977
+ config,
1978
+ cause: reason
1979
+ });
1980
+ }
1981
+ function createConfigError(config, cause) {
1982
+ return new RequestError(
1983
+ "Failed to create XMLHttpRequest",
1984
+ {
1985
+ code: "CONFIG_ERROR",
1986
+ config,
1987
+ cause
1988
+ }
1989
+ );
1990
+ }
1991
+ function isNullBodyStatus(status) {
1992
+ return status === 204 || status === 205 || status === 304;
1993
+ }
1994
+ function defaultValidateStatus2(status) {
1995
+ return status >= 200 && status < 300;
1996
+ }
743
1997
 
744
1998
  // src/plugins/downloadPlugin.ts
745
- function downloadPlugin() {
1999
+ function downloadPlugin(options = {}) {
2000
+ const xhrContexts = /* @__PURE__ */ new WeakSet();
746
2001
  return {
747
2002
  name: "download",
748
2003
  install(context) {
749
2004
  context.interceptors.request.use((config) => {
750
- if (!config.download) {
2005
+ const download = resolveExtensionConfig(
2006
+ config,
2007
+ "download",
2008
+ config.download
2009
+ );
2010
+ if (!download) {
751
2011
  return config;
752
2012
  }
753
- const responseType = config.download.onProgress ? "stream" : config.responseType ?? "blob";
2013
+ const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
754
2014
  return {
755
2015
  ...config,
756
2016
  responseType
757
2017
  };
758
2018
  });
759
- context.interceptors.response.use(async (response) => {
760
- const download = response.config.download;
2019
+ context.hooks.onRequest(async (requestContext) => {
2020
+ if (requestContext.response) {
2021
+ return;
2022
+ }
2023
+ const download = resolveExtensionConfig(
2024
+ requestContext.config,
2025
+ "download",
2026
+ requestContext.config.download
2027
+ );
2028
+ const onProgress = download?.onProgress;
2029
+ if (!onProgress || !shouldUseXHR(options.transport)) {
2030
+ return;
2031
+ }
2032
+ if (typeof XMLHttpRequest === "undefined") {
2033
+ throw new RequestError(
2034
+ "XMLHttpRequest is unavailable for download progress",
2035
+ {
2036
+ code: "CONFIG_ERROR",
2037
+ config: requestContext.config
2038
+ }
2039
+ );
2040
+ }
2041
+ requestContext.response = await xhrRequest(
2042
+ requestContext.config,
2043
+ {
2044
+ onDownloadProgress: onProgress
2045
+ }
2046
+ );
2047
+ xhrContexts.add(requestContext);
2048
+ });
2049
+ context.hooks.onResponse(async (requestContext) => {
2050
+ if (xhrContexts.has(requestContext)) {
2051
+ return;
2052
+ }
2053
+ const response = requestContext.response;
2054
+ if (!response) {
2055
+ return;
2056
+ }
2057
+ const download = resolveExtensionConfig(
2058
+ response.config,
2059
+ "download",
2060
+ response.config.download
2061
+ );
761
2062
  const onProgress = download?.onProgress;
762
2063
  if (!download || !onProgress) {
763
- return response;
2064
+ return;
764
2065
  }
765
2066
  const stream = response.data;
766
- if (!(stream instanceof ReadableStream)) {
2067
+ if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) {
767
2068
  throw new RequestError(
768
2069
  "Download response stream is unavailable",
769
2070
  {
770
2071
  code: "PARSER_ERROR",
771
- status: response.status
2072
+ status: response.status,
2073
+ config: response.config
772
2074
  }
773
2075
  );
774
2076
  }
@@ -777,7 +2079,7 @@ function downloadPlugin() {
777
2079
  response,
778
2080
  onProgress
779
2081
  );
780
- return {
2082
+ requestContext.response = {
781
2083
  ...response,
782
2084
  data: blob
783
2085
  };
@@ -785,6 +2087,18 @@ function downloadPlugin() {
785
2087
  }
786
2088
  };
787
2089
  }
2090
+ function shouldUseXHR(transport = "auto") {
2091
+ if (transport === "xhr") {
2092
+ return true;
2093
+ }
2094
+ if (transport === "fetch") {
2095
+ return false;
2096
+ }
2097
+ return !supportsFetchResponseStream() && typeof XMLHttpRequest !== "undefined";
2098
+ }
2099
+ function supportsFetchResponseStream() {
2100
+ return typeof ReadableStream !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
2101
+ }
788
2102
  async function consumeDownloadStream(stream, response, onProgress) {
789
2103
  const reader = stream.getReader();
790
2104
  const chunks = [];
@@ -799,11 +2113,16 @@ async function consumeDownloadStream(stream, response, onProgress) {
799
2113
  break;
800
2114
  }
801
2115
  const chunk = result.value;
802
- const buffer = copyToArrayBuffer(chunk);
803
- chunks.push(buffer);
2116
+ chunks.push(toDownloadBuffer(chunk));
804
2117
  loaded += chunk.byteLength;
805
- onProgress(createProgress(loaded, total));
2118
+ onProgress(createProgress2(loaded, total));
806
2119
  }
2120
+ } catch (error) {
2121
+ try {
2122
+ await reader.cancel(error);
2123
+ } catch {
2124
+ }
2125
+ throw error;
807
2126
  } finally {
808
2127
  reader.releaseLock();
809
2128
  }
@@ -811,7 +2130,16 @@ async function consumeDownloadStream(stream, response, onProgress) {
811
2130
  type: response.headers.get("content-type") ?? ""
812
2131
  });
813
2132
  }
814
- function copyToArrayBuffer(chunk) {
2133
+ function toDownloadBuffer(chunk) {
2134
+ if (chunk.buffer instanceof ArrayBuffer) {
2135
+ if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) {
2136
+ return chunk.buffer;
2137
+ }
2138
+ return chunk.buffer.slice(
2139
+ chunk.byteOffset,
2140
+ chunk.byteOffset + chunk.byteLength
2141
+ );
2142
+ }
815
2143
  const copy = new Uint8Array(chunk.byteLength);
816
2144
  copy.set(chunk);
817
2145
  return copy.buffer;
@@ -826,7 +2154,7 @@ function parseContentLength(value) {
826
2154
  }
827
2155
  return total;
828
2156
  }
829
- function createProgress(loaded, total) {
2157
+ function createProgress2(loaded, total) {
830
2158
  if (total === void 0 || total === 0) {
831
2159
  return {
832
2160
  loaded,
@@ -846,42 +2174,125 @@ function loggerPlugin(defaultOptions = {}) {
846
2174
  name: "logger",
847
2175
  install(context) {
848
2176
  context.interceptors.request.use((config) => {
849
- const logger = config.logger ?? defaultOptions;
2177
+ const logger = resolveExtensionConfig(
2178
+ config,
2179
+ "logger",
2180
+ config.logger
2181
+ ) ?? defaultOptions;
850
2182
  if (logger.enabled === false) {
851
2183
  return config;
852
2184
  }
853
2185
  console.log("[Npora Request]", {
854
2186
  type: "request",
855
2187
  method: config.method ?? "GET",
856
- url: config.url
2188
+ url: redactURL(config.url)
857
2189
  });
858
2190
  return config;
859
2191
  });
860
2192
  context.interceptors.response.use((response) => {
861
- const logger = response.config.logger ?? defaultOptions;
2193
+ const logger = resolveExtensionConfig(
2194
+ response.config,
2195
+ "logger",
2196
+ response.config.logger
2197
+ ) ?? defaultOptions;
862
2198
  if (logger.enabled === false) {
863
2199
  return response;
864
2200
  }
865
2201
  console.log("[Npora Request]", {
866
2202
  type: "response",
867
2203
  method: response.config.method ?? "GET",
868
- url: response.config.url,
2204
+ url: redactURL(response.config.url),
869
2205
  status: response.status
870
2206
  });
871
2207
  return response;
872
2208
  });
873
2209
  context.interceptors.error.use((error) => {
874
- console.error("[Npora Request]", {
875
- type: "error",
876
- error
877
- });
2210
+ const config = error instanceof RequestError ? error.config : void 0;
2211
+ const logger = config ? resolveExtensionConfig(
2212
+ config,
2213
+ "logger",
2214
+ config.logger
2215
+ ) ?? defaultOptions : defaultOptions;
2216
+ if (logger.enabled === false) {
2217
+ return error;
2218
+ }
2219
+ console.error(
2220
+ "[Npora Request]",
2221
+ createErrorLog(error)
2222
+ );
878
2223
  return error;
879
2224
  });
880
2225
  }
881
2226
  };
882
2227
  }
2228
+ var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2229
+ "access_token",
2230
+ "api-key",
2231
+ "api_key",
2232
+ "apikey",
2233
+ "authorization",
2234
+ "client_secret",
2235
+ "password",
2236
+ "refresh_token",
2237
+ "secret",
2238
+ "sig",
2239
+ "signature",
2240
+ "token"
2241
+ ]);
2242
+ function redactURL(url) {
2243
+ const queryIndex = url.indexOf("?");
2244
+ if (queryIndex === -1) {
2245
+ return url;
2246
+ }
2247
+ const hashIndex = url.indexOf("#", queryIndex);
2248
+ const pathname = url.slice(0, queryIndex);
2249
+ const query = url.slice(
2250
+ queryIndex + 1,
2251
+ hashIndex === -1 ? void 0 : hashIndex
2252
+ );
2253
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
2254
+ const params = new URLSearchParams(query);
2255
+ for (const key of [...params.keys()]) {
2256
+ if (SENSITIVE_QUERY_KEYS.has(key.toLowerCase())) {
2257
+ params.set(key, "[REDACTED]");
2258
+ }
2259
+ }
2260
+ const redactedQuery = params.toString();
2261
+ return `${pathname}${redactedQuery ? `?${redactedQuery}` : ""}${hash}`;
2262
+ }
2263
+ function createErrorLog(error) {
2264
+ if (error instanceof RequestError) {
2265
+ return {
2266
+ type: "error",
2267
+ name: error.name,
2268
+ message: error.message,
2269
+ code: error.code,
2270
+ status: error.status,
2271
+ method: error.config?.method ?? "GET",
2272
+ url: error.config ? redactURL(error.config.url) : void 0
2273
+ };
2274
+ }
2275
+ if (error instanceof Error) {
2276
+ return {
2277
+ type: "error",
2278
+ name: error.name,
2279
+ message: error.message
2280
+ };
2281
+ }
2282
+ return {
2283
+ type: "error",
2284
+ message: String(error)
2285
+ };
2286
+ }
883
2287
 
884
2288
  // src/plugins/retryPlugin.ts
2289
+ var DEFAULT_RETRY_METHODS = [
2290
+ "GET",
2291
+ "HEAD",
2292
+ "OPTIONS",
2293
+ "PUT",
2294
+ "DELETE"
2295
+ ];
885
2296
  function retryPlugin(defaultOptions = {}) {
886
2297
  return {
887
2298
  name: "retry",
@@ -891,12 +2302,22 @@ function retryPlugin(defaultOptions = {}) {
891
2302
  return void 0;
892
2303
  }
893
2304
  const retryOptions = normalizeRetryOptions(
894
- requestContext.config.retry,
2305
+ resolveExtensionConfig(
2306
+ requestContext.config,
2307
+ "retry",
2308
+ requestContext.config.retry
2309
+ ),
895
2310
  defaultOptions
896
2311
  );
897
2312
  if (attempt >= retryOptions.retries) {
898
2313
  return void 0;
899
2314
  }
2315
+ if (!canRetryRequest(
2316
+ requestContext.config,
2317
+ retryOptions.methods
2318
+ )) {
2319
+ return void 0;
2320
+ }
900
2321
  const shouldRetry = await retryOptions.shouldRetry(
901
2322
  requestContext.error,
902
2323
  attempt
@@ -904,11 +2325,16 @@ function retryPlugin(defaultOptions = {}) {
904
2325
  if (!shouldRetry) {
905
2326
  return void 0;
906
2327
  }
2328
+ const configuredDelay = await retryOptions.delay(
2329
+ attempt,
2330
+ requestContext.error
2331
+ );
2332
+ const retryAfter = retryOptions.respectRetryAfter ? parseRetryAfter(requestContext.error) : void 0;
907
2333
  return {
908
2334
  retry: true,
909
- delay: await retryOptions.delay(
910
- attempt,
911
- requestContext.error
2335
+ delay: normalizeRetryDelay(
2336
+ retryAfter ?? configuredDelay,
2337
+ retryOptions.maxDelay
912
2338
  )
913
2339
  };
914
2340
  });
@@ -919,7 +2345,10 @@ function normalizeRetryOptions(retry, defaults = {}) {
919
2345
  if (typeof retry === "number") {
920
2346
  return {
921
2347
  retries: normalizeRetries(retry),
2348
+ methods: normalizeMethods(defaults.methods),
922
2349
  delay: normalizeDelay(defaults.delay),
2350
+ respectRetryAfter: defaults.respectRetryAfter ?? true,
2351
+ maxDelay: normalizeMaxDelay(defaults.maxDelay),
923
2352
  shouldRetry: defaults.shouldRetry ?? defaultShouldRetry
924
2353
  };
925
2354
  }
@@ -927,12 +2356,31 @@ function normalizeRetryOptions(retry, defaults = {}) {
927
2356
  retries: normalizeRetries(
928
2357
  retry?.retries ?? defaults.retries ?? 0
929
2358
  ),
2359
+ methods: normalizeMethods(
2360
+ retry?.methods ?? defaults.methods
2361
+ ),
930
2362
  delay: normalizeDelay(
931
2363
  retry?.delay ?? defaults.delay
932
2364
  ),
2365
+ respectRetryAfter: retry?.respectRetryAfter ?? defaults.respectRetryAfter ?? true,
2366
+ maxDelay: normalizeMaxDelay(
2367
+ retry?.maxDelay ?? defaults.maxDelay
2368
+ ),
933
2369
  shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry
934
2370
  };
935
2371
  }
2372
+ function normalizeMethods(methods) {
2373
+ return new Set(methods ?? DEFAULT_RETRY_METHODS);
2374
+ }
2375
+ function normalizeMaxDelay(maxDelay) {
2376
+ if (maxDelay === void 0) {
2377
+ return 6e4;
2378
+ }
2379
+ if (!Number.isFinite(maxDelay)) {
2380
+ return maxDelay > 0 ? Number.MAX_SAFE_INTEGER : 0;
2381
+ }
2382
+ return Math.max(0, maxDelay);
2383
+ }
936
2384
  function normalizeRetries(retries) {
937
2385
  if (!Number.isFinite(retries)) {
938
2386
  return 0;
@@ -949,6 +2397,40 @@ function normalizeDelay(delay) {
949
2397
  function defaultRetryDelay(attempt) {
950
2398
  return Math.min(100 * 2 ** attempt, 1e3);
951
2399
  }
2400
+ function normalizeRetryDelay(delay, maxDelay) {
2401
+ if (!Number.isFinite(delay)) {
2402
+ return delay > 0 ? maxDelay : 0;
2403
+ }
2404
+ return Math.min(Math.max(0, delay), maxDelay);
2405
+ }
2406
+ function canRetryRequest(config, methods) {
2407
+ const method = config.method ?? "GET";
2408
+ if (!methods.has(method)) {
2409
+ return false;
2410
+ }
2411
+ return !isReadableStream(config.body);
2412
+ }
2413
+ function isReadableStream(value) {
2414
+ return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
2415
+ }
2416
+ function parseRetryAfter(error) {
2417
+ if (!(error instanceof RequestError)) {
2418
+ return void 0;
2419
+ }
2420
+ const value = error.response?.headers.get("retry-after");
2421
+ if (!value) {
2422
+ return void 0;
2423
+ }
2424
+ const seconds = Number(value);
2425
+ if (Number.isFinite(seconds)) {
2426
+ return Math.max(0, seconds * 1e3);
2427
+ }
2428
+ const date = Date.parse(value);
2429
+ if (Number.isNaN(date)) {
2430
+ return void 0;
2431
+ }
2432
+ return Math.max(0, date - Date.now());
2433
+ }
952
2434
  function defaultShouldRetry(error) {
953
2435
  if (!(error instanceof RequestError)) {
954
2436
  return false;
@@ -968,16 +2450,48 @@ function uploadPlugin() {
968
2450
  name: "upload",
969
2451
  install(context) {
970
2452
  context.interceptors.request.use((config) => {
971
- if (!config.upload) {
2453
+ const upload = resolveExtensionConfig(
2454
+ config,
2455
+ "upload",
2456
+ config.upload
2457
+ );
2458
+ if (!upload) {
972
2459
  return config;
973
2460
  }
974
2461
  return {
975
2462
  ...config,
976
2463
  method: config.method ?? "POST",
977
- formData: config.upload.data,
978
- upload: void 0
2464
+ formData: upload.data
979
2465
  };
980
2466
  });
2467
+ context.hooks.onRequest(async (requestContext) => {
2468
+ if (requestContext.response) {
2469
+ return;
2470
+ }
2471
+ const upload = resolveExtensionConfig(
2472
+ requestContext.config,
2473
+ "upload",
2474
+ requestContext.config.upload
2475
+ );
2476
+ if (!upload?.onProgress) {
2477
+ return;
2478
+ }
2479
+ if (typeof XMLHttpRequest === "undefined") {
2480
+ throw new RequestError(
2481
+ "XMLHttpRequest is unavailable for upload progress",
2482
+ {
2483
+ code: "CONFIG_ERROR",
2484
+ config: requestContext.config
2485
+ }
2486
+ );
2487
+ }
2488
+ requestContext.response = await xhrRequest(
2489
+ requestContext.config,
2490
+ {
2491
+ onUploadProgress: upload.onProgress
2492
+ }
2493
+ );
2494
+ });
981
2495
  }
982
2496
  };
983
2497
  }
@@ -987,6 +2501,7 @@ function uploadPlugin() {
987
2501
  FetchAdapter,
988
2502
  InterceptorManager,
989
2503
  MockAdapter,
2504
+ PluginError,
990
2505
  RequestError,
991
2506
  authPlugin,
992
2507
  cachePlugin,