@npora/request 1.15.1 → 1.17.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.
Files changed (142) hide show
  1. package/README.md +154 -6
  2. package/dist/{MockAdapter-H50LoFDu.d.ts → MockAdapter-5CFrxv9q.d.ts} +2 -2
  3. package/dist/{MockAdapter-ChWzzSnH.d.cts → MockAdapter-mR3CWESj.d.cts} +2 -2
  4. package/dist/{Plugin-0Eh51_et.d.ts → Plugin-C9ZQzyF6.d.ts} +7 -1
  5. package/dist/{Plugin-YysllE6z.d.cts → Plugin-Cxb-obdZ.d.cts} +7 -1
  6. package/dist/RequestError-B0HIY1zK.js +1 -0
  7. package/dist/RequestError-DrCr_lwO.cjs +1 -0
  8. package/dist/SchemaValidationError-Bls3Uxwj.d.cts +215 -0
  9. package/dist/SchemaValidationError-DRSiM7h7.d.ts +215 -0
  10. package/dist/{adapter-BeVVCcNG.d.cts → adapter-Bshqh0DY.d.cts} +1 -1
  11. package/dist/{adapter-ODzpt_dM.d.ts → adapter-YnK7Xzw4.d.ts} +1 -1
  12. package/dist/{authPlugin-B_YpkyC8.d.cts → authPlugin-BXi6WjtM.d.cts} +1 -1
  13. package/dist/{authPlugin-6E6_0dAO.d.ts → authPlugin-DdzlLQVo.d.ts} +1 -1
  14. package/dist/{cachePlugin-CvH26DBo.d.ts → cachePlugin-BZ0lLFOx.d.ts} +2 -2
  15. package/dist/cachePlugin-Bg1Q5N82.cjs +1 -0
  16. package/dist/{cachePlugin-B9Hvsprg.d.cts → cachePlugin-Bk7V57oZ.d.cts} +2 -2
  17. package/dist/cachePlugin-Blw0Mh9F.js +1 -0
  18. package/dist/{circuitBreakerPlugin-B45xghq9.d.cts → circuitBreakerPlugin-BG2PlHSo.d.cts} +2 -2
  19. package/dist/{circuitBreakerPlugin-DsH6YCNe.d.ts → circuitBreakerPlugin-CX7s4iAe.d.ts} +2 -2
  20. package/dist/{concurrencyPlugin-CuJMua41.d.cts → concurrencyPlugin-DeDnm7ND.d.cts} +2 -2
  21. package/dist/{concurrencyPlugin-dwGNFYrM.d.ts → concurrencyPlugin-HvGuOA2p.d.ts} +2 -2
  22. package/dist/core.cjs +1 -1
  23. package/dist/core.d.cts +5 -5
  24. package/dist/core.d.ts +5 -5
  25. package/dist/core.js +1 -1
  26. package/dist/createAbortError-CP4TUmou.js +1 -0
  27. package/dist/createAbortError-DYRmuiQS.cjs +1 -0
  28. package/dist/createClient-BXfcmvs2.js +1 -0
  29. package/dist/createClient-qfwP9cgC.cjs +1 -0
  30. package/dist/{downloadPlugin-CEXXJiDo.d.cts → downloadPlugin-BlA-z0Pj.d.cts} +1 -1
  31. package/dist/{downloadPlugin-s8VS8t9r.d.ts → downloadPlugin-BrXcygGo.d.ts} +1 -1
  32. package/dist/errorResponseTimeout-CUZ0Bx-G.cjs +1 -0
  33. package/dist/errorResponseTimeout-CuRn9Icm.js +1 -0
  34. package/dist/index.cjs +1 -1
  35. package/dist/index.d.cts +17 -14
  36. package/dist/index.d.ts +17 -14
  37. package/dist/index.js +1 -1
  38. package/dist/isBinaryBody-B0414zDU.cjs +1 -0
  39. package/dist/isBinaryBody-i4r46MoJ.js +1 -0
  40. package/dist/isReadableStream-0eF9O4Xl.cjs +1 -0
  41. package/dist/isReadableStream-O-PmslRY.js +1 -0
  42. package/dist/loggerPlugin-CBbwGZme.d.ts +6 -0
  43. package/dist/loggerPlugin-CZpdXtBt.d.cts +6 -0
  44. package/dist/openTelemetryMetricsPlugin-DIo7cT09.d.ts +42 -0
  45. package/dist/openTelemetryMetricsPlugin-VZ1ojbXJ.d.cts +42 -0
  46. package/dist/openTelemetryPlugin-CiRMppHI.d.ts +57 -0
  47. package/dist/openTelemetryPlugin-FAngP8jc.d.cts +57 -0
  48. package/dist/plugins/auth.cjs +1 -1
  49. package/dist/plugins/auth.d.cts +1 -1
  50. package/dist/plugins/auth.d.ts +1 -1
  51. package/dist/plugins/auth.js +1 -1
  52. package/dist/plugins/cache.cjs +1 -1
  53. package/dist/plugins/cache.d.cts +1 -1
  54. package/dist/plugins/cache.d.ts +1 -1
  55. package/dist/plugins/cache.js +1 -1
  56. package/dist/plugins/circuit-breaker.cjs +1 -1
  57. package/dist/plugins/circuit-breaker.d.cts +1 -1
  58. package/dist/plugins/circuit-breaker.d.ts +1 -1
  59. package/dist/plugins/circuit-breaker.js +1 -1
  60. package/dist/plugins/concurrency.cjs +1 -1
  61. package/dist/plugins/concurrency.d.cts +1 -1
  62. package/dist/plugins/concurrency.d.ts +1 -1
  63. package/dist/plugins/concurrency.js +1 -1
  64. package/dist/plugins/download.cjs +1 -1
  65. package/dist/plugins/download.d.cts +1 -1
  66. package/dist/plugins/download.d.ts +1 -1
  67. package/dist/plugins/download.js +1 -1
  68. package/dist/plugins/logger.cjs +1 -1
  69. package/dist/plugins/logger.d.cts +1 -1
  70. package/dist/plugins/logger.d.ts +1 -1
  71. package/dist/plugins/logger.js +1 -1
  72. package/dist/plugins/opentelemetry-metrics.cjs +1 -0
  73. package/dist/plugins/opentelemetry-metrics.d.cts +2 -0
  74. package/dist/plugins/opentelemetry-metrics.d.ts +2 -0
  75. package/dist/plugins/opentelemetry-metrics.js +1 -0
  76. package/dist/plugins/opentelemetry.cjs +1 -0
  77. package/dist/plugins/opentelemetry.d.cts +2 -0
  78. package/dist/plugins/opentelemetry.d.ts +2 -0
  79. package/dist/plugins/opentelemetry.js +1 -0
  80. package/dist/plugins/rate-limit.cjs +1 -0
  81. package/dist/plugins/rate-limit.d.cts +2 -0
  82. package/dist/plugins/rate-limit.d.ts +2 -0
  83. package/dist/plugins/rate-limit.js +1 -0
  84. package/dist/plugins/retry.cjs +1 -1
  85. package/dist/plugins/retry.d.cts +1 -1
  86. package/dist/plugins/retry.d.ts +1 -1
  87. package/dist/plugins/retry.js +1 -1
  88. package/dist/plugins/upload.cjs +1 -1
  89. package/dist/plugins/upload.d.cts +1 -1
  90. package/dist/plugins/upload.d.ts +1 -1
  91. package/dist/plugins/upload.js +1 -1
  92. package/dist/plugins.cjs +1 -1
  93. package/dist/plugins.d.cts +13 -10
  94. package/dist/plugins.d.ts +13 -10
  95. package/dist/plugins.js +1 -1
  96. package/dist/rateLimitPlugin-1rbZeJmP.d.cts +33 -0
  97. package/dist/rateLimitPlugin-CDpoD85h.js +1 -0
  98. package/dist/rateLimitPlugin-D5t-8kzP.d.ts +33 -0
  99. package/dist/rateLimitPlugin-uEH2OKgl.cjs +1 -0
  100. package/dist/resolveRequestOrigin-DzOB9oX9.cjs +1 -0
  101. package/dist/resolveRequestOrigin-jeuuD5SV.js +1 -0
  102. package/dist/{response-BhyS3PAL.d.ts → response-B6Z3qxyO.d.cts} +138 -13
  103. package/dist/{response-BhyS3PAL.d.cts → response-B6Z3qxyO.d.ts} +138 -13
  104. package/dist/retryPlugin-C0dORYIQ.d.cts +6 -0
  105. package/dist/retryPlugin-CVelhp0f.d.ts +6 -0
  106. package/dist/testing.cjs +1 -1
  107. package/dist/testing.d.cts +1 -1
  108. package/dist/testing.d.ts +1 -1
  109. package/dist/testing.js +1 -1
  110. package/dist/{uploadPlugin-Bb7EawRX.d.ts → uploadPlugin-BrzbWtAN.d.ts} +1 -1
  111. package/dist/{uploadPlugin-AfhFIsO7.d.cts → uploadPlugin-Ci0ys-ng.d.cts} +1 -1
  112. package/dist/validateResponseStatus-CYU2N49m.cjs +6 -0
  113. package/dist/validateResponseStatus-JYSqdThE.js +6 -0
  114. package/dist/{waitForSignal-DyyPvJd5.js → waitForSignal-C3rpyDkF.js} +1 -1
  115. package/dist/{waitForSignal-yR1BeU8f.cjs → waitForSignal-xjHyZ4cK.cjs} +1 -1
  116. package/dist/xhrTransport-C-8xl1bw.cjs +1 -0
  117. package/dist/xhrTransport-Doc_yozh.js +1 -0
  118. package/package.json +34 -13
  119. package/dist/RequestError-BH6V64XR.js +0 -1
  120. package/dist/RequestError-DPSv-HVF.cjs +0 -1
  121. package/dist/SchemaValidationError-CjvWT8YA.d.ts +0 -166
  122. package/dist/SchemaValidationError-WMTfqSBV.d.cts +0 -166
  123. package/dist/buildRequest-BRZwRLoN.cjs +0 -1
  124. package/dist/buildRequest-Cwt8XEWO.js +0 -1
  125. package/dist/cachePlugin-CSHwJYwI.js +0 -1
  126. package/dist/cachePlugin-ZPYdHbsM.cjs +0 -1
  127. package/dist/createAbortError-D4rRBq2B.js +0 -1
  128. package/dist/createAbortError-DJqbdYgk.cjs +0 -1
  129. package/dist/createClient-CibOTVAy.cjs +0 -1
  130. package/dist/createClient-I13D6XsD.js +0 -1
  131. package/dist/isURLSearchParams-B93cMCGj.js +0 -1
  132. package/dist/isURLSearchParams-o-c8Q42t.cjs +0 -1
  133. package/dist/loggerPlugin-C15EW7Sc.d.ts +0 -6
  134. package/dist/loggerPlugin-uOFiUtBi.d.cts +0 -6
  135. package/dist/resolveRequestOrigin-BndIJeZ7.js +0 -1
  136. package/dist/resolveRequestOrigin-CRATeWff.cjs +0 -1
  137. package/dist/retryPlugin-2mYKvWy3.d.ts +0 -6
  138. package/dist/retryPlugin-BqlUpmd0.d.cts +0 -6
  139. package/dist/validateResponseStatus-Dqzr342t.js +0 -4
  140. package/dist/validateResponseStatus-QAjcah2i.cjs +0 -4
  141. package/dist/xhrTransport-C0pg00i5.js +0 -1
  142. package/dist/xhrTransport-CeW2DDzo.cjs +0 -1
