@npora/request 1.11.1 → 1.13.0

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/README.md CHANGED
@@ -182,6 +182,10 @@ The body options `body`, `json`, `form`, and `formData` are mutually exclusive.
182
182
  `GET` and `HEAD` requests cannot contain a body. Invalid configuration throws a
183
183
  `RequestError` before the adapter sends a request.
184
184
 
185
+ See the complete [configuration reference](https://github.com/npora/request/blob/main/docs/configuration.md)
186
+ for every option, default, merge rule, plugin extension, environment limit,
187
+ and transfer-progress behavior.
188
+
185
189
  Create isolated clients with inherited defaults:
186
190
 
187
191
  ```ts
@@ -420,6 +424,7 @@ allowlist, and size budgets.
420
424
 
421
425
  ## Documentation
422
426
 
427
+ - [Configuration reference](https://github.com/npora/request/blob/main/docs/configuration.md)
423
428
  - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
424
429
  - [Architecture](https://github.com/npora/request/blob/main/docs/architecture.md)
425
430
  - [Migration from 0.x](https://github.com/npora/request/blob/main/docs/migration.md)
package/dist/index.cjs CHANGED
@@ -1230,7 +1230,8 @@ var Pipeline = class {
1230
1230
  while (true) try {
1231
1231
  const headers = validatedHeaders;
1232
1232
  validatedHeaders = void 0;
1233
- context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(context.config, headers, preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active) : await this.adapter.request(context.config);
1233
+ if (this.hooks.hasTransportHooks) await this.hooks.runTransport(context);
1234
+ if (!context.response) context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(context.config, headers, preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active) : await this.adapter.request(context.config);
1234
1235
  return await this.processResponse(context);
1235
1236
  } catch (error) {
1236
1237
  if (!await this.notifyError(context, error)) return this.fail(context, context.error, false);
@@ -1390,6 +1391,7 @@ function normalizePriority$1(priority) {
1390
1391
  var PluginHooks = class {
1391
1392
  constructor() {
1392
1393
  this.requestHooks = new HookRegistry();
1394
+ this.transportHooks = new HookRegistry();
1393
1395
  this.responseHooks = new HookRegistry();
1394
1396
  this.errorHooks = new HookRegistry();
1395
1397
  this.settledHooks = new HookRegistry();
@@ -1401,6 +1403,9 @@ var PluginHooks = class {
1401
1403
  get hasResponseHooks() {
1402
1404
  return this.responseHooks.active;
1403
1405
  }
1406
+ get hasTransportHooks() {
1407
+ return this.transportHooks.active;
1408
+ }
1404
1409
  get hasErrorHooks() {
1405
1410
  return this.errorHooks.active;
1406
1411
  }
@@ -1416,6 +1421,9 @@ var PluginHooks = class {
1416
1421
  onResponse(hook, options = {}) {
1417
1422
  return this.responseHooks.register(hook, options);
1418
1423
  }
1424
+ onTransport(hook, options = {}) {
1425
+ return this.transportHooks.register(hook, options);
1426
+ }
1419
1427
  onError(hook, options = {}) {
1420
1428
  return this.errorHooks.register(hook, options);
1421
1429
  }
@@ -1431,6 +1439,12 @@ var PluginHooks = class {
1431
1439
  async runResponse(context) {
1432
1440
  for (const hook of this.responseHooks.values()) await hook(context);
1433
1441
  }
1442
+ async runTransport(context) {
1443
+ for (const hook of this.transportHooks.values()) {
1444
+ await hook(context);
1445
+ if (context.response) return;
1446
+ }
1447
+ }
1434
1448
  async runError(context) {
1435
1449
  for (const hook of this.errorHooks.values()) await hook(context);
1436
1450
  }
@@ -1546,6 +1560,9 @@ function createScopedHooks(hooks, pluginPriority, cleanups) {
1546
1560
  onRequest(hook, options) {
1547
1561
  return trackHook(hooks.onRequest(hook, withPriority(options, pluginPriority)), cleanups);
1548
1562
  },
1563
+ onTransport(hook, options) {
1564
+ return trackHook(hooks.onTransport(hook, withPriority(options, pluginPriority)), cleanups);
1565
+ },
1549
1566
  onResponse(hook, options) {
1550
1567
  return trackHook(hooks.onResponse(hook, withPriority(options, pluginPriority)), cleanups);
1551
1568
  },
@@ -2606,6 +2623,30 @@ function createRemovedError(config) {
2606
2623
  });
2607
2624
  }
2608
2625
  //#endregion
2626
+ //#region src/plugins/transferProgress.ts
2627
+ const MIN_RATE_SAMPLE_MILLISECONDS = 250;
2628
+ function createTransferProgressTracker(now = Date.now) {
2629
+ const startedAt = now();
2630
+ let previousLoaded = 0;
2631
+ return (loaded, total) => {
2632
+ const bytes = Math.max(loaded - previousLoaded, 0);
2633
+ const elapsed = Math.max(now() - startedAt, 0) / 1e3;
2634
+ const rate = elapsed >= MIN_RATE_SAMPLE_MILLISECONDS / 1e3 && loaded > 0 ? loaded / elapsed : void 0;
2635
+ const progress = total === void 0 || total === 0 ? void 0 : Math.min(loaded / total, 1);
2636
+ const estimated = rate && total !== void 0 ? Math.max(total - loaded, 0) / rate : void 0;
2637
+ previousLoaded = loaded;
2638
+ const snapshot = {
2639
+ loaded,
2640
+ total,
2641
+ bytes
2642
+ };
2643
+ if (progress !== void 0) snapshot.progress = progress;
2644
+ if (rate !== void 0) snapshot.rate = rate;
2645
+ if (estimated !== void 0) snapshot.estimated = estimated;
2646
+ return snapshot;
2647
+ };
2648
+ }
2649
+ //#endregion
2609
2650
  //#region src/plugins/xhrTransport.ts
2610
2651
  function xhrRequest(config, options = {}) {
2611
2652
  let request;
@@ -2725,6 +2766,7 @@ async function processResponse(xhr, config) {
2725
2766
  }
2726
2767
  function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2727
2768
  if (!callback && !Number.isFinite(maxResponseSize)) return null;
2769
+ const trackProgress = callback ? createTransferProgressTracker() : void 0;
2728
2770
  return (event) => {
2729
2771
  if (Number.isFinite(maxResponseSize) && event.loaded > (maxResponseSize ?? Number.POSITIVE_INFINITY)) {
2730
2772
  abortWith(new RequestError(`Response body exceeds maxResponseSize ${maxResponseSize}`, {
@@ -2733,25 +2775,14 @@ function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2733
2775
  }));
2734
2776
  return;
2735
2777
  }
2736
- if (!callback) return;
2778
+ if (!callback || !trackProgress) return;
2737
2779
  try {
2738
- callback(createProgress$1(event.loaded, event.lengthComputable ? event.total : void 0));
2780
+ callback(trackProgress(event.loaded, event.lengthComputable ? event.total : void 0));
2739
2781
  } catch (error) {
2740
2782
  abortWith(error);
2741
2783
  }
2742
2784
  };
2743
2785
  }
2744
- function createProgress$1(loaded, total) {
2745
- if (total === void 0 || total === 0) return {
2746
- loaded,
2747
- total
2748
- };
2749
- return {
2750
- loaded,
2751
- total,
2752
- progress: Math.min(loaded / total, 1)
2753
- };
2754
- }
2755
2786
  function parseHeaders(value) {
2756
2787
  const headers = new Headers();
2757
2788
  for (const line of value.split(/\r?\n/)) {
@@ -2801,7 +2832,7 @@ function downloadPlugin(options = {}) {
2801
2832
  responseType
2802
2833
  };
2803
2834
  });
2804
- context.hooks.onRequest(async (requestContext) => {
2835
+ context.hooks.onTransport(async (requestContext) => {
2805
2836
  if (requestContext.response) return;
2806
2837
  const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2807
2838
  if (!onProgress || !shouldUseXHR(options.transport)) return;
@@ -2846,7 +2877,9 @@ async function consumeDownloadStream(stream, response, onProgress) {
2846
2877
  const reader = stream.getReader();
2847
2878
  const chunks = [];
2848
2879
  const total = parseContentLength(response.headers.get("content-length"));
2880
+ const trackProgress = createTransferProgressTracker();
2849
2881
  let loaded = 0;
2882
+ let reported = false;
2850
2883
  try {
2851
2884
  while (true) {
2852
2885
  const result = await reader.read();
@@ -2854,8 +2887,10 @@ async function consumeDownloadStream(stream, response, onProgress) {
2854
2887
  const chunk = result.value;
2855
2888
  chunks.push(toDownloadBuffer(chunk));
2856
2889
  loaded += chunk.byteLength;
2857
- onProgress(createProgress(loaded, total));
2890
+ reported = true;
2891
+ onProgress(trackProgress(loaded, total));
2858
2892
  }
2893
+ if (!reported) onProgress(trackProgress(0, total));
2859
2894
  } catch (error) {
2860
2895
  try {
2861
2896
  await reader.cancel(error);
@@ -2881,17 +2916,6 @@ function parseContentLength(value) {
2881
2916
  if (!Number.isFinite(total) || total < 0) return;
2882
2917
  return total;
2883
2918
  }
2884
- function createProgress(loaded, total) {
2885
- if (total === void 0 || total === 0) return {
2886
- loaded,
2887
- total
2888
- };
2889
- return {
2890
- loaded,
2891
- total,
2892
- progress: Math.min(loaded / total, 1)
2893
- };
2894
- }
2895
2919
  //#endregion
2896
2920
  //#region src/plugins/loggerPlugin.ts
2897
2921
  function loggerPlugin(defaultOptions = {}) {
@@ -3201,7 +3225,7 @@ function uploadPlugin() {
3201
3225
  formData: upload.data
3202
3226
  };
3203
3227
  });
3204
- context.hooks.onRequest(async (requestContext) => {
3228
+ context.hooks.onTransport(async (requestContext) => {
3205
3229
  if (requestContext.response) return;
3206
3230
  const upload = resolveExtensionConfig(requestContext.config, "upload");
3207
3231
  if (!upload?.onProgress) return;
package/dist/index.d.cts CHANGED
@@ -222,23 +222,36 @@ interface RequestLogger {
222
222
  error(message: string, entry: ErrorLogEntry): void | Promise<void>;
223
223
  }
224
224
  type UploadData = FormData | Record<string, unknown>;
225
- /**
226
- * Upload progress information.
227
- */
228
- interface UploadProgress {
225
+ interface TransferProgress {
229
226
  /**
230
- * Number of bytes sent.
227
+ * Cumulative number of bytes transferred.
231
228
  */
232
229
  loaded: number;
233
230
  /**
234
- * Total request size when the browser provides it.
231
+ * Total transfer size when the runtime provides it.
235
232
  */
236
233
  total?: number;
237
234
  /**
238
235
  * Progress ratio between 0 and 1 when total is available.
239
236
  */
240
237
  progress?: number;
238
+ /**
239
+ * Bytes transferred since the previous progress event.
240
+ */
241
+ bytes?: number;
242
+ /**
243
+ * Average transfer rate in bytes per second when measurable.
244
+ */
245
+ rate?: number;
246
+ /**
247
+ * Estimated remaining seconds when total and rate are available.
248
+ */
249
+ estimated?: number;
241
250
  }
251
+ /**
252
+ * Upload progress information.
253
+ */
254
+ interface UploadProgress extends TransferProgress {}
242
255
  interface UploadOptions {
243
256
  data: UploadData;
244
257
  /**
@@ -249,21 +262,13 @@ interface UploadOptions {
249
262
  /**
250
263
  * Download progress information.
251
264
  */
252
- interface DownloadProgress {
253
- /**
254
- * Number of bytes received.
255
- */
256
- loaded: number;
257
- /**
258
- * Total response size when Content-Length is available.
259
- */
260
- total?: number;
265
+ interface DownloadProgress extends TransferProgress {}
266
+ interface DownloadOptions {
261
267
  /**
262
- * Progress ratio between 0 and 1 when total is available.
268
+ * Reserved legacy field. It does not save or rename the returned Blob.
269
+ *
270
+ * @deprecated This field currently has no effect.
263
271
  */
264
- progress?: number;
265
- }
266
- interface DownloadOptions {
267
272
  filename?: string;
268
273
  /**
269
274
  * Called while the response stream is being consumed.
@@ -550,6 +555,14 @@ interface PluginInterceptorManager<T> {
550
555
  }
551
556
  interface PluginHookManager {
552
557
  onRequest(hook: RequestHook, options?: HookOptions): HookDisposer;
558
+ /**
559
+ * Provide an alternative transport for the current attempt.
560
+ *
561
+ * Transport hooks run inside the retry loop. A hook that handles the
562
+ * request assigns `context.response`; later transport hooks and the client
563
+ * adapter are then skipped for that attempt.
564
+ */
565
+ onTransport(hook: RequestHook, options?: HookOptions): HookDisposer;
553
566
  onResponse(hook: RequestHook, options?: HookOptions): HookDisposer;
554
567
  onError(hook: RequestHook, options?: HookOptions): HookDisposer;
555
568
  /**
@@ -994,4 +1007,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
994
1007
  //#region src/plugins/uploadPlugin.d.ts
995
1008
  declare function uploadPlugin(): Plugin;
996
1009
  //#endregion
997
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
1010
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -222,23 +222,36 @@ interface RequestLogger {
222
222
  error(message: string, entry: ErrorLogEntry): void | Promise<void>;
223
223
  }
224
224
  type UploadData = FormData | Record<string, unknown>;
225
- /**
226
- * Upload progress information.
227
- */
228
- interface UploadProgress {
225
+ interface TransferProgress {
229
226
  /**
230
- * Number of bytes sent.
227
+ * Cumulative number of bytes transferred.
231
228
  */
232
229
  loaded: number;
233
230
  /**
234
- * Total request size when the browser provides it.
231
+ * Total transfer size when the runtime provides it.
235
232
  */
236
233
  total?: number;
237
234
  /**
238
235
  * Progress ratio between 0 and 1 when total is available.
239
236
  */
240
237
  progress?: number;
238
+ /**
239
+ * Bytes transferred since the previous progress event.
240
+ */
241
+ bytes?: number;
242
+ /**
243
+ * Average transfer rate in bytes per second when measurable.
244
+ */
245
+ rate?: number;
246
+ /**
247
+ * Estimated remaining seconds when total and rate are available.
248
+ */
249
+ estimated?: number;
241
250
  }
251
+ /**
252
+ * Upload progress information.
253
+ */
254
+ interface UploadProgress extends TransferProgress {}
242
255
  interface UploadOptions {
243
256
  data: UploadData;
244
257
  /**
@@ -249,21 +262,13 @@ interface UploadOptions {
249
262
  /**
250
263
  * Download progress information.
251
264
  */
252
- interface DownloadProgress {
253
- /**
254
- * Number of bytes received.
255
- */
256
- loaded: number;
257
- /**
258
- * Total response size when Content-Length is available.
259
- */
260
- total?: number;
265
+ interface DownloadProgress extends TransferProgress {}
266
+ interface DownloadOptions {
261
267
  /**
262
- * Progress ratio between 0 and 1 when total is available.
268
+ * Reserved legacy field. It does not save or rename the returned Blob.
269
+ *
270
+ * @deprecated This field currently has no effect.
263
271
  */
264
- progress?: number;
265
- }
266
- interface DownloadOptions {
267
272
  filename?: string;
268
273
  /**
269
274
  * Called while the response stream is being consumed.
@@ -550,6 +555,14 @@ interface PluginInterceptorManager<T> {
550
555
  }
551
556
  interface PluginHookManager {
552
557
  onRequest(hook: RequestHook, options?: HookOptions): HookDisposer;
558
+ /**
559
+ * Provide an alternative transport for the current attempt.
560
+ *
561
+ * Transport hooks run inside the retry loop. A hook that handles the
562
+ * request assigns `context.response`; later transport hooks and the client
563
+ * adapter are then skipped for that attempt.
564
+ */
565
+ onTransport(hook: RequestHook, options?: HookOptions): HookDisposer;
553
566
  onResponse(hook: RequestHook, options?: HookOptions): HookDisposer;
554
567
  onError(hook: RequestHook, options?: HookOptions): HookDisposer;
555
568
  /**
@@ -994,4 +1007,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
994
1007
  //#region src/plugins/uploadPlugin.d.ts
995
1008
  declare function uploadPlugin(): Plugin;
996
1009
  //#endregion
997
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
1010
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -1229,7 +1229,8 @@ var Pipeline = class {
1229
1229
  while (true) try {
1230
1230
  const headers = validatedHeaders;
1231
1231
  validatedHeaders = void 0;
1232
- context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(context.config, headers, preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active) : await this.adapter.request(context.config);
1232
+ if (this.hooks.hasTransportHooks) await this.hooks.runTransport(context);
1233
+ if (!context.response) context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(context.config, headers, preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active) : await this.adapter.request(context.config);
1233
1234
  return await this.processResponse(context);
1234
1235
  } catch (error) {
1235
1236
  if (!await this.notifyError(context, error)) return this.fail(context, context.error, false);
@@ -1389,6 +1390,7 @@ function normalizePriority$1(priority) {
1389
1390
  var PluginHooks = class {
1390
1391
  constructor() {
1391
1392
  this.requestHooks = new HookRegistry();
1393
+ this.transportHooks = new HookRegistry();
1392
1394
  this.responseHooks = new HookRegistry();
1393
1395
  this.errorHooks = new HookRegistry();
1394
1396
  this.settledHooks = new HookRegistry();
@@ -1400,6 +1402,9 @@ var PluginHooks = class {
1400
1402
  get hasResponseHooks() {
1401
1403
  return this.responseHooks.active;
1402
1404
  }
1405
+ get hasTransportHooks() {
1406
+ return this.transportHooks.active;
1407
+ }
1403
1408
  get hasErrorHooks() {
1404
1409
  return this.errorHooks.active;
1405
1410
  }
@@ -1415,6 +1420,9 @@ var PluginHooks = class {
1415
1420
  onResponse(hook, options = {}) {
1416
1421
  return this.responseHooks.register(hook, options);
1417
1422
  }
1423
+ onTransport(hook, options = {}) {
1424
+ return this.transportHooks.register(hook, options);
1425
+ }
1418
1426
  onError(hook, options = {}) {
1419
1427
  return this.errorHooks.register(hook, options);
1420
1428
  }
@@ -1430,6 +1438,12 @@ var PluginHooks = class {
1430
1438
  async runResponse(context) {
1431
1439
  for (const hook of this.responseHooks.values()) await hook(context);
1432
1440
  }
1441
+ async runTransport(context) {
1442
+ for (const hook of this.transportHooks.values()) {
1443
+ await hook(context);
1444
+ if (context.response) return;
1445
+ }
1446
+ }
1433
1447
  async runError(context) {
1434
1448
  for (const hook of this.errorHooks.values()) await hook(context);
1435
1449
  }
@@ -1545,6 +1559,9 @@ function createScopedHooks(hooks, pluginPriority, cleanups) {
1545
1559
  onRequest(hook, options) {
1546
1560
  return trackHook(hooks.onRequest(hook, withPriority(options, pluginPriority)), cleanups);
1547
1561
  },
1562
+ onTransport(hook, options) {
1563
+ return trackHook(hooks.onTransport(hook, withPriority(options, pluginPriority)), cleanups);
1564
+ },
1548
1565
  onResponse(hook, options) {
1549
1566
  return trackHook(hooks.onResponse(hook, withPriority(options, pluginPriority)), cleanups);
1550
1567
  },
@@ -2605,6 +2622,30 @@ function createRemovedError(config) {
2605
2622
  });
2606
2623
  }
2607
2624
  //#endregion
2625
+ //#region src/plugins/transferProgress.ts
2626
+ const MIN_RATE_SAMPLE_MILLISECONDS = 250;
2627
+ function createTransferProgressTracker(now = Date.now) {
2628
+ const startedAt = now();
2629
+ let previousLoaded = 0;
2630
+ return (loaded, total) => {
2631
+ const bytes = Math.max(loaded - previousLoaded, 0);
2632
+ const elapsed = Math.max(now() - startedAt, 0) / 1e3;
2633
+ const rate = elapsed >= MIN_RATE_SAMPLE_MILLISECONDS / 1e3 && loaded > 0 ? loaded / elapsed : void 0;
2634
+ const progress = total === void 0 || total === 0 ? void 0 : Math.min(loaded / total, 1);
2635
+ const estimated = rate && total !== void 0 ? Math.max(total - loaded, 0) / rate : void 0;
2636
+ previousLoaded = loaded;
2637
+ const snapshot = {
2638
+ loaded,
2639
+ total,
2640
+ bytes
2641
+ };
2642
+ if (progress !== void 0) snapshot.progress = progress;
2643
+ if (rate !== void 0) snapshot.rate = rate;
2644
+ if (estimated !== void 0) snapshot.estimated = estimated;
2645
+ return snapshot;
2646
+ };
2647
+ }
2648
+ //#endregion
2608
2649
  //#region src/plugins/xhrTransport.ts
2609
2650
  function xhrRequest(config, options = {}) {
2610
2651
  let request;
@@ -2724,6 +2765,7 @@ async function processResponse(xhr, config) {
2724
2765
  }
2725
2766
  function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2726
2767
  if (!callback && !Number.isFinite(maxResponseSize)) return null;
2768
+ const trackProgress = callback ? createTransferProgressTracker() : void 0;
2727
2769
  return (event) => {
2728
2770
  if (Number.isFinite(maxResponseSize) && event.loaded > (maxResponseSize ?? Number.POSITIVE_INFINITY)) {
2729
2771
  abortWith(new RequestError(`Response body exceeds maxResponseSize ${maxResponseSize}`, {
@@ -2732,25 +2774,14 @@ function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2732
2774
  }));
2733
2775
  return;
2734
2776
  }
2735
- if (!callback) return;
2777
+ if (!callback || !trackProgress) return;
2736
2778
  try {
2737
- callback(createProgress$1(event.loaded, event.lengthComputable ? event.total : void 0));
2779
+ callback(trackProgress(event.loaded, event.lengthComputable ? event.total : void 0));
2738
2780
  } catch (error) {
2739
2781
  abortWith(error);
2740
2782
  }
2741
2783
  };
2742
2784
  }
2743
- function createProgress$1(loaded, total) {
2744
- if (total === void 0 || total === 0) return {
2745
- loaded,
2746
- total
2747
- };
2748
- return {
2749
- loaded,
2750
- total,
2751
- progress: Math.min(loaded / total, 1)
2752
- };
2753
- }
2754
2785
  function parseHeaders(value) {
2755
2786
  const headers = new Headers();
2756
2787
  for (const line of value.split(/\r?\n/)) {
@@ -2800,7 +2831,7 @@ function downloadPlugin(options = {}) {
2800
2831
  responseType
2801
2832
  };
2802
2833
  });
2803
- context.hooks.onRequest(async (requestContext) => {
2834
+ context.hooks.onTransport(async (requestContext) => {
2804
2835
  if (requestContext.response) return;
2805
2836
  const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2806
2837
  if (!onProgress || !shouldUseXHR(options.transport)) return;
@@ -2845,7 +2876,9 @@ async function consumeDownloadStream(stream, response, onProgress) {
2845
2876
  const reader = stream.getReader();
2846
2877
  const chunks = [];
2847
2878
  const total = parseContentLength(response.headers.get("content-length"));
2879
+ const trackProgress = createTransferProgressTracker();
2848
2880
  let loaded = 0;
2881
+ let reported = false;
2849
2882
  try {
2850
2883
  while (true) {
2851
2884
  const result = await reader.read();
@@ -2853,8 +2886,10 @@ async function consumeDownloadStream(stream, response, onProgress) {
2853
2886
  const chunk = result.value;
2854
2887
  chunks.push(toDownloadBuffer(chunk));
2855
2888
  loaded += chunk.byteLength;
2856
- onProgress(createProgress(loaded, total));
2889
+ reported = true;
2890
+ onProgress(trackProgress(loaded, total));
2857
2891
  }
2892
+ if (!reported) onProgress(trackProgress(0, total));
2858
2893
  } catch (error) {
2859
2894
  try {
2860
2895
  await reader.cancel(error);
@@ -2880,17 +2915,6 @@ function parseContentLength(value) {
2880
2915
  if (!Number.isFinite(total) || total < 0) return;
2881
2916
  return total;
2882
2917
  }
2883
- function createProgress(loaded, total) {
2884
- if (total === void 0 || total === 0) return {
2885
- loaded,
2886
- total
2887
- };
2888
- return {
2889
- loaded,
2890
- total,
2891
- progress: Math.min(loaded / total, 1)
2892
- };
2893
- }
2894
2918
  //#endregion
2895
2919
  //#region src/plugins/loggerPlugin.ts
2896
2920
  function loggerPlugin(defaultOptions = {}) {
@@ -3200,7 +3224,7 @@ function uploadPlugin() {
3200
3224
  formData: upload.data
3201
3225
  };
3202
3226
  });
3203
- context.hooks.onRequest(async (requestContext) => {
3227
+ context.hooks.onTransport(async (requestContext) => {
3204
3228
  if (requestContext.response) return;
3205
3229
  const upload = resolveExtensionConfig(requestContext.config, "upload");
3206
3230
  if (!upload?.onProgress) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.11.1",
3
+ "version": "1.13.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",