@@ -0,0 +1,33 @@
1
+ import { f as RequestConfig } from "./response-B6Z3qxyO.cjs";
2
+ import { t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
3
+ //#region src/plugins/rateLimitPlugin.d.ts
4
+ interface RateLimitPluginOptions {
5
+ /** Maximum transport attempts admitted during each rolling interval. */
6
+ maxRequests?: number;
7
+ /** Rolling interval in milliseconds. @default 1000 */
8
+ interval?: number;
9
+ /** Maximum queued attempts for each isolation key. @default 1000 */
10
+ maxQueue?: number;
11
+ /** Maximum queue wait in milliseconds. @default 30000 */
12
+ queueTimeout?: number;
13
+ /** Maximum inactive isolation states retained. @default 1000 */
14
+ maxKeys?: number;
15
+ /** @default the resolved request origin or "default" */
16
+ createKey?: (config: RequestConfig) => string;
17
+ /** Share 429 Retry-After cooldowns between requests with the same key. @default true */
18
+ sharedRetryAfter?: boolean;
19
+ /** Maximum shared Retry-After cooldown in milliseconds. @default 60000 */
20
+ maxRetryAfter?: number;
21
+ }
22
+ interface RateLimitState {
23
+ remaining: number;
24
+ queued: number;
25
+ resetAt?: number;
26
+ cooldownUntil?: number;
27
+ }
28
+ interface RateLimitPlugin extends Plugin {
29
+ getState(key: string): Readonly<RateLimitState>;
30
+ }
31
+ declare function rateLimitPlugin(options?: RateLimitPluginOptions): RateLimitPlugin;
32
+ //#endregion
33
+ export { rateLimitPlugin as i, RateLimitPluginOptions as n, RateLimitState as r, RateLimitPlugin as t };
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./RequestError-B0HIY1zK.js";import{t as n}from"./maxTimerDelay-Hn7X0Wuh.js";import{t as r}from"./resolveExtensionConfig-QAFHZVte.js";import{t as i}from"./resolveRequestOrigin-jeuuD5SV.js";function parseRetryAfter(e,t=Date.now()){let n=e?.get(`retry-after`)?.trim();if(!n)return;if(/^\d+$/.test(n)){let e=Number(n);return Number.isFinite(e)?Math.max(0,e*1e3):void 0}let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function rateLimitPlugin(t={}){let n=normalizeOptions(t),i=new Map;return{name:`rate-limit`,getState(e){let t=i.get(normalizeKey(e));if(!t)return{remaining:n.maxRequests,queued:0};let r=Date.now();return pruneTimestamps(t,r,n.interval),createState(t,n,r)},install(t){let a=!0;t.hooks.onTransport(e=>{let t=r(e.config,`rateLimit`);if(t?.enabled===!1)return;let o=normalizeKey(t?.key??n.createKey(e.config)),s=Date.now(),c=getRecord(i,o,n.maxKeys,s,n.interval);if(pruneTimestamps(c,s,n.interval),e.rateLimitApplied=!0,c.size===0&&(c.cooldownUntil??0)<=s&&activeCount(c)<n.maxRequests){c.timestamps.push(s);return}if(e.config.signal?.aborted)throw createAbortError(e.config.signal.reason,e.config);if(c.size>=n.maxQueue)throw createLimitError(`Rate limit queue is full`,e.config);let l=normalizeDuration(t?.queueTimeout,n.queueTimeout),u=Date.now();return enqueue(c,e.config,l,()=>{schedule(c,i,n,a)}).then(()=>{if(e.rateLimitWaitTime+=Math.max(0,Date.now()-u),!a)throw createRemovedError(e.config)})});let observeRetryAfter=t=>{if(!n.sharedRetryAfter)return;let o=r(t.config,`rateLimit`);if(o?.enabled===!1||o?.sharedRetryAfter===!1||!isRateLimitError(t))return;let s=parseRetryAfter((t.response??(e(t.error)?t.error.response:void 0))?.headers);if(s===void 0)return;let c=normalizeKey(o?.key??n.createKey(t.config)),l=Date.now(),u=getRecord(i,c,n.maxKeys,l,n.interval),d=l+Math.min(s,n.maxRetryAfter);(u.cooldownUntil??0)>=d||(u.cooldownUntil=d,clearRecordTimer(u),schedule(u,i,n,a))};return t.hooks.onResponse(observeRetryAfter,{requiresRawResponse:!1}),t.hooks.onError(observeRetryAfter),()=>{a=!1;for(let e of i.values()){clearRecordTimer(e);let t;for(;t=shiftQueue(e);)t.reject(createRemovedError(t.config))}i.clear()}}}}function isRateLimitError(t){return t.response?.status===429||e(t.error)&&t.error.status===429}function enqueue(e,t,n,r){let i=t.signal;return i?.aborted?Promise.reject(createAbortError(i.reason,t)):n<=0?Promise.reject(createLimitError(`Rate limit queue wait timed out`,t)):new Promise((a,o)=>{let s,c=!1,cleanup=()=>{s!==void 0&&(clearTimeout(s),s=void 0);try{i?.removeEventListener(`abort`,onAbort)}catch{}},rejectOnce=e=>{c||(c=!0,cleanup(),o(e))},resolveOnce=()=>{c||(c=!0,cleanup(),a())},onAbort=()=>{removeQueuedEntry(e,l),rejectOnce(createAbortError(i?.reason,t))},l={config:t,linked:!1,resolve:resolveOnce,reject:rejectOnce};try{i?.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}if(i?.aborted&&onAbort(),!c){if(Number.isFinite(n))try{s=setTimeout(()=>{removeQueuedEntry(e,l),rejectOnce(createLimitError(`Rate limit queue wait timed out`,t))},n)}catch(e){rejectOnce(e);return}appendQueue(e,l);try{r()}catch(t){removeQueuedEntry(e,l),rejectOnce(t)}}})}function schedule(e,t,r,i){if(!i||e.size===0||e.timer!==void 0)return;let a=Date.now();if(pruneTimestamps(e,a,r.interval),e.cooldownUntil!==void 0&&e.cooldownUntil>a){let o=Math.min(e.cooldownUntil-a,n);e.timer=setTimeout(()=>{e.timer=void 0,drain(e,t,r,i,Date.now())},o);return}if(e.cooldownUntil=void 0,activeCount(e)<r.maxRequests){drain(e,t,r,i,a);return}let o=(e.timestamps[e.timestampHead]??a)+r.interval,s=Math.max(0,Math.min(o-a,n));e.timer=setTimeout(()=>{e.timer=void 0,drain(e,t,r,i,Date.now())},s)}function drain(e,t,n,r,i){if(!(!r||t.get(e.key)!==e)){if(pruneTimestamps(e,i,n.interval),e.cooldownUntil!==void 0&&e.cooldownUntil>i){schedule(e,t,n,r);return}for(e.cooldownUntil=void 0;e.size>0&&activeCount(e)<n.maxRequests;){let t=shiftQueue(e);if(!t)break;e.timestamps.push(i),t.resolve()}schedule(e,t,n,r)}}function pruneTimestamps(e,t,n){let r=t-n;for(;e.timestampHead<e.timestamps.length&&(e.timestamps[e.timestampHead]??0)<=r;)e.timestampHead+=1;e.timestampHead>=1024&&e.timestampHead*2>=e.timestamps.length&&(e.timestamps=e.timestamps.slice(e.timestampHead),e.timestampHead=0)}function activeCount(e){return e.timestamps.length-e.timestampHead}function createState(e,t,n){(e.cooldownUntil??0)<=n&&(e.cooldownUntil=void 0);let r=activeCount(e),i=r>0?(e.timestamps[e.timestampHead]??n)+t.interval:void 0;return{remaining:e.cooldownUntil!==void 0&&e.cooldownUntil>n?0:Math.max(0,t.maxRequests-r),queued:e.size,...i===void 0&&e.cooldownUntil===void 0?{}:{resetAt:Math.max(i??0,e.cooldownUntil??0)},...e.cooldownUntil===void 0?{}:{cooldownUntil:e.cooldownUntil}}}function getRecord(e,t,n,r,i){let a=e.get(t);if(a)return a;trimRecords(e,Math.max(0,n-1),r,i);let o={key:t,timestamps:[],timestampHead:0,size:0};return e.set(t,o),o}function trimRecords(e,t,n,r){for(let[i,a]of e){if(e.size<=t)return;pruneTimestamps(a,n,r),a.size===0&&activeCount(a)===0&&(a.cooldownUntil??0)<=n&&(clearRecordTimer(a),e.delete(i))}}function appendQueue(e,t){t.prev=e.tail,t.next=void 0,t.linked=!0,e.tail?e.tail.next=t:e.head=t,e.tail=t,e.size+=1}function shiftQueue(e){let t=e.head;return t&&removeQueuedEntry(e,t),t}function removeQueuedEntry(e,t){if(!t.linked)return;let{prev:n,next:r}=t;n?n.next=r:e.head=r,r?r.prev=n:e.tail=n,t.prev=void 0,t.next=void 0,t.linked=!1,--e.size,e.size===0&&clearRecordTimer(e)}function clearRecordTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}function normalizeOptions(e){return{maxRequests:normalizePositiveInteger(e.maxRequests,10),interval:normalizePositiveDuration(e.interval,1e3),maxQueue:normalizeNonNegativeInteger(e.maxQueue,1e3),queueTimeout:normalizeDuration(e.queueTimeout,3e4),maxKeys:normalizePositiveInteger(e.maxKeys,1e3),createKey:e.createKey??i,sharedRetryAfter:e.sharedRetryAfter??!0,maxRetryAfter:normalizePositiveDuration(e.maxRetryAfter,6e4)}}function normalizePositiveInteger(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.floor(e))}function normalizeNonNegativeInteger(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function normalizePositiveDuration(e,t){return e===void 0||!Number.isFinite(e)?t:Math.min(Math.max(1,e),n)}function normalizeDuration(e,t){return e===void 0?t:Number.isFinite(e)?Math.min(Math.max(0,e),n):e>0?1/0:0}function normalizeKey(e){return String(e).trim()||`default`}function createLimitError(e,n){return new t(e,{code:`RATE_LIMIT`,config:n})}function createAbortError(e,n){return new t(`Request aborted while waiting for rate limit permit`,{code:`ABORT_ERROR`,config:n,cause:e})}function createRemovedError(e){return new t(`Rate limit plugin removed while request was queued`,{code:`ABORT_ERROR`,config:e})}export{rateLimitPlugin as t};
@@ -0,0 +1,33 @@
1
+ import { f as RequestConfig } from "./response-B6Z3qxyO.js";
2
+ import { t as Plugin } from "./Plugin-C9ZQzyF6.js";
3
+ //#region src/plugins/rateLimitPlugin.d.ts
4
+ interface RateLimitPluginOptions {
5
+ /** Maximum transport attempts admitted during each rolling interval. */
6
+ maxRequests?: number;
7
+ /** Rolling interval in milliseconds. @default 1000 */
8
+ interval?: number;
9
+ /** Maximum queued attempts for each isolation key. @default 1000 */
10
+ maxQueue?: number;
11
+ /** Maximum queue wait in milliseconds. @default 30000 */
12
+ queueTimeout?: number;
13
+ /** Maximum inactive isolation states retained. @default 1000 */
14
+ maxKeys?: number;
15
+ /** @default the resolved request origin or "default" */
16
+ createKey?: (config: RequestConfig) => string;
17
+ /** Share 429 Retry-After cooldowns between requests with the same key. @default true */
18
+ sharedRetryAfter?: boolean;
19
+ /** Maximum shared Retry-After cooldown in milliseconds. @default 60000 */
20
+ maxRetryAfter?: number;
21
+ }
22
+ interface RateLimitState {
23
+ remaining: number;
24
+ queued: number;
25
+ resetAt?: number;
26
+ cooldownUntil?: number;
27
+ }
28
+ interface RateLimitPlugin extends Plugin {
29
+ getState(key: string): Readonly<RateLimitState>;
30
+ }
31
+ declare function rateLimitPlugin(options?: RateLimitPluginOptions): RateLimitPlugin;
32
+ //#endregion
33
+ export { rateLimitPlugin as i, RateLimitPluginOptions as n, RateLimitState as r, RateLimitPlugin as t };
@@ -0,0 +1 @@
1
+ const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./maxTimerDelay-NH5XeTXb.cjs"),n=require("./resolveExtensionConfig-BHHfQwjF.cjs"),r=require("./resolveRequestOrigin-DzOB9oX9.cjs");function parseRetryAfter(e,t=Date.now()){let n=e?.get(`retry-after`)?.trim();if(!n)return;if(/^\d+$/.test(n)){let e=Number(n);return Number.isFinite(e)?Math.max(0,e*1e3):void 0}let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function rateLimitPlugin(t={}){let r=normalizeOptions(t),i=new Map;return{name:`rate-limit`,getState(e){let t=i.get(normalizeKey(e));if(!t)return{remaining:r.maxRequests,queued:0};let n=Date.now();return pruneTimestamps(t,n,r.interval),createState(t,r,n)},install(t){let a=!0;t.hooks.onTransport(e=>{let t=n.t(e.config,`rateLimit`);if(t?.enabled===!1)return;let o=normalizeKey(t?.key??r.createKey(e.config)),s=Date.now(),c=getRecord(i,o,r.maxKeys,s,r.interval);if(pruneTimestamps(c,s,r.interval),e.rateLimitApplied=!0,c.size===0&&(c.cooldownUntil??0)<=s&&activeCount(c)<r.maxRequests){c.timestamps.push(s);return}if(e.config.signal?.aborted)throw createAbortError(e.config.signal.reason,e.config);if(c.size>=r.maxQueue)throw createLimitError(`Rate limit queue is full`,e.config);let l=normalizeDuration(t?.queueTimeout,r.queueTimeout),u=Date.now();return enqueue(c,e.config,l,()=>{schedule(c,i,r,a)}).then(()=>{if(e.rateLimitWaitTime+=Math.max(0,Date.now()-u),!a)throw createRemovedError(e.config)})});let observeRetryAfter=t=>{if(!r.sharedRetryAfter)return;let o=n.t(t.config,`rateLimit`);if(o?.enabled===!1||o?.sharedRetryAfter===!1||!isRateLimitError(t))return;let s=parseRetryAfter((t.response??(e.n(t.error)?t.error.response:void 0))?.headers);if(s===void 0)return;let c=normalizeKey(o?.key??r.createKey(t.config)),l=Date.now(),u=getRecord(i,c,r.maxKeys,l,r.interval),d=l+Math.min(s,r.maxRetryAfter);(u.cooldownUntil??0)>=d||(u.cooldownUntil=d,clearRecordTimer(u),schedule(u,i,r,a))};return t.hooks.onResponse(observeRetryAfter,{requiresRawResponse:!1}),t.hooks.onError(observeRetryAfter),()=>{a=!1;for(let e of i.values()){clearRecordTimer(e);let t;for(;t=shiftQueue(e);)t.reject(createRemovedError(t.config))}i.clear()}}}}function isRateLimitError(t){return t.response?.status===429||e.n(t.error)&&t.error.status===429}function enqueue(e,t,n,r){let i=t.signal;return i?.aborted?Promise.reject(createAbortError(i.reason,t)):n<=0?Promise.reject(createLimitError(`Rate limit queue wait timed out`,t)):new Promise((a,o)=>{let s,c=!1,cleanup=()=>{s!==void 0&&(clearTimeout(s),s=void 0);try{i?.removeEventListener(`abort`,onAbort)}catch{}},rejectOnce=e=>{c||(c=!0,cleanup(),o(e))},resolveOnce=()=>{c||(c=!0,cleanup(),a())},onAbort=()=>{removeQueuedEntry(e,l),rejectOnce(createAbortError(i?.reason,t))},l={config:t,linked:!1,resolve:resolveOnce,reject:rejectOnce};try{i?.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}if(i?.aborted&&onAbort(),!c){if(Number.isFinite(n))try{s=setTimeout(()=>{removeQueuedEntry(e,l),rejectOnce(createLimitError(`Rate limit queue wait timed out`,t))},n)}catch(e){rejectOnce(e);return}appendQueue(e,l);try{r()}catch(t){removeQueuedEntry(e,l),rejectOnce(t)}}})}function schedule(e,n,r,i){if(!i||e.size===0||e.timer!==void 0)return;let a=Date.now();if(pruneTimestamps(e,a,r.interval),e.cooldownUntil!==void 0&&e.cooldownUntil>a){let o=Math.min(e.cooldownUntil-a,t.t);e.timer=setTimeout(()=>{e.timer=void 0,drain(e,n,r,i,Date.now())},o);return}if(e.cooldownUntil=void 0,activeCount(e)<r.maxRequests){drain(e,n,r,i,a);return}let o=(e.timestamps[e.timestampHead]??a)+r.interval,s=Math.max(0,Math.min(o-a,t.t));e.timer=setTimeout(()=>{e.timer=void 0,drain(e,n,r,i,Date.now())},s)}function drain(e,t,n,r,i){if(!(!r||t.get(e.key)!==e)){if(pruneTimestamps(e,i,n.interval),e.cooldownUntil!==void 0&&e.cooldownUntil>i){schedule(e,t,n,r);return}for(e.cooldownUntil=void 0;e.size>0&&activeCount(e)<n.maxRequests;){let t=shiftQueue(e);if(!t)break;e.timestamps.push(i),t.resolve()}schedule(e,t,n,r)}}function pruneTimestamps(e,t,n){let r=t-n;for(;e.timestampHead<e.timestamps.length&&(e.timestamps[e.timestampHead]??0)<=r;)e.timestampHead+=1;e.timestampHead>=1024&&e.timestampHead*2>=e.timestamps.length&&(e.timestamps=e.timestamps.slice(e.timestampHead),e.timestampHead=0)}function activeCount(e){return e.timestamps.length-e.timestampHead}function createState(e,t,n){(e.cooldownUntil??0)<=n&&(e.cooldownUntil=void 0);let r=activeCount(e),i=r>0?(e.timestamps[e.timestampHead]??n)+t.interval:void 0;return{remaining:e.cooldownUntil!==void 0&&e.cooldownUntil>n?0:Math.max(0,t.maxRequests-r),queued:e.size,...i===void 0&&e.cooldownUntil===void 0?{}:{resetAt:Math.max(i??0,e.cooldownUntil??0)},...e.cooldownUntil===void 0?{}:{cooldownUntil:e.cooldownUntil}}}function getRecord(e,t,n,r,i){let a=e.get(t);if(a)return a;trimRecords(e,Math.max(0,n-1),r,i);let o={key:t,timestamps:[],timestampHead:0,size:0};return e.set(t,o),o}function trimRecords(e,t,n,r){for(let[i,a]of e){if(e.size<=t)return;pruneTimestamps(a,n,r),a.size===0&&activeCount(a)===0&&(a.cooldownUntil??0)<=n&&(clearRecordTimer(a),e.delete(i))}}function appendQueue(e,t){t.prev=e.tail,t.next=void 0,t.linked=!0,e.tail?e.tail.next=t:e.head=t,e.tail=t,e.size+=1}function shiftQueue(e){let t=e.head;return t&&removeQueuedEntry(e,t),t}function removeQueuedEntry(e,t){if(!t.linked)return;let{prev:n,next:r}=t;n?n.next=r:e.head=r,r?r.prev=n:e.tail=n,t.prev=void 0,t.next=void 0,t.linked=!1,--e.size,e.size===0&&clearRecordTimer(e)}function clearRecordTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}function normalizeOptions(e){return{maxRequests:normalizePositiveInteger(e.maxRequests,10),interval:normalizePositiveDuration(e.interval,1e3),maxQueue:normalizeNonNegativeInteger(e.maxQueue,1e3),queueTimeout:normalizeDuration(e.queueTimeout,3e4),maxKeys:normalizePositiveInteger(e.maxKeys,1e3),createKey:e.createKey??r.t,sharedRetryAfter:e.sharedRetryAfter??!0,maxRetryAfter:normalizePositiveDuration(e.maxRetryAfter,6e4)}}function normalizePositiveInteger(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.floor(e))}function normalizeNonNegativeInteger(e,t){return e===void 0||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function normalizePositiveDuration(e,n){return e===void 0||!Number.isFinite(e)?n:Math.min(Math.max(1,e),t.t)}function normalizeDuration(e,n){return e===void 0?n:Number.isFinite(e)?Math.min(Math.max(0,e),t.t):e>0?1/0:0}function normalizeKey(e){return String(e).trim()||`default`}function createLimitError(t,n){return new e.t(t,{code:`RATE_LIMIT`,config:n})}function createAbortError(t,n){return new e.t(`Request aborted while waiting for rate limit permit`,{code:`ABORT_ERROR`,config:n,cause:t})}function createRemovedError(t){return new e.t(`Rate limit plugin removed while request was queued`,{code:`ABORT_ERROR`,config:t})}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return rateLimitPlugin}});
@@ -0,0 +1 @@
1
+ let e,t,n;function parseOrigin(r,i){if(r===e&&i===t)return n;try{let a=i===void 0?new URL(r).origin:new URL(r,i).origin;return e=r,t=i,n=a,a}catch{return}}function resolveRequestOrigin(e){let t=String(e.url);if(t.includes(`:`)){let e=parseOrigin(t);if(e!==void 0)return e}return e.baseURL?parseOrigin(t,e.baseURL)??`default`:`default`}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return resolveRequestOrigin}});
@@ -0,0 +1 @@
1
+ let e,t,n;function parseOrigin(r,i){if(r===e&&i===t)return n;try{let a=i===void 0?new URL(r).origin:new URL(r,i).origin;return e=r,t=i,n=a,a}catch{return}}function resolveRequestOrigin(e){let t=String(e.url);if(t.includes(`:`)){let e=parseOrigin(t);if(e!==void 0)return e}return e.baseURL?parseOrigin(t,e.baseURL)??`default`:`default`}export{resolveRequestOrigin as t};
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * HTTP request method.
4
4
  */
5
- type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
5
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'QUERY' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
7
  //#region src/types/standardSchema.d.ts
8
8
  /**
@@ -76,12 +76,25 @@ interface RetryOptions {
76
76
  /**
77
77
  * HTTP methods that may be retried.
78
78
  *
79
- * @default GET, HEAD, OPTIONS, PUT and DELETE
79
+ * @default GET, HEAD, OPTIONS, QUERY, PUT and DELETE
80
80
  */
81
81
  methods?: readonly HttpMethod[];
82
+ /**
83
+ * HTTP response status codes that may be retried.
84
+ *
85
+ * When omitted, HTTP 408, 425, 429, 5xx, and timed 413 responses are
86
+ * retried. A configured 413 still requires a valid retry timing header.
87
+ */
88
+ statusCodes?: readonly number[];
89
+ /**
90
+ * Retry per-attempt timeout failures.
91
+ *
92
+ * @default true
93
+ */
94
+ retryOnTimeout?: boolean;
82
95
  delay?: number | ((attempt: number, error: unknown) => number | Promise<number>);
83
96
  /**
84
- * Respect the server Retry-After response header.
97
+ * Respect Retry-After and common rate-limit reset response headers.
85
98
  *
86
99
  * @default true
87
100
  */
@@ -97,7 +110,7 @@ interface RetryOptions {
97
110
  *
98
111
  * `true` applies full jitter between zero and the configured delay.
99
112
  * A function receives the pending retry event and returns the final delay.
100
- * Server-provided Retry-After delays are not jittered.
113
+ * Server-provided retry delays are not jittered.
101
114
  *
102
115
  * @default false
103
116
  */
@@ -109,7 +122,7 @@ interface RetryOptions {
109
122
  * @default unlimited
110
123
  */
111
124
  maxElapsedTime?: number;
112
- shouldRetry?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
125
+ shouldRetry?: (error: unknown, attempt: number) => boolean | undefined | Promise<boolean | undefined>;
113
126
  /**
114
127
  * Observe a scheduled retry.
115
128
  *
@@ -186,6 +199,37 @@ interface ConcurrencyOptions {
186
199
  */
187
200
  queueTimeout?: number;
188
201
  }
202
+ interface RateLimitOptions {
203
+ /** Enable request-rate limiting. @default true */
204
+ enabled?: boolean;
205
+ /** Override the isolation key for this request. */
206
+ key?: string;
207
+ /** Maximum time this transport attempt may wait for a permit. */
208
+ queueTimeout?: number;
209
+ /** Participate in shared 429 Retry-After cooldowns. @default true */
210
+ sharedRetryAfter?: boolean;
211
+ }
212
+ type OpenTelemetryAttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
213
+ /** Per-request overrides for `openTelemetryPlugin()`. */
214
+ interface OpenTelemetryOptions {
215
+ /** Enable tracing for this request. @default true */
216
+ enabled?: boolean;
217
+ /** Inject the active span context into request headers. @default true */
218
+ propagate?: boolean;
219
+ /** Override the low-cardinality span name. */
220
+ spanName?: string;
221
+ /** Additional span attributes. Values must not contain secrets. */
222
+ attributes?: Readonly<Record<string, OpenTelemetryAttributeValue>>;
223
+ }
224
+ /** Per-request overrides for `openTelemetryMetricsPlugin()`. */
225
+ interface OpenTelemetryMetricsOptions {
226
+ /** Enable metrics for this request. @default true */
227
+ enabled?: boolean;
228
+ /** Measure returned stream consumption until completion or cancellation. @default true */
229
+ measureStreamConsumption?: boolean;
230
+ /** Additional low-cardinality attributes. Values must not contain secrets. */
231
+ attributes?: Readonly<Record<string, OpenTelemetryAttributeValue>>;
232
+ }
189
233
  interface AuthOptions {
190
234
  token?: string | (() => string | Promise<string>);
191
235
  scheme?: string;
@@ -308,7 +352,9 @@ interface DownloadOptions {
308
352
  //#region src/types/config.d.ts
309
353
  type QueryValue = string | number | boolean | null | undefined;
310
354
  type QueryParams = Record<string, QueryValue | QueryValue[]>;
311
- type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse' | 'ndjson';
355
+ type QuerySerializer = (query: QueryParams) => string;
356
+ type RequestURL = string | URL;
357
+ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'bytes' | 'formData' | 'stream' | 'sse' | 'ndjson';
312
358
  /**
313
359
  * Native Fetch options passed to the underlying adapter.
314
360
  *
@@ -316,6 +362,15 @@ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse'
316
362
  * is a single source of truth for method, headers, body and cancellation.
317
363
  */
318
364
  type FetchOptions = Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>;
365
+ type FetchFunction = typeof globalThis.fetch;
366
+ interface JsonParserContext {
367
+ /** Final request configuration used for the response. */
368
+ readonly config: RequestConfig;
369
+ /** Native response whose buffered JSON body is being parsed. */
370
+ readonly response: Response;
371
+ }
372
+ type JsonParser = (text: string, context: JsonParserContext) => unknown | Promise<unknown>;
373
+ type JsonStringifier = (value: unknown) => string;
319
374
  /**
320
375
  * Plugin-owned request configuration.
321
376
  *
@@ -328,11 +383,14 @@ interface RequestExtensions {
328
383
  concurrency?: ConcurrencyOptions;
329
384
  download?: DownloadOptions;
330
385
  logger?: LoggerOptions;
386
+ openTelemetry?: OpenTelemetryOptions;
387
+ openTelemetryMetrics?: OpenTelemetryMetricsOptions;
388
+ rateLimit?: RateLimitOptions;
331
389
  retry?: number | RetryOptions;
332
390
  upload?: UploadOptions;
333
391
  }
334
392
  interface RequestConfig {
335
- url: string;
393
+ url: RequestURL;
336
394
  method?: HttpMethod;
337
395
  baseURL?: string;
338
396
  /**
@@ -344,21 +402,53 @@ interface RequestConfig {
344
402
  */
345
403
  allowAbsoluteUrls?: boolean;
346
404
  fetchOptions?: FetchOptions;
405
+ /**
406
+ * Fetch-compatible transport function used by the built-in FetchAdapter.
407
+ *
408
+ * @default globalThis.fetch
409
+ */
410
+ fetch?: FetchFunction;
411
+ /** Custom parser used for buffered JSON responses. */
412
+ parseJson?: JsonParser;
413
+ /** Custom stringifier used for `json` and plain-object request bodies. */
414
+ stringifyJson?: JsonStringifier;
415
+ /**
416
+ * Application metadata available throughout the request lifecycle.
417
+ *
418
+ * Context is shallow merged and is never sent over the network.
419
+ */
420
+ context?: Record<string, unknown>;
347
421
  headers?: HeadersInit;
422
+ /**
423
+ * Case-insensitive names of inherited headers to remove.
424
+ *
425
+ * @default []
426
+ */
427
+ removeHeaders?: readonly string[];
348
428
  query?: QueryParams;
429
+ /** Custom serializer for object query parameters. */
430
+ querySerializer?: QuerySerializer;
349
431
  searchParams?: URLSearchParams;
350
432
  body?: BodyInit | Record<string, unknown> | null;
351
- json?: Record<string, unknown> | unknown[];
433
+ /** Any value accepted by the configured JSON stringifier. */
434
+ json?: unknown;
352
435
  form?: URLSearchParams | Record<string, QueryValue | QueryValue[]>;
353
436
  formData?: FormData | Record<string, unknown>;
354
437
  timeout?: number;
438
+ /**
439
+ * Maximum duration for the complete request lifecycle, including hooks,
440
+ * retries, retry delays, parsing, interceptors, and stream consumption.
441
+ *
442
+ * @default disabled
443
+ */
444
+ totalTimeout?: number;
355
445
  signal?: AbortSignal;
356
446
  /**
357
- * Maximum request body size in bytes when the serialized size can be
358
- * determined before dispatch.
447
+ * Maximum request body size in bytes. Deterministically sized bodies are
448
+ * rejected before dispatch; ReadableStream bodies are limited as consumed.
359
449
  *
360
- * FormData and ReadableStream bodies cannot be preflighted without
361
- * buffering and are therefore not covered.
450
+ * Native FormData cannot be measured without changing its encoding and is
451
+ * therefore not covered.
362
452
  *
363
453
  * @default unlimited
364
454
  */
@@ -369,6 +459,14 @@ interface RequestConfig {
369
459
  * @default unlimited
370
460
  */
371
461
  maxResponseSize?: number;
462
+ /**
463
+ * Maximum body size parsed into HTTP_ERROR.data. Larger error bodies are
464
+ * not parsed, while status, headers, and the raw response remain available.
465
+ * Set to Infinity to disable this error-body-specific guard.
466
+ *
467
+ * @default 10 MiB
468
+ */
469
+ maxErrorResponseSize?: number;
372
470
  /**
373
471
  * Maximum nested array depth accepted while building FormData.
374
472
  *
@@ -382,9 +480,25 @@ interface RequestConfig {
382
480
  * Accepts any Standard Schema v1 compatible validator.
383
481
  */
384
482
  schema?: StandardSchemaV1;
483
+ /**
484
+ * Validate and optionally transform each SSE event or NDJSON record lazily.
485
+ *
486
+ * Accepts any Standard Schema v1 compatible validator.
487
+ */
488
+ itemSchema?: StandardSchemaV1;
385
489
  validateStatus?: (status: number) => boolean;
490
+ /**
491
+ * Throw `HTTP_ERROR` for responses rejected by the default status policy.
492
+ *
493
+ * Use `validateStatus` instead when a custom status policy is required.
494
+ *
495
+ * @default true
496
+ */
497
+ throwHttpErrors?: boolean;
386
498
  extensions?: RequestExtensions;
387
499
  }
500
+ /** Per-call overrides accepted with a native Request input. */
501
+ type RequestInputConfig = Omit<RequestConfig, 'url'>;
388
502
  //#endregion
389
503
  //#region src/types/response.d.ts
390
504
  /**
@@ -408,6 +522,17 @@ interface ServerSentEvent {
408
522
  */
409
523
  retry?: number;
410
524
  }
525
+ /** Location of an item that failed validation in a streaming response. */
526
+ interface StreamingSchemaLocation {
527
+ /** Zero-based index among emitted SSE events or non-empty NDJSON records. */
528
+ itemIndex: number;
529
+ /** One-based physical NDJSON line number, including blank lines. */
530
+ lineNumber?: number;
531
+ /** SSE event type. */
532
+ event?: string;
533
+ /** SSE event identifier. */
534
+ eventId?: string;
535
+ }
411
536
  /**
412
537
  * Npora response.
413
538
  */
@@ -438,4 +563,4 @@ interface NporaResponse<T = unknown> {
438
563
  raw: Response;
439
564
  }
440
565
  //#endregion
441
- export { StandardSchemaV1 as A, ResponseLogEntry as C, UploadData as D, TransferProgress as E, UploadOptions as O, RequestLogger as S, RetryOptions as T, DownloadProgress as _, QueryValue as a, LoggerOptions as b, ResponseType as c, CircuitBreakerOptions as d, CircuitBreakerStateChange as f, DownloadOutput as g, DownloadOptions as h, QueryParams as i, HttpMethod as j, UploadProgress as k, AuthOptions as l, ConcurrencyOptions as m, ServerSentEvent as n, RequestConfig as o, CircuitState as p, FetchOptions as r, RequestExtensions as s, NporaResponse as t, CacheOptions as u, ErrorLogEntry as v, RetryEvent as w, RequestLogEntry as x, LoggerEntry as y };
566
+ export { OpenTelemetryMetricsOptions as A, UploadOptions as B, DownloadOptions as C, LoggerEntry as D, ErrorLogEntry as E, ResponseLogEntry as F, StandardSchemaV1 as H, RetryEvent as I, RetryOptions as L, RateLimitOptions as M, RequestLogEntry as N, LoggerOptions as O, RequestLogger as P, TransferProgress as R, ConcurrencyOptions as S, DownloadProgress as T, HttpMethod as U, UploadProgress as V, AuthOptions as _, FetchOptions as a, CircuitBreakerStateChange as b, JsonStringifier as c, QueryValue as d, RequestConfig as f, ResponseType as g, RequestURL as h, FetchFunction as i, OpenTelemetryOptions as j, OpenTelemetryAttributeValue as k, QueryParams as l, RequestInputConfig as m, ServerSentEvent as n, JsonParser as o, RequestExtensions as p, StreamingSchemaLocation as r, JsonParserContext as s, NporaResponse as t, QuerySerializer as u, CacheOptions as v, DownloadOutput as w, CircuitState as x, CircuitBreakerOptions as y, UploadData as z };
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * HTTP request method.
4
4
  */
5
- type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
5
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'QUERY' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
7
  //#region src/types/standardSchema.d.ts
8
8
  /**
@@ -76,12 +76,25 @@ interface RetryOptions {
76
76
  /**
77
77
  * HTTP methods that may be retried.
78
78
  *
79
- * @default GET, HEAD, OPTIONS, PUT and DELETE
79
+ * @default GET, HEAD, OPTIONS, QUERY, PUT and DELETE
80
80
  */
81
81
  methods?: readonly HttpMethod[];
82
+ /**
83
+ * HTTP response status codes that may be retried.
84
+ *
85
+ * When omitted, HTTP 408, 425, 429, 5xx, and timed 413 responses are
86
+ * retried. A configured 413 still requires a valid retry timing header.
87
+ */
88
+ statusCodes?: readonly number[];
89
+ /**
90
+ * Retry per-attempt timeout failures.
91
+ *
92
+ * @default true
93
+ */
94
+ retryOnTimeout?: boolean;
82
95
  delay?: number | ((attempt: number, error: unknown) => number | Promise<number>);
83
96
  /**
84
- * Respect the server Retry-After response header.
97
+ * Respect Retry-After and common rate-limit reset response headers.
85
98
  *
86
99
  * @default true
87
100
  */
@@ -97,7 +110,7 @@ interface RetryOptions {
97
110
  *
98
111
  * `true` applies full jitter between zero and the configured delay.
99
112
  * A function receives the pending retry event and returns the final delay.
100
- * Server-provided Retry-After delays are not jittered.
113
+ * Server-provided retry delays are not jittered.
101
114
  *
102
115
  * @default false
103
116
  */
@@ -109,7 +122,7 @@ interface RetryOptions {
109
122
  * @default unlimited
110
123
  */
111
124
  maxElapsedTime?: number;
112
- shouldRetry?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
125
+ shouldRetry?: (error: unknown, attempt: number) => boolean | undefined | Promise<boolean | undefined>;
113
126
  /**
114
127
  * Observe a scheduled retry.
115
128
  *
@@ -186,6 +199,37 @@ interface ConcurrencyOptions {
186
199
  */
187
200
  queueTimeout?: number;
188
201
  }
202
+ interface RateLimitOptions {
203
+ /** Enable request-rate limiting. @default true */
204
+ enabled?: boolean;
205
+ /** Override the isolation key for this request. */
206
+ key?: string;
207
+ /** Maximum time this transport attempt may wait for a permit. */
208
+ queueTimeout?: number;
209
+ /** Participate in shared 429 Retry-After cooldowns. @default true */
210
+ sharedRetryAfter?: boolean;
211
+ }
212
+ type OpenTelemetryAttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
213
+ /** Per-request overrides for `openTelemetryPlugin()`. */
214
+ interface OpenTelemetryOptions {
215
+ /** Enable tracing for this request. @default true */
216
+ enabled?: boolean;
217
+ /** Inject the active span context into request headers. @default true */
218
+ propagate?: boolean;
219
+ /** Override the low-cardinality span name. */
220
+ spanName?: string;
221
+ /** Additional span attributes. Values must not contain secrets. */
222
+ attributes?: Readonly<Record<string, OpenTelemetryAttributeValue>>;
223
+ }
224
+ /** Per-request overrides for `openTelemetryMetricsPlugin()`. */
225
+ interface OpenTelemetryMetricsOptions {
226
+ /** Enable metrics for this request. @default true */
227
+ enabled?: boolean;
228
+ /** Measure returned stream consumption until completion or cancellation. @default true */
229
+ measureStreamConsumption?: boolean;
230
+ /** Additional low-cardinality attributes. Values must not contain secrets. */
231
+ attributes?: Readonly<Record<string, OpenTelemetryAttributeValue>>;
232
+ }
189
233
  interface AuthOptions {
190
234
  token?: string | (() => string | Promise<string>);
191
235
  scheme?: string;
@@ -308,7 +352,9 @@ interface DownloadOptions {
308
352
  //#region src/types/config.d.ts
309
353
  type QueryValue = string | number | boolean | null | undefined;
310
354
  type QueryParams = Record<string, QueryValue | QueryValue[]>;
311
- type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse' | 'ndjson';
355
+ type QuerySerializer = (query: QueryParams) => string;
356
+ type RequestURL = string | URL;
357
+ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'bytes' | 'formData' | 'stream' | 'sse' | 'ndjson';
312
358
  /**
313
359
  * Native Fetch options passed to the underlying adapter.
314
360
  *
@@ -316,6 +362,15 @@ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse'
316
362
  * is a single source of truth for method, headers, body and cancellation.
317
363
  */
318
364
  type FetchOptions = Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>;
365
+ type FetchFunction = typeof globalThis.fetch;
366
+ interface JsonParserContext {
367
+ /** Final request configuration used for the response. */
368
+ readonly config: RequestConfig;
369
+ /** Native response whose buffered JSON body is being parsed. */
370
+ readonly response: Response;
371
+ }
372
+ type JsonParser = (text: string, context: JsonParserContext) => unknown | Promise<unknown>;
373
+ type JsonStringifier = (value: unknown) => string;
319
374
  /**
320
375
  * Plugin-owned request configuration.
321
376
  *
@@ -328,11 +383,14 @@ interface RequestExtensions {
328
383
  concurrency?: ConcurrencyOptions;
329
384
  download?: DownloadOptions;
330
385
  logger?: LoggerOptions;
386
+ openTelemetry?: OpenTelemetryOptions;
387
+ openTelemetryMetrics?: OpenTelemetryMetricsOptions;
388
+ rateLimit?: RateLimitOptions;
331
389
  retry?: number | RetryOptions;
332
390
  upload?: UploadOptions;
333
391
  }
334
392
  interface RequestConfig {
335
- url: string;
393
+ url: RequestURL;
336
394
  method?: HttpMethod;
337
395
  baseURL?: string;
338
396
  /**
@@ -344,21 +402,53 @@ interface RequestConfig {
344
402
  */
345
403
  allowAbsoluteUrls?: boolean;
346
404
  fetchOptions?: FetchOptions;
405
+ /**
406
+ * Fetch-compatible transport function used by the built-in FetchAdapter.
407
+ *
408
+ * @default globalThis.fetch
409
+ */
410
+ fetch?: FetchFunction;
411
+ /** Custom parser used for buffered JSON responses. */
412
+ parseJson?: JsonParser;
413
+ /** Custom stringifier used for `json` and plain-object request bodies. */
414
+ stringifyJson?: JsonStringifier;
415
+ /**
416
+ * Application metadata available throughout the request lifecycle.
417
+ *
418
+ * Context is shallow merged and is never sent over the network.
419
+ */
420
+ context?: Record<string, unknown>;
347
421
  headers?: HeadersInit;
422
+ /**
423
+ * Case-insensitive names of inherited headers to remove.
424
+ *
425
+ * @default []
426
+ */
427
+ removeHeaders?: readonly string[];
348
428
  query?: QueryParams;
429
+ /** Custom serializer for object query parameters. */
430
+ querySerializer?: QuerySerializer;
349
431
  searchParams?: URLSearchParams;
350
432
  body?: BodyInit | Record<string, unknown> | null;
351
- json?: Record<string, unknown> | unknown[];
433
+ /** Any value accepted by the configured JSON stringifier. */
434
+ json?: unknown;
352
435
  form?: URLSearchParams | Record<string, QueryValue | QueryValue[]>;
353
436
  formData?: FormData | Record<string, unknown>;
354
437
  timeout?: number;
438
+ /**
439
+ * Maximum duration for the complete request lifecycle, including hooks,
440
+ * retries, retry delays, parsing, interceptors, and stream consumption.
441
+ *
442
+ * @default disabled
443
+ */
444
+ totalTimeout?: number;
355
445
  signal?: AbortSignal;
356
446
  /**
357
- * Maximum request body size in bytes when the serialized size can be
358
- * determined before dispatch.
447
+ * Maximum request body size in bytes. Deterministically sized bodies are
448
+ * rejected before dispatch; ReadableStream bodies are limited as consumed.
359
449
  *
360
- * FormData and ReadableStream bodies cannot be preflighted without
361
- * buffering and are therefore not covered.
450
+ * Native FormData cannot be measured without changing its encoding and is
451
+ * therefore not covered.
362
452
  *
363
453
  * @default unlimited
364
454
  */
@@ -369,6 +459,14 @@ interface RequestConfig {
369
459
  * @default unlimited
370
460
  */
371
461
  maxResponseSize?: number;
462
+ /**
463
+ * Maximum body size parsed into HTTP_ERROR.data. Larger error bodies are
464
+ * not parsed, while status, headers, and the raw response remain available.
465
+ * Set to Infinity to disable this error-body-specific guard.
466
+ *
467
+ * @default 10 MiB
468
+ */
469
+ maxErrorResponseSize?: number;
372
470
  /**
373
471
  * Maximum nested array depth accepted while building FormData.
374
472
  *
@@ -382,9 +480,25 @@ interface RequestConfig {
382
480
  * Accepts any Standard Schema v1 compatible validator.
383
481
  */
384
482
  schema?: StandardSchemaV1;
483
+ /**
484
+ * Validate and optionally transform each SSE event or NDJSON record lazily.
485
+ *
486
+ * Accepts any Standard Schema v1 compatible validator.
487
+ */
488
+ itemSchema?: StandardSchemaV1;
385
489
  validateStatus?: (status: number) => boolean;
490
+ /**
491
+ * Throw `HTTP_ERROR` for responses rejected by the default status policy.
492
+ *
493
+ * Use `validateStatus` instead when a custom status policy is required.
494
+ *
495
+ * @default true
496
+ */
497
+ throwHttpErrors?: boolean;
386
498
  extensions?: RequestExtensions;
387
499
  }
500
+ /** Per-call overrides accepted with a native Request input. */
501
+ type RequestInputConfig = Omit<RequestConfig, 'url'>;
388
502
  //#endregion
389
503
  //#region src/types/response.d.ts
390
504
  /**
@@ -408,6 +522,17 @@ interface ServerSentEvent {
408
522
  */
409
523
  retry?: number;
410
524
  }
525
+ /** Location of an item that failed validation in a streaming response. */
526
+ interface StreamingSchemaLocation {
527
+ /** Zero-based index among emitted SSE events or non-empty NDJSON records. */
528
+ itemIndex: number;
529
+ /** One-based physical NDJSON line number, including blank lines. */
530
+ lineNumber?: number;
531
+ /** SSE event type. */
532
+ event?: string;
533
+ /** SSE event identifier. */
534
+ eventId?: string;
535
+ }
411
536
  /**
412
537
  * Npora response.
413
538
  */
@@ -438,4 +563,4 @@ interface NporaResponse<T = unknown> {
438
563
  raw: Response;
439
564
  }
440
565
  //#endregion
441
- export { StandardSchemaV1 as A, ResponseLogEntry as C, UploadData as D, TransferProgress as E, UploadOptions as O, RequestLogger as S, RetryOptions as T, DownloadProgress as _, QueryValue as a, LoggerOptions as b, ResponseType as c, CircuitBreakerOptions as d, CircuitBreakerStateChange as f, DownloadOutput as g, DownloadOptions as h, QueryParams as i, HttpMethod as j, UploadProgress as k, AuthOptions as l, ConcurrencyOptions as m, ServerSentEvent as n, RequestConfig as o, CircuitState as p, FetchOptions as r, RequestExtensions as s, NporaResponse as t, CacheOptions as u, ErrorLogEntry as v, RetryEvent as w, RequestLogEntry as x, LoggerEntry as y };
566
+ export { OpenTelemetryMetricsOptions as A, UploadOptions as B, DownloadOptions as C, LoggerEntry as D, ErrorLogEntry as E, ResponseLogEntry as F, StandardSchemaV1 as H, RetryEvent as I, RetryOptions as L, RateLimitOptions as M, RequestLogEntry as N, LoggerOptions as O, RequestLogger as P, TransferProgress as R, ConcurrencyOptions as S, DownloadProgress as T, HttpMethod as U, UploadProgress as V, AuthOptions as _, FetchOptions as a, CircuitBreakerStateChange as b, JsonStringifier as c, QueryValue as d, RequestConfig as f, ResponseType as g, RequestURL as h, FetchFunction as i, OpenTelemetryOptions as j, OpenTelemetryAttributeValue as k, QueryParams as l, RequestInputConfig as m, ServerSentEvent as n, JsonParser as o, RequestExtensions as p, StreamingSchemaLocation as r, JsonParserContext as s, NporaResponse as t, QuerySerializer as u, CacheOptions as v, DownloadOutput as w, CircuitState as x, CircuitBreakerOptions as y, UploadData as z };
@@ -0,0 +1,6 @@
1
+ import { L as RetryOptions } from "./response-B6Z3qxyO.cjs";
2
+ import { t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
3
+ //#region src/plugins/retryPlugin.d.ts
4
+ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
5
+ //#endregion
6
+ export { retryPlugin as t };
@@ -0,0 +1,6 @@
1
+ import { L as RetryOptions } from "./response-B6Z3qxyO.js";
2
+ import { t as Plugin } from "./Plugin-C9ZQzyF6.js";
3
+ //#region src/plugins/retryPlugin.d.ts
4
+ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
5
+ //#endregion
6
+ export { retryPlugin as t };