@npora/request 1.22.0 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,6 +80,29 @@ implementations.
80
80
 
81
81
  ## Quick start
82
82
 
83
+ To try a real response before connecting your own backend, save this as
84
+ `first-request.mjs` in the project where you installed the package:
85
+
86
+ ```js
87
+ import { createClient } from '@npora/request/core'
88
+
89
+ const api = createClient({
90
+ baseURL: 'https://npora.pages.dev/api',
91
+ timeout: 5000
92
+ })
93
+
94
+ const user = await api.get('/user')
95
+ console.log(user.name)
96
+ ```
97
+
98
+ Run `node first-request.mjs` with Node.js 22 or newer. The public demo returns
99
+ `Ada Lovelace`. For browser applications, use your own same-origin `/api` or a
100
+ backend with CORS configured for your application origin. The public demo is
101
+ for experimentation; connect your own backend for application traffic.
102
+
103
+ For a TypeScript application, define the expected response type and configure
104
+ your API base URL:
105
+
83
106
  ```ts
84
107
  import { createClient } from '@npora/request'
85
108
 
@@ -0,0 +1,2 @@
1
+ const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-DNjjEzFS.cjs"),n=require("./validateResponseStatus-6FKeKyEV.cjs"),r=require("./isReadableStream-uWhOa7eR.cjs"),i=require("./isPromiseLike-B4LL7DlV.cjs"),a=require("./maxTimerDelay-NH5XeTXb.cjs");var MockRecorder=class{constructor(e){if(this.entries=new Map,this.skipped=0,this.sequence=0,this.generation=0,!e||typeof e.adapter?.request!=`function`)throw TypeError(`Mock recording requires an adapter`);if(this.maxEntries=s(e.maxEntries,100),this.maxRecordSize=s(e.maxRecordSize,262144),e.transform!==void 0&&typeof e.transform!=`function`)throw TypeError(`Mock recording transform must be a function`);this.adapter=e.adapter,this.transform=e.transform}get recordings(){return[...this.entries].sort(([e],[t])=>e-t).map(([,e])=>JSON.parse(e))}get stats(){return{recorded:this.entries.size,skipped:this.skipped}}clear(){this.generation++,this.entries.clear(),this.skipped=0}exportMocks(){return this.recordings.map(({method:e,matcher:t,response:n})=>{let r=t.searchParams?`, searchParams: new URLSearchParams(${d(t.searchParams)})`:``,i=`{ url: ${d(t.url)}${t.query?`, query: JSON.parse(${d(JSON.stringify(t.query))})`:``}${r} }`,a=n.data===void 0?`undefined`:`JSON.parse(${d(JSON.stringify(n.data))})`,o=JSON.stringify({headers:n.headers,statusText:n.statusText});return`mock.onMethod(${d(e)}, ${i}).replyOnce(${n.status}, ${a}, JSON.parse(${d(o)}));`}).join(`
2
+ `)}async request(t){let n=this.generation,r;try{r={id:this.sequence++,generation:n,method:t.method??`GET`,matcher:l(t,this.maxRecordSize)}}catch{this.skipped++}let i;try{i=await this.adapter.request(t)}catch(t){if(r&&n===this.generation)try{e.n(t)&&t.code===`HTTP_ERROR`&&t.response?this.record(r,t.response):this.skipped++}catch{this.skipped++}throw t}return r&&this.record(r,i),i}record(e,t){if(e.generation===this.generation)try{let n=Object.fromEntries([...t.headers].filter(([e])=>!c(e)&&!/^(content-length|content-encoding|transfer-encoding)$/i.test(e))),r={method:e.method,matcher:e.matcher,response:{status:t.status,statusText:t.statusText,headers:n}};t.data!==void 0&&(r.response.data=u(t.data,this.maxRecordSize));let a=this.transform?this.transform(r):r;if(i.t(a)){Promise.resolve(a).catch(()=>{}),e.generation===this.generation&&this.skipped++;return}if(e.generation!==this.generation)return;if(!a){this.skipped++;return}let s=u(a,this.maxRecordSize);o(s);let l=JSON.stringify(s);if(e.generation!==this.generation)return;this.entries.set(e.id,l),this.entries.size>this.maxEntries&&this.entries.delete([...this.entries.keys()].reduce((e,t)=>Math.min(e,t)))}catch{e.generation===this.generation&&this.skipped++}}};function o(e){if(![`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`QUERY`].includes(e.method)||typeof e.matcher?.url!=`string`||!Number.isInteger(e.response?.status)||e.response.status<200||e.response.status>599||typeof e.response.statusText!=`string`)throw TypeError(`Invalid recording`);if(l({...e.matcher,searchParams:e.matcher.searchParams?new URLSearchParams(e.matcher.searchParams):void 0},2**53-1),!e.response.headers||Object.values(e.response.headers).some(e=>typeof e!=`string`))throw TypeError(`Invalid recorded headers`);new Response(null,e.response)}function s(e,t){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<=0)throw TypeError(`Mock recording limits must be positive safe integers`);return e}function c(e){return/^(?:authorization|proxyauthorization|cookie|setcookie|password|passwd|secret|token|accesstoken|refreshtoken|apikey|xapikey|clientsecret|sessionid|csrftoken|xcsrftoken|xsrftoken|xxsrftoken|xauthtoken)$/i.test(e.replace(/[-_]/g,``))}function l(e,t){let n=String(e.url);if(/^(?:[a-z][a-z\d+.-]*:)?\/\/[^/?#]*@/i.test(n))throw TypeError(`Credential URL`);if(n.includes(`#`))throw TypeError(`Fragment URL`);let r=n.indexOf(`?`);if(r!==-1){let e=new URLSearchParams(n.slice(r+1).split(`#`,1)[0]);for(let t of e.keys())if(c(t))throw TypeError(`Sensitive URL query`)}let i={url:n};if(e.query){for(let t of Object.keys(e.query))if(c(t))throw TypeError(`Sensitive query`);i.query=u(Object.fromEntries(Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>[e,Array.isArray(t)?t.filter(e=>e!==void 0):t])),t)}if(e.searchParams){for(let t of e.searchParams.keys())if(c(t))throw TypeError(`Sensitive searchParams`);i.searchParams=[...e.searchParams]}return u(i,t)}function u(e,t){let n=new Set,r=new TextEncoder,i=t,a=e=>{if(e.length>i||(i-=r.encode(e).byteLength,i<0))throw TypeError(`Recording too large`)},o=(e,t)=>{if(t>64)throw TypeError(`Recording too deep`);if(e===null||typeof e==`boolean`)return a(String(e)),e;if(typeof e==`string`){if(e.length>i)throw TypeError(`Recording too large`);return a(JSON.stringify(e)),e}if(typeof e==`number`&&Number.isFinite(e)&&!Object.is(e,-0))return a(String(e)),e;if(typeof e!=`object`||n.has(e))throw TypeError(`Non-JSON recording`);let r=Array.isArray(e);if(r&&e.length>(i-2)/2)throw TypeError(`Recording too large`);if(!r&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Non-JSON recording`);if(Object.getOwnPropertySymbols(e).length)throw TypeError(`Symbol recording`);n.add(e),a(`[]`);let s=r?[]:Object.create(null),l=Object.keys(e);if(l.length>i/2)throw TypeError(`Recording too large`);for(let n of l){let l=Object.getOwnPropertyDescriptor(e,n);if(n.length>i)throw TypeError(`Recording too large`);if(!(`value`in l))throw TypeError(`Accessor recording`);if(r&&!/^(0|[1-9]\d*)$/.test(n))throw TypeError(`Non-JSON array`);a(`,`),r||a(`${JSON.stringify(n)}:`);let u=c(n)?`[REDACTED]`:l.value,d=o(u,t+1);r?s.push(d):s[n]=d}if(r&&s.length!==e.length)throw TypeError(`Sparse recording`);return n.delete(e),s};return o(e,0)}function d(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var MockAdapter=class{constructor(e={}){this.handlers=new Map,this.rules=[],this.requests=[],this.delay=T(e.delay),this.recorder=e.record===void 0?void 0:new MockRecorder(e.record),Object.entries(e.handlers??{}).forEach(([e,t])=>{this.handlers.set(e,t)})}get history(){return[...this.requests]}get recordings(){return this.recorder?.recordings??[]}get recordingStats(){return this.recorder?.stats??{recorded:0,skipped:0}}exportMocks(){return this.recorder?.exportMocks()??``}clearRecordings(){return this.recorder?.clear(),this}on(e,t){return this.handlers.set(e,t),this}onMethod(e,t){let n=f(t);return new RouteBuilder({reply:(t,r,i,a)=>this.registerReply(e,n,t,r,i,a),error:(t,r,i)=>this.registerError(e,n,t,r,i)})}onGet(e){return this.onMethod(`GET`,e)}onPost(e){return this.onMethod(`POST`,e)}onPut(e){return this.onMethod(`PUT`,e)}onPatch(e){return this.onMethod(`PATCH`,e)}onDelete(e){return this.onMethod(`DELETE`,e)}onHead(e){return this.onMethod(`HEAD`,e)}onOptions(e){return this.onMethod(`OPTIONS`,e)}resetHistory(){return this.requests.length=0,this}resetHandlers(){return this.handlers.clear(),this.rules.length=0,this}reset(){return this.resetHandlers().resetHistory().clearRecordings()}async request(e){this.requests.push(e);let t=e.method??`GET`,n=this.rules.findIndex(n=>(n.method===void 0||n.method===t)&&p(n.matcher,e));if(n!==-1){let t=this.rules[n];return t.once&&this.rules.splice(n,1),b(await t.respond(e),e)}let r=this.handlers.get(String(e.url));if(!r){if(this.recorder)return this.recorder.request(e);throw Error(`No mock handler found for ${e.url} (${t})`)}return await E(this.delay,e),b(y(e,{status:200,statusText:`OK`,data:await r(e)}),e)}registerReply(e,t,n,r,i,a={}){let o=typeof r==`function`?r:()=>({status:r,data:i,...a});return this.rules.push({method:e,matcher:t,once:n,respond:async e=>{let t=await o(e);return await E(T(t.delay??this.delay),e),y(e,t)}}),this}registerError(t,n,r,i,a){return this.rules.push({method:t,matcher:n,once:r,respond:async t=>{throw await E(this.delay,t),new e.t(a,{code:i,config:t})}}),this}},RouteBuilder=class{constructor(e){this.registrar=e}reply(e,t,n={}){return this.registrar.reply(!1,e,t,n)}replyOnce(e,t,n={}){return this.registrar.reply(!0,e,t,n)}networkError(e=`Mock network error`){return this.registrar.error(!1,`NETWORK_ERROR`,e)}networkErrorOnce(e=`Mock network error`){return this.registrar.error(!0,`NETWORK_ERROR`,e)}timeout(e=`Mock request timeout`){return this.registrar.error(!1,`TIMEOUT_ERROR`,e)}timeoutOnce(e=`Mock request timeout`){return this.registrar.error(!0,`TIMEOUT_ERROR`,e)}};function f(e){return typeof e==`string`||e instanceof RegExp?{url:e}:e}function p(e,t){return m(e.url,String(t.url))&&h(e.query,t.query)&&_(e.searchParams,t.searchParams)&&v(e.headers,t.headers)}function m(e,t){return typeof e==`string`?e===t:(e.lastIndex=0,e.test(t))}function h(e,t){return!e||g(e)===g(t)}function g(e){if(!e)return`[]`;let t=[];for(let n of Object.keys(e).sort()){let r=e[n],i=Array.isArray(r)?r:[r];for(let e of i)e!==void 0&&t.push([n,e===null?``:String(e)])}return JSON.stringify(t)}function _(e,t){return!e||JSON.stringify([...e.entries()])===JSON.stringify([...t?.entries()??[]])}function v(e,t){if(!e)return!0;let n=new Headers(e),r=new Headers(t);for(let[e,t]of n.entries())if(r.get(e)!==t)return!1;return!0}function y(e,t){let n=new Headers(t.headers),r=C(t.data,n,t.status),i=t.statusText??x(t.status),a=new Response(r,{status:t.status,statusText:i,headers:n});return{data:t.data,status:t.status,statusText:i,headers:a.headers,config:e,raw:a}}function b(t,r){if(!n.t(t.status,r))throw new e.t(t.statusText||`Mock request failed`,{code:`HTTP_ERROR`,response:t});return t}function x(e){return S[e]??``}const S={200:`OK`,201:`Created`,202:`Accepted`,204:`No Content`,400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,408:`Request Timeout`,409:`Conflict`,422:`Unprocessable Content`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`};function C(e,t,r){return e==null||n.n(void 0,r)?null:typeof e==`string`||w(e)?e:(t.has(`content-type`)||t.set(`content-type`,`application/json`),JSON.stringify(e))}function w(e){return t.n(e)||n.r(e)||t.r(e)||r.t(e)||t.t(e)||ArrayBuffer.isView(e)}function T(e){return Number.isFinite(e)?Math.min(Math.max(0,e??0),a.t):e&&e>0?a.t:0}function E(t,n){let r=n.signal;if(r?.aborted)return Promise.reject(D(r.reason,n));let i=n.timeout&&n.timeout>0?n.timeout:void 0,a=i!==void 0&&i<=t,o=a?i:t;return o<=0?Promise.resolve():new Promise((t,s)=>{let c,l=!1,u=()=>{c!==void 0&&(clearTimeout(c),c=void 0);try{r?.removeEventListener(`abort`,f)}catch{}},d=e=>{l||(l=!0,u(),s(e))},f=()=>{d(D(r?.reason,n))};try{r?.addEventListener(`abort`,f,{once:!0})}catch(e){d(e);return}if(r?.aborted&&f(),!l)try{c=setTimeout(()=>{a?d(new e.t(`Request timeout after ${i}ms`,{code:`TIMEOUT_ERROR`,config:n})):(l=!0,u(),t())},o)}catch(e){d(e)}})}function D(t,n){return new e.t(`Mock request aborted`,{code:`ABORT_ERROR`,config:n,cause:t})}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return MockAdapter}});
@@ -0,0 +1,2 @@
1
+ import{n as isRequestError,t as e}from"./RequestError-B0HIY1zK.js";import{n as t,r as n,t as r}from"./isBinaryBody-D-Wp2IPk.js";import{n as i,r as a,t as o}from"./validateResponseStatus-BzkEtZZi.js";import{t as s}from"./isReadableStream-DBMPCr6B.js";import{t as c}from"./isPromiseLike-B6ok3Q-C.js";import{t as l}from"./maxTimerDelay-Hn7X0Wuh.js";var MockRecorder=class{constructor(e){if(this.entries=new Map,this.skipped=0,this.sequence=0,this.generation=0,!e||typeof e.adapter?.request!=`function`)throw TypeError(`Mock recording requires an adapter`);if(this.maxEntries=d(e.maxEntries,100),this.maxRecordSize=d(e.maxRecordSize,262144),e.transform!==void 0&&typeof e.transform!=`function`)throw TypeError(`Mock recording transform must be a function`);this.adapter=e.adapter,this.transform=e.transform}get recordings(){return[...this.entries].sort(([e],[t])=>e-t).map(([,e])=>JSON.parse(e))}get stats(){return{recorded:this.entries.size,skipped:this.skipped}}clear(){this.generation++,this.entries.clear(),this.skipped=0}exportMocks(){return this.recordings.map(({method:e,matcher:t,response:n})=>{let r=t.searchParams?`, searchParams: new URLSearchParams(${h(t.searchParams)})`:``,i=`{ url: ${h(t.url)}${t.query?`, query: JSON.parse(${h(JSON.stringify(t.query))})`:``}${r} }`,a=n.data===void 0?`undefined`:`JSON.parse(${h(JSON.stringify(n.data))})`,o=JSON.stringify({headers:n.headers,statusText:n.statusText});return`mock.onMethod(${h(e)}, ${i}).replyOnce(${n.status}, ${a}, JSON.parse(${h(o)}));`}).join(`
2
+ `)}async request(e){let t=this.generation,n;try{n={id:this.sequence++,generation:t,method:e.method??`GET`,matcher:p(e,this.maxRecordSize)}}catch{this.skipped++}let r;try{r=await this.adapter.request(e)}catch(e){if(n&&t===this.generation)try{isRequestError(e)&&e.code===`HTTP_ERROR`&&e.response?this.record(n,e.response):this.skipped++}catch{this.skipped++}throw e}return n&&this.record(n,r),r}record(e,t){if(e.generation===this.generation)try{let n=Object.fromEntries([...t.headers].filter(([e])=>!f(e)&&!/^(content-length|content-encoding|transfer-encoding)$/i.test(e))),r={method:e.method,matcher:e.matcher,response:{status:t.status,statusText:t.statusText,headers:n}};t.data!==void 0&&(r.response.data=m(t.data,this.maxRecordSize));let i=this.transform?this.transform(r):r;if(c(i)){Promise.resolve(i).catch(()=>{}),e.generation===this.generation&&this.skipped++;return}if(e.generation!==this.generation)return;if(!i){this.skipped++;return}let a=m(i,this.maxRecordSize);u(a);let o=JSON.stringify(a);if(e.generation!==this.generation)return;this.entries.set(e.id,o),this.entries.size>this.maxEntries&&this.entries.delete([...this.entries.keys()].reduce((e,t)=>Math.min(e,t)))}catch{e.generation===this.generation&&this.skipped++}}};function u(e){if(![`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`QUERY`].includes(e.method)||typeof e.matcher?.url!=`string`||!Number.isInteger(e.response?.status)||e.response.status<200||e.response.status>599||typeof e.response.statusText!=`string`)throw TypeError(`Invalid recording`);if(p({...e.matcher,searchParams:e.matcher.searchParams?new URLSearchParams(e.matcher.searchParams):void 0},2**53-1),!e.response.headers||Object.values(e.response.headers).some(e=>typeof e!=`string`))throw TypeError(`Invalid recorded headers`);new Response(null,e.response)}function d(e,t){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<=0)throw TypeError(`Mock recording limits must be positive safe integers`);return e}function f(e){return/^(?:authorization|proxyauthorization|cookie|setcookie|password|passwd|secret|token|accesstoken|refreshtoken|apikey|xapikey|clientsecret|sessionid|csrftoken|xcsrftoken|xsrftoken|xxsrftoken|xauthtoken)$/i.test(e.replace(/[-_]/g,``))}function p(e,t){let n=String(e.url);if(/^(?:[a-z][a-z\d+.-]*:)?\/\/[^/?#]*@/i.test(n))throw TypeError(`Credential URL`);if(n.includes(`#`))throw TypeError(`Fragment URL`);let r=n.indexOf(`?`);if(r!==-1){let e=new URLSearchParams(n.slice(r+1).split(`#`,1)[0]);for(let t of e.keys())if(f(t))throw TypeError(`Sensitive URL query`)}let i={url:n};if(e.query){for(let t of Object.keys(e.query))if(f(t))throw TypeError(`Sensitive query`);i.query=m(Object.fromEntries(Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>[e,Array.isArray(t)?t.filter(e=>e!==void 0):t])),t)}if(e.searchParams){for(let t of e.searchParams.keys())if(f(t))throw TypeError(`Sensitive searchParams`);i.searchParams=[...e.searchParams]}return m(i,t)}function m(e,t){let n=new Set,r=new TextEncoder,i=t,a=e=>{if(e.length>i||(i-=r.encode(e).byteLength,i<0))throw TypeError(`Recording too large`)},o=(e,t)=>{if(t>64)throw TypeError(`Recording too deep`);if(e===null||typeof e==`boolean`)return a(String(e)),e;if(typeof e==`string`){if(e.length>i)throw TypeError(`Recording too large`);return a(JSON.stringify(e)),e}if(typeof e==`number`&&Number.isFinite(e)&&!Object.is(e,-0))return a(String(e)),e;if(typeof e!=`object`||n.has(e))throw TypeError(`Non-JSON recording`);let r=Array.isArray(e);if(r&&e.length>(i-2)/2)throw TypeError(`Recording too large`);if(!r&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Non-JSON recording`);if(Object.getOwnPropertySymbols(e).length)throw TypeError(`Symbol recording`);n.add(e),a(`[]`);let s=r?[]:Object.create(null),c=Object.keys(e);if(c.length>i/2)throw TypeError(`Recording too large`);for(let n of c){let c=Object.getOwnPropertyDescriptor(e,n);if(n.length>i)throw TypeError(`Recording too large`);if(!(`value`in c))throw TypeError(`Accessor recording`);if(r&&!/^(0|[1-9]\d*)$/.test(n))throw TypeError(`Non-JSON array`);a(`,`),r||a(`${JSON.stringify(n)}:`);let l=f(n)?`[REDACTED]`:c.value,u=o(l,t+1);r?s.push(u):s[n]=u}if(r&&s.length!==e.length)throw TypeError(`Sparse recording`);return n.delete(e),s};return o(e,0)}function h(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var MockAdapter=class{constructor(e={}){this.handlers=new Map,this.rules=[],this.requests=[],this.delay=k(e.delay),this.recorder=e.record===void 0?void 0:new MockRecorder(e.record),Object.entries(e.handlers??{}).forEach(([e,t])=>{this.handlers.set(e,t)})}get history(){return[...this.requests]}get recordings(){return this.recorder?.recordings??[]}get recordingStats(){return this.recorder?.stats??{recorded:0,skipped:0}}exportMocks(){return this.recorder?.exportMocks()??``}clearRecordings(){return this.recorder?.clear(),this}on(e,t){return this.handlers.set(e,t),this}onMethod(e,t){let n=g(t);return new RouteBuilder({reply:(t,r,i,a)=>this.registerReply(e,n,t,r,i,a),error:(t,r,i)=>this.registerError(e,n,t,r,i)})}onGet(e){return this.onMethod(`GET`,e)}onPost(e){return this.onMethod(`POST`,e)}onPut(e){return this.onMethod(`PUT`,e)}onPatch(e){return this.onMethod(`PATCH`,e)}onDelete(e){return this.onMethod(`DELETE`,e)}onHead(e){return this.onMethod(`HEAD`,e)}onOptions(e){return this.onMethod(`OPTIONS`,e)}resetHistory(){return this.requests.length=0,this}resetHandlers(){return this.handlers.clear(),this.rules.length=0,this}reset(){return this.resetHandlers().resetHistory().clearRecordings()}async request(e){this.requests.push(e);let t=e.method??`GET`,n=this.rules.findIndex(n=>(n.method===void 0||n.method===t)&&_(n.matcher,e));if(n!==-1){let t=this.rules[n];return t.once&&this.rules.splice(n,1),w(await t.respond(e),e)}let r=this.handlers.get(String(e.url));if(!r){if(this.recorder)return this.recorder.request(e);throw Error(`No mock handler found for ${e.url} (${t})`)}return await A(this.delay,e),w(C(e,{status:200,statusText:`OK`,data:await r(e)}),e)}registerReply(e,t,n,r,i,a={}){let o=typeof r==`function`?r:()=>({status:r,data:i,...a});return this.rules.push({method:e,matcher:t,once:n,respond:async e=>{let t=await o(e);return await A(k(t.delay??this.delay),e),C(e,t)}}),this}registerError(t,n,r,i,a){return this.rules.push({method:t,matcher:n,once:r,respond:async t=>{throw await A(this.delay,t),new e(a,{code:i,config:t})}}),this}},RouteBuilder=class{constructor(e){this.registrar=e}reply(e,t,n={}){return this.registrar.reply(!1,e,t,n)}replyOnce(e,t,n={}){return this.registrar.reply(!0,e,t,n)}networkError(e=`Mock network error`){return this.registrar.error(!1,`NETWORK_ERROR`,e)}networkErrorOnce(e=`Mock network error`){return this.registrar.error(!0,`NETWORK_ERROR`,e)}timeout(e=`Mock request timeout`){return this.registrar.error(!1,`TIMEOUT_ERROR`,e)}timeoutOnce(e=`Mock request timeout`){return this.registrar.error(!0,`TIMEOUT_ERROR`,e)}};function g(e){return typeof e==`string`||e instanceof RegExp?{url:e}:e}function _(e,t){return v(e.url,String(t.url))&&y(e.query,t.query)&&x(e.searchParams,t.searchParams)&&S(e.headers,t.headers)}function v(e,t){return typeof e==`string`?e===t:(e.lastIndex=0,e.test(t))}function y(e,t){return!e||b(e)===b(t)}function b(e){if(!e)return`[]`;let t=[];for(let n of Object.keys(e).sort()){let r=e[n],i=Array.isArray(r)?r:[r];for(let e of i)e!==void 0&&t.push([n,e===null?``:String(e)])}return JSON.stringify(t)}function x(e,t){return!e||JSON.stringify([...e.entries()])===JSON.stringify([...t?.entries()??[]])}function S(e,t){if(!e)return!0;let n=new Headers(e),r=new Headers(t);for(let[e,t]of n.entries())if(r.get(e)!==t)return!1;return!0}function C(e,t){let n=new Headers(t.headers),r=D(t.data,n,t.status),i=t.statusText??T(t.status),a=new Response(r,{status:t.status,statusText:i,headers:n});return{data:t.data,status:t.status,statusText:i,headers:a.headers,config:e,raw:a}}function w(t,n){if(!o(t.status,n))throw new e(t.statusText||`Mock request failed`,{code:`HTTP_ERROR`,response:t});return t}function T(e){return E[e]??``}const E={200:`OK`,201:`Created`,202:`Accepted`,204:`No Content`,400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,408:`Request Timeout`,409:`Conflict`,422:`Unprocessable Content`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`};function D(e,t,n){return e==null||i(void 0,n)?null:typeof e==`string`||O(e)?e:(t.has(`content-type`)||t.set(`content-type`,`application/json`),JSON.stringify(e))}function O(e){return t(e)||a(e)||n(e)||s(e)||r(e)||ArrayBuffer.isView(e)}function k(e){return Number.isFinite(e)?Math.min(Math.max(0,e??0),l):e&&e>0?l:0}function A(t,n){let r=n.signal;if(r?.aborted)return Promise.reject(j(r.reason,n));let i=n.timeout&&n.timeout>0?n.timeout:void 0,a=i!==void 0&&i<=t,o=a?i:t;return o<=0?Promise.resolve():new Promise((t,s)=>{let c,l=!1,u=()=>{c!==void 0&&(clearTimeout(c),c=void 0);try{r?.removeEventListener(`abort`,f)}catch{}},d=e=>{l||(l=!0,u(),s(e))},f=()=>{d(j(r?.reason,n))};try{r?.addEventListener(`abort`,f,{once:!0})}catch(e){d(e);return}if(r?.aborted&&f(),!l)try{c=setTimeout(()=>{a?d(new e(`Request timeout after ${i}ms`,{code:`TIMEOUT_ERROR`,config:n})):(l=!0,u(),t())},o)}catch(e){d(e)}})}function j(t,n){return new e(`Mock request aborted`,{code:`ABORT_ERROR`,config:n,cause:t})}export{MockAdapter as t};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./errorResponseTimeout-CZWn7IpX.cjs"),n=require("./createClient-CXvspA_F.cjs"),r=require("./MockAdapter-DlW19YXg.cjs"),i=require("./PluginError-DT3VnlUB.cjs"),a=require("./plugins/auth.cjs"),o=require("./cachePlugin-XacR7ADG.cjs"),s=require("./plugins/circuit-breaker.cjs"),c=require("./plugins/concurrency.cjs"),l=require("./plugins/download.cjs"),u=require("./plugins/logger.cjs"),d=require("./plugins/opentelemetry.cjs"),f=require("./plugins/opentelemetry-metrics.cjs"),p=require("./rateLimitPlugin-D4to499s.cjs"),m=require("./plugins/retry.cjs"),h=require("./plugins/upload.cjs");require("./plugins.cjs"),exports.Client=n.n,exports.FetchAdapter=n.i,exports.IndexedDBCacheStore=o.r,exports.InterceptorManager=n.r,exports.MemoryCacheStore=o.i,exports.MockAdapter=r.t,exports.PluginError=i.t,exports.RequestError=e.t,exports.SchemaValidationError=t.b,exports.TieredCacheStore=o.n,exports.WebStorageCacheStore=o.a,exports.authPlugin=a.authPlugin,exports.cachePlugin=o.t,exports.circuitBreakerPlugin=s.circuitBreakerPlugin,exports.concurrencyPlugin=c.concurrencyPlugin,exports.createClient=n.t,exports.downloadPlugin=l.downloadPlugin,exports.isRequestError=e.n,exports.isSchemaValidationError=t.x,exports.loggerPlugin=u.loggerPlugin,exports.openTelemetryMetricsPlugin=f.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=d.openTelemetryPlugin,exports.rateLimitPlugin=p.t,exports.retryPlugin=m.retryPlugin,exports.uploadPlugin=h.uploadPlugin;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./errorResponseTimeout-CZWn7IpX.cjs"),n=require("./createClient-CXvspA_F.cjs"),r=require("./MockAdapter-BZwg5VWz.cjs"),i=require("./PluginError-DT3VnlUB.cjs"),a=require("./plugins/auth.cjs"),o=require("./cachePlugin-XacR7ADG.cjs"),s=require("./plugins/circuit-breaker.cjs"),c=require("./plugins/concurrency.cjs"),l=require("./plugins/download.cjs"),u=require("./plugins/logger.cjs"),d=require("./plugins/opentelemetry.cjs"),f=require("./plugins/opentelemetry-metrics.cjs"),p=require("./rateLimitPlugin-D4to499s.cjs"),m=require("./plugins/retry.cjs"),h=require("./plugins/upload.cjs");require("./plugins.cjs"),exports.Client=n.n,exports.FetchAdapter=n.i,exports.IndexedDBCacheStore=o.r,exports.InterceptorManager=n.r,exports.MemoryCacheStore=o.i,exports.MockAdapter=r.t,exports.PluginError=i.t,exports.RequestError=e.t,exports.SchemaValidationError=t.b,exports.TieredCacheStore=o.n,exports.WebStorageCacheStore=o.a,exports.authPlugin=a.authPlugin,exports.cachePlugin=o.t,exports.circuitBreakerPlugin=s.circuitBreakerPlugin,exports.concurrencyPlugin=c.concurrencyPlugin,exports.createClient=n.t,exports.downloadPlugin=l.downloadPlugin,exports.isRequestError=e.n,exports.isSchemaValidationError=t.x,exports.loggerPlugin=u.loggerPlugin,exports.openTelemetryMetricsPlugin=f.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=d.openTelemetryPlugin,exports.rateLimitPlugin=p.t,exports.retryPlugin=m.retryPlugin,exports.uploadPlugin=h.uploadPlugin;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{n as isRequestError,t as e}from"./RequestError-B0HIY1zK.js";import{b as t,x as isSchemaValidationError}from"./errorResponseTimeout-CLPv3sv8.js";import{i as n,n as r,r as i,t as createClient}from"./createClient-B5Oxq2Fj.js";import{t as a}from"./MockAdapter-zpaGJ9mM.js";import{t as o}from"./PluginError-CcuPSIRv.js";import{authPlugin}from"./plugins/auth.js";import{a as s,i as c,n as l,r as u,t as cachePlugin}from"./cachePlugin-JU-Rob4m.js";import{circuitBreakerPlugin}from"./plugins/circuit-breaker.js";import{concurrencyPlugin}from"./plugins/concurrency.js";import{downloadPlugin}from"./plugins/download.js";import{loggerPlugin}from"./plugins/logger.js";import{openTelemetryPlugin}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin}from"./plugins/opentelemetry-metrics.js";import{t as rateLimitPlugin}from"./rateLimitPlugin-C9CKjRyU.js";import{retryPlugin}from"./plugins/retry.js";import{uploadPlugin}from"./plugins/upload.js";import"./plugins.js";export{r as Client,n as FetchAdapter,u as IndexedDBCacheStore,i as InterceptorManager,c as MemoryCacheStore,a as MockAdapter,o as PluginError,e as RequestError,t as SchemaValidationError,l as TieredCacheStore,s as WebStorageCacheStore,authPlugin,cachePlugin,circuitBreakerPlugin,concurrencyPlugin,createClient,downloadPlugin,isRequestError,isSchemaValidationError,loggerPlugin,openTelemetryMetricsPlugin,openTelemetryPlugin,rateLimitPlugin,retryPlugin,uploadPlugin};
1
+ import{n as isRequestError,t as e}from"./RequestError-B0HIY1zK.js";import{b as t,x as isSchemaValidationError}from"./errorResponseTimeout-CLPv3sv8.js";import{i as n,n as r,r as i,t as createClient}from"./createClient-B5Oxq2Fj.js";import{t as a}from"./MockAdapter-DCnauo5Q.js";import{t as o}from"./PluginError-CcuPSIRv.js";import{authPlugin}from"./plugins/auth.js";import{a as s,i as c,n as l,r as u,t as cachePlugin}from"./cachePlugin-JU-Rob4m.js";import{circuitBreakerPlugin}from"./plugins/circuit-breaker.js";import{concurrencyPlugin}from"./plugins/concurrency.js";import{downloadPlugin}from"./plugins/download.js";import{loggerPlugin}from"./plugins/logger.js";import{openTelemetryPlugin}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin}from"./plugins/opentelemetry-metrics.js";import{t as rateLimitPlugin}from"./rateLimitPlugin-C9CKjRyU.js";import{retryPlugin}from"./plugins/retry.js";import{uploadPlugin}from"./plugins/upload.js";import"./plugins.js";export{r as Client,n as FetchAdapter,u as IndexedDBCacheStore,i as InterceptorManager,c as MemoryCacheStore,a as MockAdapter,o as PluginError,e as RequestError,t as SchemaValidationError,l as TieredCacheStore,s as WebStorageCacheStore,authPlugin,cachePlugin,circuitBreakerPlugin,concurrencyPlugin,createClient,downloadPlugin,isRequestError,isSchemaValidationError,loggerPlugin,openTelemetryMetricsPlugin,openTelemetryPlugin,rateLimitPlugin,retryPlugin,uploadPlugin};
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../RequestError-DrCr_lwO.cjs"),t=require("../isReadableStream-uWhOa7eR.cjs"),n=require("../waitForSignal-9c9DAqqS.cjs"),r=require("../isPromiseLike-B4LL7DlV.cjs"),i=require("../maxTimerDelay-NH5XeTXb.cjs"),a=require("../resolveExtensionConfig-D_eh4DjS.cjs"),o=[`GET`,`HEAD`,`OPTIONS`,`QUERY`,`PUT`,`DELETE`];function retryPlugin(e={}){let t=d(void 0,e);return{name:`retry`,install(e){let i=new WeakMap;e.hooks.onRetry((e,o)=>{if(!e.error)return;let l=i.get(e);if(!l){let n=a.t(e.config,`retry`);l=s(n,t),n&&i.set(e,l)}if(o>=l.retries||!C(e.config,l.methods))return;let u=E(l,e.error,o);if(r.t(u)){let t=Promise.resolve(u).then(t=>t?c(l,e.error,e.startTime,o):void 0);return e.config.signal?n.n(()=>t,e.config):t}if(!u)return;let d=c(l,e.error,e.startTime,o);return e.config.signal&&r.t(d)?n.n(()=>d,e.config):d})}}}function s(e,t){return e===void 0?t:typeof e==`number`?{...t,retries:h(e)}:{retries:e.retries===void 0?t.retries:h(e.retries),methods:e.methods===void 0?t.methods:f(e.methods),statusCodes:e.statusCodes===void 0?t.statusCodes:p(e.statusCodes),retryOnTimeout:e.retryOnTimeout??t.retryOnTimeout,delay:e.delay===void 0?t.delay:_(e.delay),respectRetryAfter:e.respectRetryAfter??t.respectRetryAfter,maxDelay:e.maxDelay===void 0?t.maxDelay:m(e.maxDelay),jitter:e.jitter??t.jitter,maxElapsedTime:e.maxElapsedTime===void 0?t.maxElapsedTime:g(e.maxElapsedTime),shouldRetry:e.shouldRetry??t.shouldRetry,onRetry:e.onRetry??t.onRetry}}function c(e,t,n,i){let a=e.delay(i,t);return r.t(a)?Promise.resolve(a).then(r=>l(e,t,n,i,r)):l(e,t,n,i,a)}function l(e,t,n,i,a){let o=e.respectRetryAfter?w(t):void 0;if(o!==void 0&&o>e.maxDelay)return;let s=y(o??a,e.maxDelay);if((o!==void 0||e.jitter===!1)&&e.maxElapsedTime===1/0&&!e.onRetry)return{retry:!0,delay:s};let c={attempt:i+1,delay:s,elapsedTime:Math.max(0,Date.now()-n),error:t},l=o===void 0?b(e.jitter,c):s;return r.t(l)?Promise.resolve(l).then(t=>u(e,c,t,n)):u(e,c,l,n)}function u(e,t,n,r){let i=y(n,e.maxDelay),a={...t,delay:i,elapsedTime:Math.max(0,Date.now()-r)};if(!(a.elapsedTime>=e.maxElapsedTime||a.elapsedTime+i>e.maxElapsedTime))return x(e.onRetry,a),{retry:!0,delay:i}}function d(e,t={}){return typeof e==`number`?{retries:h(e),methods:f(t.methods),statusCodes:p(t.statusCodes),retryOnTimeout:t.retryOnTimeout??!0,delay:_(t.delay),respectRetryAfter:t.respectRetryAfter??!0,maxDelay:m(t.maxDelay),jitter:t.jitter??!1,maxElapsedTime:g(t.maxElapsedTime),shouldRetry:t.shouldRetry,onRetry:t.onRetry}:{retries:h(e?.retries??t.retries??0),methods:f(e?.methods??t.methods),statusCodes:p(e?.statusCodes??t.statusCodes),retryOnTimeout:e?.retryOnTimeout??t.retryOnTimeout??!0,delay:_(e?.delay??t.delay),respectRetryAfter:e?.respectRetryAfter??t.respectRetryAfter??!0,maxDelay:m(e?.maxDelay??t.maxDelay),jitter:e?.jitter??t.jitter??!1,maxElapsedTime:g(e?.maxElapsedTime??t.maxElapsedTime),shouldRetry:e?.shouldRetry??t.shouldRetry,onRetry:e?.onRetry??t.onRetry}}function f(e){return new Set(e??o)}function p(e){return e?new Set(e):void 0}function m(e){return e===void 0?6e4:Number.isFinite(e)?Math.min(Math.max(0,e),i.t):e>0?i.t:0}function h(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function g(e){return e===void 0?1/0:Number.isFinite(e)?Math.max(0,e):e>0?1/0:0}function _(e){if(typeof e==`number`){let t=Math.max(0,e);return()=>t}return e??v}function v(e){return Math.min(100*2**e,1e3)}function y(e,t){return Number.isFinite(e)?Math.min(Math.max(0,e),t):e>0?t:0}function b(e,t){return e===!1?t.delay:e===!0?Math.random()*t.delay:e(t)}function x(e,t){if(e)try{let n=e(t);r.t(n)&&Promise.resolve(n).catch(S)}catch{}}function S(){}function C(e,n){let r=e.method??`GET`;return n.has(r)?!t.t(e.body):!1}function w(t){if(!e.n(t))return;let n=T(t.response?.headers);if(!n)return;let{value:r,allowTimestamp:i}=n;if(/^\d+$/.test(r)){let e=Number(r)*1e3;return i&&e>=Date.parse(`2024-01-01T00:00:00Z`)&&(e-=Date.now()),Math.max(0,e)}if(!r.includes(`:`)||!/^(Mo|T[uh]|We|Fr|S[au])/.test(r))return;let a=Date.parse(r);if(!Number.isNaN(a))return Math.max(0,a-Date.now())}function T(e){if(!e)return;let t=e.get(`retry-after`);if(t!==null)return{value:t,allowTimestamp:!1};let n=e.get(`ratelimit-reset`);if(n!==null)return{value:n,allowTimestamp:!0};let r=e.get(`x-ratelimit-retry-after`);if(r!==null)return{value:r,allowTimestamp:!1};let i=e.get(`x-ratelimit-reset`)??e.get(`x-rate-limit-reset`);return i===null?void 0:{value:i,allowTimestamp:!0}}function E(e,t,n){let i=e.shouldRetry?.(t,n);return r.t(i)?Promise.resolve(i).then(n=>n??D(t,e)):i??D(t,e)}function D(t,n){return e.n(t)?t.code===`NETWORK_ERROR`?!0:t.code===`TIMEOUT_ERROR`?n.retryOnTimeout:t.status===void 0?!1:t.status===413?O(413,n)&&w(t)!==void 0:O(t.status,n):!1}function O(e,t){return t.statusCodes?t.statusCodes.has(e):e===408||e===413||e===425||e===429||e>=500}exports.retryPlugin=retryPlugin;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../RequestError-DrCr_lwO.cjs"),t=require("../isReadableStream-uWhOa7eR.cjs"),n=require("../waitForSignal-9c9DAqqS.cjs"),r=require("../isPromiseLike-B4LL7DlV.cjs"),i=require("../maxTimerDelay-NH5XeTXb.cjs"),a=require("../resolveExtensionConfig-D_eh4DjS.cjs"),o=[`GET`,`HEAD`,`OPTIONS`,`QUERY`,`PUT`,`DELETE`];function retryPlugin(e={}){let t=d(void 0,e);return{name:`retry`,install(e){let i=new WeakMap;e.hooks.onRetry((e,o)=>{if(!e.error)return;let l=i.get(e);if(!l){let n=a.t(e.config,`retry`);l=s(n,t),n&&i.set(e,l)}if(o>=l.retries||!C(e.config,l.methods))return;let u=E(l,e.error,o);if(r.t(u)){let t=Promise.resolve(u).then(t=>(n.i(e.config),t?c(l,e.error,e.startTime,o,e.config):void 0));return e.config.signal?n.n(()=>t,e.config):t}if(!u)return;let d=c(l,e.error,e.startTime,o,e.config);return e.config.signal&&r.t(d)?n.n(()=>d,e.config):d})}}}function s(e,t){return e===void 0?t:typeof e==`number`?{...t,retries:h(e)}:{retries:e.retries===void 0?t.retries:h(e.retries),methods:e.methods===void 0?t.methods:f(e.methods),statusCodes:e.statusCodes===void 0?t.statusCodes:p(e.statusCodes),retryOnTimeout:e.retryOnTimeout??t.retryOnTimeout,delay:e.delay===void 0?t.delay:_(e.delay),respectRetryAfter:e.respectRetryAfter??t.respectRetryAfter,maxDelay:e.maxDelay===void 0?t.maxDelay:m(e.maxDelay),jitter:e.jitter??t.jitter,maxElapsedTime:e.maxElapsedTime===void 0?t.maxElapsedTime:g(e.maxElapsedTime),shouldRetry:e.shouldRetry??t.shouldRetry,onRetry:e.onRetry??t.onRetry}}function c(e,t,i,a,o){n.i(o);let s=e.delay(a,t);return r.t(s)?Promise.resolve(s).then(n=>l(e,t,i,a,n,o)):l(e,t,i,a,s,o)}function l(e,t,i,a,o,s){n.i(s);let c=e.respectRetryAfter?w(t):void 0;if(c!==void 0&&c>e.maxDelay)return;let l=y(c??o,e.maxDelay);if((c!==void 0||e.jitter===!1)&&e.maxElapsedTime===1/0&&!e.onRetry)return{retry:!0,delay:l};let d={attempt:a+1,delay:l,elapsedTime:Math.max(0,Date.now()-i),error:t},f=c===void 0?b(e.jitter,d):l;return r.t(f)?Promise.resolve(f).then(t=>u(e,d,t,i,s)):u(e,d,f,i,s)}function u(e,t,r,i,a){n.i(a);let o=y(r,e.maxDelay),s={...t,delay:o,elapsedTime:Math.max(0,Date.now()-i)};if(!(s.elapsedTime>=e.maxElapsedTime||s.elapsedTime+o>e.maxElapsedTime))return x(e.onRetry,s),{retry:!0,delay:o}}function d(e,t={}){return typeof e==`number`?{retries:h(e),methods:f(t.methods),statusCodes:p(t.statusCodes),retryOnTimeout:t.retryOnTimeout??!0,delay:_(t.delay),respectRetryAfter:t.respectRetryAfter??!0,maxDelay:m(t.maxDelay),jitter:t.jitter??!1,maxElapsedTime:g(t.maxElapsedTime),shouldRetry:t.shouldRetry,onRetry:t.onRetry}:{retries:h(e?.retries??t.retries??0),methods:f(e?.methods??t.methods),statusCodes:p(e?.statusCodes??t.statusCodes),retryOnTimeout:e?.retryOnTimeout??t.retryOnTimeout??!0,delay:_(e?.delay??t.delay),respectRetryAfter:e?.respectRetryAfter??t.respectRetryAfter??!0,maxDelay:m(e?.maxDelay??t.maxDelay),jitter:e?.jitter??t.jitter??!1,maxElapsedTime:g(e?.maxElapsedTime??t.maxElapsedTime),shouldRetry:e?.shouldRetry??t.shouldRetry,onRetry:e?.onRetry??t.onRetry}}function f(e){return new Set(e??o)}function p(e){return e?new Set(e):void 0}function m(e){return e===void 0?6e4:Number.isFinite(e)?Math.min(Math.max(0,e),i.t):e>0?i.t:0}function h(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function g(e){return e===void 0?1/0:Number.isFinite(e)?Math.max(0,e):e>0?1/0:0}function _(e){if(typeof e==`number`){let t=Math.max(0,e);return()=>t}return e??v}function v(e){return Math.min(100*2**e,1e3)}function y(e,t){return Number.isFinite(e)?Math.min(Math.max(0,e),t):e>0?t:0}function b(e,t){return e===!1?t.delay:e===!0?Math.random()*t.delay:e(t)}function x(e,t){if(e)try{let n=e(t);r.t(n)&&Promise.resolve(n).catch(S)}catch{}}function S(){}function C(e,n){let r=e.method??`GET`;return n.has(r)?!t.t(e.body):!1}function w(t){if(!e.n(t))return;let n=T(t.response?.headers);if(!n)return;let{value:r,allowTimestamp:i}=n;if(/^\d+$/.test(r)){let e=Number(r)*1e3;return i&&e>=Date.parse(`2024-01-01T00:00:00Z`)&&(e-=Date.now()),Math.max(0,e)}if(!r.includes(`:`)||!/^(Mo|T[uh]|We|Fr|S[au])/.test(r))return;let a=Date.parse(r);if(!Number.isNaN(a))return Math.max(0,a-Date.now())}function T(e){if(!e)return;let t=e.get(`retry-after`);if(t!==null)return{value:t,allowTimestamp:!1};let n=e.get(`ratelimit-reset`);if(n!==null)return{value:n,allowTimestamp:!0};let r=e.get(`x-ratelimit-retry-after`);if(r!==null)return{value:r,allowTimestamp:!1};let i=e.get(`x-ratelimit-reset`)??e.get(`x-rate-limit-reset`);return i===null?void 0:{value:i,allowTimestamp:!0}}function E(e,t,n){let i=e.shouldRetry?.(t,n);return r.t(i)?Promise.resolve(i).then(n=>n??D(t,e)):i??D(t,e)}function D(t,n){return e.n(t)?t.code===`NETWORK_ERROR`?!0:t.code===`TIMEOUT_ERROR`?n.retryOnTimeout:t.status===void 0?!1:t.status===413?O(413,n)&&w(t)!==void 0:O(t.status,n):!1}function O(e,t){return t.statusCodes?t.statusCodes.has(e):e===408||e===413||e===425||e===429||e>=500}exports.retryPlugin=retryPlugin;
@@ -1 +1 @@
1
- import{n as isRequestError}from"../RequestError-B0HIY1zK.js";import{t as e}from"../isReadableStream-DBMPCr6B.js";import{n as t}from"../waitForSignal-DXgmbuoa.js";import{t as n}from"../isPromiseLike-B6ok3Q-C.js";import{t as r}from"../maxTimerDelay-Hn7X0Wuh.js";import{t as i}from"../resolveExtensionConfig-C_MshvkE.js";const a=[`GET`,`HEAD`,`OPTIONS`,`QUERY`,`PUT`,`DELETE`];function retryPlugin(e={}){let r=u(void 0,e);return{name:`retry`,install(e){let a=new WeakMap;e.hooks.onRetry((e,c)=>{if(!e.error)return;let l=a.get(e);if(!l){let t=i(e.config,`retry`);l=o(t,r),t&&a.set(e,l)}if(c>=l.retries||!S(e.config,l.methods))return;let u=T(l,e.error,c);if(n(u)){let n=Promise.resolve(u).then(t=>t?s(l,e.error,e.startTime,c):void 0);return e.config.signal?t(()=>n,e.config):n}if(!u)return;let d=s(l,e.error,e.startTime,c);return e.config.signal&&n(d)?t(()=>d,e.config):d})}}}function o(e,t){return e===void 0?t:typeof e==`number`?{...t,retries:m(e)}:{retries:e.retries===void 0?t.retries:m(e.retries),methods:e.methods===void 0?t.methods:d(e.methods),statusCodes:e.statusCodes===void 0?t.statusCodes:f(e.statusCodes),retryOnTimeout:e.retryOnTimeout??t.retryOnTimeout,delay:e.delay===void 0?t.delay:g(e.delay),respectRetryAfter:e.respectRetryAfter??t.respectRetryAfter,maxDelay:e.maxDelay===void 0?t.maxDelay:p(e.maxDelay),jitter:e.jitter??t.jitter,maxElapsedTime:e.maxElapsedTime===void 0?t.maxElapsedTime:h(e.maxElapsedTime),shouldRetry:e.shouldRetry??t.shouldRetry,onRetry:e.onRetry??t.onRetry}}function s(e,t,r,i){let a=e.delay(i,t);return n(a)?Promise.resolve(a).then(n=>c(e,t,r,i,n)):c(e,t,r,i,a)}function c(e,t,r,i,a){let o=e.respectRetryAfter?C(t):void 0;if(o!==void 0&&o>e.maxDelay)return;let s=v(o??a,e.maxDelay);if((o!==void 0||e.jitter===!1)&&e.maxElapsedTime===1/0&&!e.onRetry)return{retry:!0,delay:s};let c={attempt:i+1,delay:s,elapsedTime:Math.max(0,Date.now()-r),error:t},u=o===void 0?y(e.jitter,c):s;return n(u)?Promise.resolve(u).then(t=>l(e,c,t,r)):l(e,c,u,r)}function l(e,t,n,r){let i=v(n,e.maxDelay),a={...t,delay:i,elapsedTime:Math.max(0,Date.now()-r)};if(!(a.elapsedTime>=e.maxElapsedTime||a.elapsedTime+i>e.maxElapsedTime))return b(e.onRetry,a),{retry:!0,delay:i}}function u(e,t={}){return typeof e==`number`?{retries:m(e),methods:d(t.methods),statusCodes:f(t.statusCodes),retryOnTimeout:t.retryOnTimeout??!0,delay:g(t.delay),respectRetryAfter:t.respectRetryAfter??!0,maxDelay:p(t.maxDelay),jitter:t.jitter??!1,maxElapsedTime:h(t.maxElapsedTime),shouldRetry:t.shouldRetry,onRetry:t.onRetry}:{retries:m(e?.retries??t.retries??0),methods:d(e?.methods??t.methods),statusCodes:f(e?.statusCodes??t.statusCodes),retryOnTimeout:e?.retryOnTimeout??t.retryOnTimeout??!0,delay:g(e?.delay??t.delay),respectRetryAfter:e?.respectRetryAfter??t.respectRetryAfter??!0,maxDelay:p(e?.maxDelay??t.maxDelay),jitter:e?.jitter??t.jitter??!1,maxElapsedTime:h(e?.maxElapsedTime??t.maxElapsedTime),shouldRetry:e?.shouldRetry??t.shouldRetry,onRetry:e?.onRetry??t.onRetry}}function d(e){return new Set(e??a)}function f(e){return e?new Set(e):void 0}function p(e){return e===void 0?6e4:Number.isFinite(e)?Math.min(Math.max(0,e),r):e>0?r:0}function m(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function h(e){return e===void 0?1/0:Number.isFinite(e)?Math.max(0,e):e>0?1/0:0}function g(e){if(typeof e==`number`){let t=Math.max(0,e);return()=>t}return e??_}function _(e){return Math.min(100*2**e,1e3)}function v(e,t){return Number.isFinite(e)?Math.min(Math.max(0,e),t):e>0?t:0}function y(e,t){return e===!1?t.delay:e===!0?Math.random()*t.delay:e(t)}function b(e,t){if(e)try{let r=e(t);n(r)&&Promise.resolve(r).catch(x)}catch{}}function x(){}function S(t,n){let r=t.method??`GET`;return n.has(r)?!e(t.body):!1}function C(e){if(!isRequestError(e))return;let t=w(e.response?.headers);if(!t)return;let{value:n,allowTimestamp:r}=t;if(/^\d+$/.test(n)){let e=Number(n)*1e3;return r&&e>=Date.parse(`2024-01-01T00:00:00Z`)&&(e-=Date.now()),Math.max(0,e)}if(!n.includes(`:`)||!/^(Mo|T[uh]|We|Fr|S[au])/.test(n))return;let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}function w(e){if(!e)return;let t=e.get(`retry-after`);if(t!==null)return{value:t,allowTimestamp:!1};let n=e.get(`ratelimit-reset`);if(n!==null)return{value:n,allowTimestamp:!0};let r=e.get(`x-ratelimit-retry-after`);if(r!==null)return{value:r,allowTimestamp:!1};let i=e.get(`x-ratelimit-reset`)??e.get(`x-rate-limit-reset`);return i===null?void 0:{value:i,allowTimestamp:!0}}function T(e,t,r){let i=e.shouldRetry?.(t,r);return n(i)?Promise.resolve(i).then(n=>n??E(t,e)):i??E(t,e)}function E(e,t){return isRequestError(e)?e.code===`NETWORK_ERROR`?!0:e.code===`TIMEOUT_ERROR`?t.retryOnTimeout:e.status===void 0?!1:e.status===413?D(413,t)&&C(e)!==void 0:D(e.status,t):!1}function D(e,t){return t.statusCodes?t.statusCodes.has(e):e===408||e===413||e===425||e===429||e>=500}export{retryPlugin};
1
+ import{n as isRequestError}from"../RequestError-B0HIY1zK.js";import{t as e}from"../isReadableStream-DBMPCr6B.js";import{i as t,n}from"../waitForSignal-DXgmbuoa.js";import{t as r}from"../isPromiseLike-B6ok3Q-C.js";import{t as i}from"../maxTimerDelay-Hn7X0Wuh.js";import{t as a}from"../resolveExtensionConfig-C_MshvkE.js";const o=[`GET`,`HEAD`,`OPTIONS`,`QUERY`,`PUT`,`DELETE`];function retryPlugin(e={}){let i=d(void 0,e);return{name:`retry`,install(e){let o=new WeakMap;e.hooks.onRetry((e,l)=>{if(!e.error)return;let u=o.get(e);if(!u){let t=a(e.config,`retry`);u=s(t,i),t&&o.set(e,u)}if(l>=u.retries||!C(e.config,u.methods))return;let d=E(u,e.error,l);if(r(d)){let r=Promise.resolve(d).then(n=>(t(e.config),n?c(u,e.error,e.startTime,l,e.config):void 0));return e.config.signal?n(()=>r,e.config):r}if(!d)return;let f=c(u,e.error,e.startTime,l,e.config);return e.config.signal&&r(f)?n(()=>f,e.config):f})}}}function s(e,t){return e===void 0?t:typeof e==`number`?{...t,retries:h(e)}:{retries:e.retries===void 0?t.retries:h(e.retries),methods:e.methods===void 0?t.methods:f(e.methods),statusCodes:e.statusCodes===void 0?t.statusCodes:p(e.statusCodes),retryOnTimeout:e.retryOnTimeout??t.retryOnTimeout,delay:e.delay===void 0?t.delay:_(e.delay),respectRetryAfter:e.respectRetryAfter??t.respectRetryAfter,maxDelay:e.maxDelay===void 0?t.maxDelay:m(e.maxDelay),jitter:e.jitter??t.jitter,maxElapsedTime:e.maxElapsedTime===void 0?t.maxElapsedTime:g(e.maxElapsedTime),shouldRetry:e.shouldRetry??t.shouldRetry,onRetry:e.onRetry??t.onRetry}}function c(e,n,i,a,o){t(o);let s=e.delay(a,n);return r(s)?Promise.resolve(s).then(t=>l(e,n,i,a,t,o)):l(e,n,i,a,s,o)}function l(e,n,i,a,o,s){t(s);let c=e.respectRetryAfter?w(n):void 0;if(c!==void 0&&c>e.maxDelay)return;let l=y(c??o,e.maxDelay);if((c!==void 0||e.jitter===!1)&&e.maxElapsedTime===1/0&&!e.onRetry)return{retry:!0,delay:l};let d={attempt:a+1,delay:l,elapsedTime:Math.max(0,Date.now()-i),error:n},f=c===void 0?b(e.jitter,d):l;return r(f)?Promise.resolve(f).then(t=>u(e,d,t,i,s)):u(e,d,f,i,s)}function u(e,n,r,i,a){t(a);let o=y(r,e.maxDelay),s={...n,delay:o,elapsedTime:Math.max(0,Date.now()-i)};if(!(s.elapsedTime>=e.maxElapsedTime||s.elapsedTime+o>e.maxElapsedTime))return x(e.onRetry,s),{retry:!0,delay:o}}function d(e,t={}){return typeof e==`number`?{retries:h(e),methods:f(t.methods),statusCodes:p(t.statusCodes),retryOnTimeout:t.retryOnTimeout??!0,delay:_(t.delay),respectRetryAfter:t.respectRetryAfter??!0,maxDelay:m(t.maxDelay),jitter:t.jitter??!1,maxElapsedTime:g(t.maxElapsedTime),shouldRetry:t.shouldRetry,onRetry:t.onRetry}:{retries:h(e?.retries??t.retries??0),methods:f(e?.methods??t.methods),statusCodes:p(e?.statusCodes??t.statusCodes),retryOnTimeout:e?.retryOnTimeout??t.retryOnTimeout??!0,delay:_(e?.delay??t.delay),respectRetryAfter:e?.respectRetryAfter??t.respectRetryAfter??!0,maxDelay:m(e?.maxDelay??t.maxDelay),jitter:e?.jitter??t.jitter??!1,maxElapsedTime:g(e?.maxElapsedTime??t.maxElapsedTime),shouldRetry:e?.shouldRetry??t.shouldRetry,onRetry:e?.onRetry??t.onRetry}}function f(e){return new Set(e??o)}function p(e){return e?new Set(e):void 0}function m(e){return e===void 0?6e4:Number.isFinite(e)?Math.min(Math.max(0,e),i):e>0?i:0}function h(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function g(e){return e===void 0?1/0:Number.isFinite(e)?Math.max(0,e):e>0?1/0:0}function _(e){if(typeof e==`number`){let t=Math.max(0,e);return()=>t}return e??v}function v(e){return Math.min(100*2**e,1e3)}function y(e,t){return Number.isFinite(e)?Math.min(Math.max(0,e),t):e>0?t:0}function b(e,t){return e===!1?t.delay:e===!0?Math.random()*t.delay:e(t)}function x(e,t){if(e)try{let n=e(t);r(n)&&Promise.resolve(n).catch(S)}catch{}}function S(){}function C(t,n){let r=t.method??`GET`;return n.has(r)?!e(t.body):!1}function w(e){if(!isRequestError(e))return;let t=T(e.response?.headers);if(!t)return;let{value:n,allowTimestamp:r}=t;if(/^\d+$/.test(n)){let e=Number(n)*1e3;return r&&e>=Date.parse(`2024-01-01T00:00:00Z`)&&(e-=Date.now()),Math.max(0,e)}if(!n.includes(`:`)||!/^(Mo|T[uh]|We|Fr|S[au])/.test(n))return;let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}function T(e){if(!e)return;let t=e.get(`retry-after`);if(t!==null)return{value:t,allowTimestamp:!1};let n=e.get(`ratelimit-reset`);if(n!==null)return{value:n,allowTimestamp:!0};let r=e.get(`x-ratelimit-retry-after`);if(r!==null)return{value:r,allowTimestamp:!1};let i=e.get(`x-ratelimit-reset`)??e.get(`x-rate-limit-reset`);return i===null?void 0:{value:i,allowTimestamp:!0}}function E(e,t,n){let i=e.shouldRetry?.(t,n);return r(i)?Promise.resolve(i).then(n=>n??D(t,e)):i??D(t,e)}function D(e,t){return isRequestError(e)?e.code===`NETWORK_ERROR`?!0:e.code===`TIMEOUT_ERROR`?t.retryOnTimeout:e.status===void 0?!1:e.status===413?O(413,t)&&w(e)!==void 0:O(e.status,t):!1}function O(e,t){return t.statusCodes?t.statusCodes.has(e):e===408||e===413||e===425||e===429||e>=500}export{retryPlugin};
package/dist/testing.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./MockAdapter-DlW19YXg.cjs");exports.MockAdapter=e.t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./MockAdapter-BZwg5VWz.cjs");exports.MockAdapter=e.t;
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- export{t as MockAdapter}from"./MockAdapter-zpaGJ9mM.js";
1
+ export{t as MockAdapter}from"./MockAdapter-DCnauo5Q.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.22.0",
3
+ "version": "1.22.2",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",
@@ -1,2 +0,0 @@
1
- const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-DNjjEzFS.cjs"),n=require("./validateResponseStatus-6FKeKyEV.cjs"),r=require("./isReadableStream-uWhOa7eR.cjs"),i=require("./isPromiseLike-B4LL7DlV.cjs"),a=require("./maxTimerDelay-NH5XeTXb.cjs");var MockRecorder=class{constructor(e){if(this.entries=new Map,this.skipped=0,this.sequence=0,this.generation=0,!e||typeof e.adapter?.request!=`function`)throw TypeError(`Mock recording requires an adapter`);if(this.maxEntries=s(e.maxEntries,100),this.maxRecordSize=s(e.maxRecordSize,262144),e.transform!==void 0&&typeof e.transform!=`function`)throw TypeError(`Mock recording transform must be a function`);this.adapter=e.adapter,this.transform=e.transform}get recordings(){return[...this.entries].sort(([e],[t])=>e-t).map(([,e])=>JSON.parse(e))}get stats(){return{recorded:this.entries.size,skipped:this.skipped}}clear(){this.generation++,this.entries.clear(),this.skipped=0}exportMocks(){return this.recordings.map(({method:e,matcher:t,response:n})=>{let r=t.searchParams?`, searchParams: new URLSearchParams(${d(t.searchParams)})`:``,i=`{ url: ${d(t.url)}${t.query?`, query: JSON.parse(${d(JSON.stringify(t.query))})`:``}${r} }`,a=n.data===void 0?`undefined`:`JSON.parse(${d(JSON.stringify(n.data))})`,o=JSON.stringify({headers:n.headers,statusText:n.statusText});return`mock.onMethod(${d(e)}, ${i}).replyOnce(${n.status}, ${a}, JSON.parse(${d(o)}));`}).join(`
2
- `)}async request(t){let n=this.generation,r;try{r={id:this.sequence++,generation:n,method:t.method??`GET`,matcher:l(t,this.maxRecordSize)}}catch{this.skipped++}let i;try{i=await this.adapter.request(t)}catch(t){if(r&&n===this.generation)try{e.n(t)&&t.code===`HTTP_ERROR`&&t.response?this.record(r,t.response):this.skipped++}catch{this.skipped++}throw t}return r&&this.record(r,i),i}record(e,t){if(e.generation===this.generation)try{let n=Object.fromEntries([...t.headers].filter(([e])=>!c(e)&&!/^(content-length|content-encoding|transfer-encoding)$/i.test(e))),r={method:e.method,matcher:e.matcher,response:{status:t.status,statusText:t.statusText,headers:n}};t.data!==void 0&&(r.response.data=u(t.data,this.maxRecordSize));let a=this.transform?this.transform(r):r;if(i.t(a)){Promise.resolve(a).catch(()=>{}),e.generation===this.generation&&this.skipped++;return}if(e.generation!==this.generation)return;if(!a){this.skipped++;return}let s=u(a,this.maxRecordSize);o(s);let l=JSON.stringify(s);if(e.generation!==this.generation)return;this.entries.set(e.id,l),this.entries.size>this.maxEntries&&this.entries.delete([...this.entries.keys()].reduce((e,t)=>Math.min(e,t)))}catch{e.generation===this.generation&&this.skipped++}}};function o(e){if(![`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`QUERY`].includes(e.method)||typeof e.matcher?.url!=`string`||!Number.isInteger(e.response?.status)||e.response.status<200||e.response.status>599||typeof e.response.statusText!=`string`)throw TypeError(`Invalid recording`);if(l({...e.matcher,searchParams:e.matcher.searchParams?new URLSearchParams(e.matcher.searchParams):void 0},2**53-1),!e.response.headers||Object.values(e.response.headers).some(e=>typeof e!=`string`))throw TypeError(`Invalid recorded headers`);new Headers(e.response.headers)}function s(e,t){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<=0)throw TypeError(`Mock recording limits must be positive safe integers`);return e}function c(e){return/^(?:authorization|proxyauthorization|cookie|setcookie|password|passwd|secret|token|accesstoken|refreshtoken|apikey|xapikey|clientsecret|sessionid|csrftoken|xcsrftoken|xsrftoken|xxsrftoken|xauthtoken)$/i.test(e.replace(/[-_]/g,``))}function l(e,t){let n=String(e.url);if(/^(?:[a-z][a-z\d+.-]*:)?\/\/[^/?#]*@/i.test(n))throw TypeError(`Credential URL`);if(n.includes(`#`))throw TypeError(`Fragment URL`);let r=n.indexOf(`?`);if(r!==-1){let e=new URLSearchParams(n.slice(r+1).split(`#`,1)[0]);for(let t of e.keys())if(c(t))throw TypeError(`Sensitive URL query`)}let i={url:n};if(e.query){for(let t of Object.keys(e.query))if(c(t))throw TypeError(`Sensitive query`);i.query=u(Object.fromEntries(Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>[e,Array.isArray(t)?t.filter(e=>e!==void 0):t])),t)}if(e.searchParams){for(let t of e.searchParams.keys())if(c(t))throw TypeError(`Sensitive searchParams`);i.searchParams=[...e.searchParams]}return u(i,t)}function u(e,t){let n=new Set,r=new TextEncoder,i=t,a=e=>{if(e.length>i||(i-=r.encode(e).byteLength,i<0))throw TypeError(`Recording too large`)},o=(e,t)=>{if(t>64)throw TypeError(`Recording too deep`);if(e===null||typeof e==`boolean`)return a(String(e)),e;if(typeof e==`string`){if(e.length>i)throw TypeError(`Recording too large`);return a(JSON.stringify(e)),e}if(typeof e==`number`&&Number.isFinite(e)&&!Object.is(e,-0))return a(String(e)),e;if(typeof e!=`object`||n.has(e))throw TypeError(`Non-JSON recording`);let r=Array.isArray(e);if(!r&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Non-JSON recording`);if(Object.getOwnPropertySymbols(e).length)throw TypeError(`Symbol recording`);n.add(e),a(`[]`);let s=r?[]:Object.create(null),l=Object.keys(e);if(l.length>i/2)throw TypeError(`Recording too large`);for(let n of l){let l=Object.getOwnPropertyDescriptor(e,n);if(n.length>i)throw TypeError(`Recording too large`);if(!(`value`in l))throw TypeError(`Accessor recording`);if(r&&!/^(0|[1-9]\d*)$/.test(n))throw TypeError(`Non-JSON array`);a(`,`),r||a(`${JSON.stringify(n)}:`);let u=c(n)?`[REDACTED]`:l.value,d=o(u,t+1);r?s.push(d):s[n]=d}if(r&&s.length!==e.length)throw TypeError(`Sparse recording`);return n.delete(e),s};return o(e,0)}function d(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var MockAdapter=class{constructor(e={}){this.handlers=new Map,this.rules=[],this.requests=[],this.delay=T(e.delay),this.recorder=e.record===void 0?void 0:new MockRecorder(e.record),Object.entries(e.handlers??{}).forEach(([e,t])=>{this.handlers.set(e,t)})}get history(){return[...this.requests]}get recordings(){return this.recorder?.recordings??[]}get recordingStats(){return this.recorder?.stats??{recorded:0,skipped:0}}exportMocks(){return this.recorder?.exportMocks()??``}clearRecordings(){return this.recorder?.clear(),this}on(e,t){return this.handlers.set(e,t),this}onMethod(e,t){let n=f(t);return new RouteBuilder({reply:(t,r,i,a)=>this.registerReply(e,n,t,r,i,a),error:(t,r,i)=>this.registerError(e,n,t,r,i)})}onGet(e){return this.onMethod(`GET`,e)}onPost(e){return this.onMethod(`POST`,e)}onPut(e){return this.onMethod(`PUT`,e)}onPatch(e){return this.onMethod(`PATCH`,e)}onDelete(e){return this.onMethod(`DELETE`,e)}onHead(e){return this.onMethod(`HEAD`,e)}onOptions(e){return this.onMethod(`OPTIONS`,e)}resetHistory(){return this.requests.length=0,this}resetHandlers(){return this.handlers.clear(),this.rules.length=0,this}reset(){return this.resetHandlers().resetHistory().clearRecordings()}async request(e){this.requests.push(e);let t=e.method??`GET`,n=this.rules.findIndex(n=>(n.method===void 0||n.method===t)&&p(n.matcher,e));if(n!==-1){let t=this.rules[n];return t.once&&this.rules.splice(n,1),b(await t.respond(e),e)}let r=this.handlers.get(String(e.url));if(!r){if(this.recorder)return this.recorder.request(e);throw Error(`No mock handler found for ${e.url} (${t})`)}return await E(this.delay,e),b(y(e,{status:200,statusText:`OK`,data:await r(e)}),e)}registerReply(e,t,n,r,i,a={}){let o=typeof r==`function`?r:()=>({status:r,data:i,...a});return this.rules.push({method:e,matcher:t,once:n,respond:async e=>{let t=await o(e);return await E(T(t.delay??this.delay),e),y(e,t)}}),this}registerError(t,n,r,i,a){return this.rules.push({method:t,matcher:n,once:r,respond:async t=>{throw await E(this.delay,t),new e.t(a,{code:i,config:t})}}),this}},RouteBuilder=class{constructor(e){this.registrar=e}reply(e,t,n={}){return this.registrar.reply(!1,e,t,n)}replyOnce(e,t,n={}){return this.registrar.reply(!0,e,t,n)}networkError(e=`Mock network error`){return this.registrar.error(!1,`NETWORK_ERROR`,e)}networkErrorOnce(e=`Mock network error`){return this.registrar.error(!0,`NETWORK_ERROR`,e)}timeout(e=`Mock request timeout`){return this.registrar.error(!1,`TIMEOUT_ERROR`,e)}timeoutOnce(e=`Mock request timeout`){return this.registrar.error(!0,`TIMEOUT_ERROR`,e)}};function f(e){return typeof e==`string`||e instanceof RegExp?{url:e}:e}function p(e,t){return m(e.url,String(t.url))&&h(e.query,t.query)&&_(e.searchParams,t.searchParams)&&v(e.headers,t.headers)}function m(e,t){return typeof e==`string`?e===t:(e.lastIndex=0,e.test(t))}function h(e,t){return!e||g(e)===g(t)}function g(e){if(!e)return`[]`;let t=[];for(let n of Object.keys(e).sort()){let r=e[n],i=Array.isArray(r)?r:[r];for(let e of i)e!==void 0&&t.push([n,e===null?``:String(e)])}return JSON.stringify(t)}function _(e,t){return!e||JSON.stringify([...e.entries()])===JSON.stringify([...t?.entries()??[]])}function v(e,t){if(!e)return!0;let n=new Headers(e),r=new Headers(t);for(let[e,t]of n.entries())if(r.get(e)!==t)return!1;return!0}function y(e,t){let n=new Headers(t.headers),r=C(t.data,n,t.status),i=t.statusText??x(t.status),a=new Response(r,{status:t.status,statusText:i,headers:n});return{data:t.data,status:t.status,statusText:i,headers:a.headers,config:e,raw:a}}function b(t,r){if(!n.t(t.status,r))throw new e.t(t.statusText||`Mock request failed`,{code:`HTTP_ERROR`,response:t});return t}function x(e){return S[e]??``}const S={200:`OK`,201:`Created`,202:`Accepted`,204:`No Content`,400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,408:`Request Timeout`,409:`Conflict`,422:`Unprocessable Content`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`};function C(e,t,r){return e==null||n.n(void 0,r)?null:typeof e==`string`||w(e)?e:(t.has(`content-type`)||t.set(`content-type`,`application/json`),JSON.stringify(e))}function w(e){return t.n(e)||n.r(e)||t.r(e)||r.t(e)||t.t(e)||ArrayBuffer.isView(e)}function T(e){return Number.isFinite(e)?Math.min(Math.max(0,e??0),a.t):e&&e>0?a.t:0}function E(t,n){let r=n.signal;if(r?.aborted)return Promise.reject(D(r.reason,n));let i=n.timeout&&n.timeout>0?n.timeout:void 0,a=i!==void 0&&i<=t,o=a?i:t;return o<=0?Promise.resolve():new Promise((t,s)=>{let c,l=!1,u=()=>{c!==void 0&&(clearTimeout(c),c=void 0);try{r?.removeEventListener(`abort`,f)}catch{}},d=e=>{l||(l=!0,u(),s(e))},f=()=>{d(D(r?.reason,n))};try{r?.addEventListener(`abort`,f,{once:!0})}catch(e){d(e);return}if(r?.aborted&&f(),!l)try{c=setTimeout(()=>{a?d(new e.t(`Request timeout after ${i}ms`,{code:`TIMEOUT_ERROR`,config:n})):(l=!0,u(),t())},o)}catch(e){d(e)}})}function D(t,n){return new e.t(`Mock request aborted`,{code:`ABORT_ERROR`,config:n,cause:t})}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return MockAdapter}});
@@ -1,2 +0,0 @@
1
- import{n as isRequestError,t as e}from"./RequestError-B0HIY1zK.js";import{n as t,r as n,t as r}from"./isBinaryBody-D-Wp2IPk.js";import{n as i,r as a,t as o}from"./validateResponseStatus-BzkEtZZi.js";import{t as s}from"./isReadableStream-DBMPCr6B.js";import{t as c}from"./isPromiseLike-B6ok3Q-C.js";import{t as l}from"./maxTimerDelay-Hn7X0Wuh.js";var MockRecorder=class{constructor(e){if(this.entries=new Map,this.skipped=0,this.sequence=0,this.generation=0,!e||typeof e.adapter?.request!=`function`)throw TypeError(`Mock recording requires an adapter`);if(this.maxEntries=d(e.maxEntries,100),this.maxRecordSize=d(e.maxRecordSize,262144),e.transform!==void 0&&typeof e.transform!=`function`)throw TypeError(`Mock recording transform must be a function`);this.adapter=e.adapter,this.transform=e.transform}get recordings(){return[...this.entries].sort(([e],[t])=>e-t).map(([,e])=>JSON.parse(e))}get stats(){return{recorded:this.entries.size,skipped:this.skipped}}clear(){this.generation++,this.entries.clear(),this.skipped=0}exportMocks(){return this.recordings.map(({method:e,matcher:t,response:n})=>{let r=t.searchParams?`, searchParams: new URLSearchParams(${h(t.searchParams)})`:``,i=`{ url: ${h(t.url)}${t.query?`, query: JSON.parse(${h(JSON.stringify(t.query))})`:``}${r} }`,a=n.data===void 0?`undefined`:`JSON.parse(${h(JSON.stringify(n.data))})`,o=JSON.stringify({headers:n.headers,statusText:n.statusText});return`mock.onMethod(${h(e)}, ${i}).replyOnce(${n.status}, ${a}, JSON.parse(${h(o)}));`}).join(`
2
- `)}async request(e){let t=this.generation,n;try{n={id:this.sequence++,generation:t,method:e.method??`GET`,matcher:p(e,this.maxRecordSize)}}catch{this.skipped++}let r;try{r=await this.adapter.request(e)}catch(e){if(n&&t===this.generation)try{isRequestError(e)&&e.code===`HTTP_ERROR`&&e.response?this.record(n,e.response):this.skipped++}catch{this.skipped++}throw e}return n&&this.record(n,r),r}record(e,t){if(e.generation===this.generation)try{let n=Object.fromEntries([...t.headers].filter(([e])=>!f(e)&&!/^(content-length|content-encoding|transfer-encoding)$/i.test(e))),r={method:e.method,matcher:e.matcher,response:{status:t.status,statusText:t.statusText,headers:n}};t.data!==void 0&&(r.response.data=m(t.data,this.maxRecordSize));let i=this.transform?this.transform(r):r;if(c(i)){Promise.resolve(i).catch(()=>{}),e.generation===this.generation&&this.skipped++;return}if(e.generation!==this.generation)return;if(!i){this.skipped++;return}let a=m(i,this.maxRecordSize);u(a);let o=JSON.stringify(a);if(e.generation!==this.generation)return;this.entries.set(e.id,o),this.entries.size>this.maxEntries&&this.entries.delete([...this.entries.keys()].reduce((e,t)=>Math.min(e,t)))}catch{e.generation===this.generation&&this.skipped++}}};function u(e){if(![`GET`,`HEAD`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`,`QUERY`].includes(e.method)||typeof e.matcher?.url!=`string`||!Number.isInteger(e.response?.status)||e.response.status<200||e.response.status>599||typeof e.response.statusText!=`string`)throw TypeError(`Invalid recording`);if(p({...e.matcher,searchParams:e.matcher.searchParams?new URLSearchParams(e.matcher.searchParams):void 0},2**53-1),!e.response.headers||Object.values(e.response.headers).some(e=>typeof e!=`string`))throw TypeError(`Invalid recorded headers`);new Headers(e.response.headers)}function d(e,t){if(e===void 0)return t;if(!Number.isSafeInteger(e)||e<=0)throw TypeError(`Mock recording limits must be positive safe integers`);return e}function f(e){return/^(?:authorization|proxyauthorization|cookie|setcookie|password|passwd|secret|token|accesstoken|refreshtoken|apikey|xapikey|clientsecret|sessionid|csrftoken|xcsrftoken|xsrftoken|xxsrftoken|xauthtoken)$/i.test(e.replace(/[-_]/g,``))}function p(e,t){let n=String(e.url);if(/^(?:[a-z][a-z\d+.-]*:)?\/\/[^/?#]*@/i.test(n))throw TypeError(`Credential URL`);if(n.includes(`#`))throw TypeError(`Fragment URL`);let r=n.indexOf(`?`);if(r!==-1){let e=new URLSearchParams(n.slice(r+1).split(`#`,1)[0]);for(let t of e.keys())if(f(t))throw TypeError(`Sensitive URL query`)}let i={url:n};if(e.query){for(let t of Object.keys(e.query))if(f(t))throw TypeError(`Sensitive query`);i.query=m(Object.fromEntries(Object.entries(e.query).filter(([,e])=>e!==void 0).map(([e,t])=>[e,Array.isArray(t)?t.filter(e=>e!==void 0):t])),t)}if(e.searchParams){for(let t of e.searchParams.keys())if(f(t))throw TypeError(`Sensitive searchParams`);i.searchParams=[...e.searchParams]}return m(i,t)}function m(e,t){let n=new Set,r=new TextEncoder,i=t,a=e=>{if(e.length>i||(i-=r.encode(e).byteLength,i<0))throw TypeError(`Recording too large`)},o=(e,t)=>{if(t>64)throw TypeError(`Recording too deep`);if(e===null||typeof e==`boolean`)return a(String(e)),e;if(typeof e==`string`){if(e.length>i)throw TypeError(`Recording too large`);return a(JSON.stringify(e)),e}if(typeof e==`number`&&Number.isFinite(e)&&!Object.is(e,-0))return a(String(e)),e;if(typeof e!=`object`||n.has(e))throw TypeError(`Non-JSON recording`);let r=Array.isArray(e);if(!r&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Non-JSON recording`);if(Object.getOwnPropertySymbols(e).length)throw TypeError(`Symbol recording`);n.add(e),a(`[]`);let s=r?[]:Object.create(null),c=Object.keys(e);if(c.length>i/2)throw TypeError(`Recording too large`);for(let n of c){let c=Object.getOwnPropertyDescriptor(e,n);if(n.length>i)throw TypeError(`Recording too large`);if(!(`value`in c))throw TypeError(`Accessor recording`);if(r&&!/^(0|[1-9]\d*)$/.test(n))throw TypeError(`Non-JSON array`);a(`,`),r||a(`${JSON.stringify(n)}:`);let l=f(n)?`[REDACTED]`:c.value,u=o(l,t+1);r?s.push(u):s[n]=u}if(r&&s.length!==e.length)throw TypeError(`Sparse recording`);return n.delete(e),s};return o(e,0)}function h(e){return JSON.stringify(e).replace(/</g,`\\u003c`)}var MockAdapter=class{constructor(e={}){this.handlers=new Map,this.rules=[],this.requests=[],this.delay=k(e.delay),this.recorder=e.record===void 0?void 0:new MockRecorder(e.record),Object.entries(e.handlers??{}).forEach(([e,t])=>{this.handlers.set(e,t)})}get history(){return[...this.requests]}get recordings(){return this.recorder?.recordings??[]}get recordingStats(){return this.recorder?.stats??{recorded:0,skipped:0}}exportMocks(){return this.recorder?.exportMocks()??``}clearRecordings(){return this.recorder?.clear(),this}on(e,t){return this.handlers.set(e,t),this}onMethod(e,t){let n=g(t);return new RouteBuilder({reply:(t,r,i,a)=>this.registerReply(e,n,t,r,i,a),error:(t,r,i)=>this.registerError(e,n,t,r,i)})}onGet(e){return this.onMethod(`GET`,e)}onPost(e){return this.onMethod(`POST`,e)}onPut(e){return this.onMethod(`PUT`,e)}onPatch(e){return this.onMethod(`PATCH`,e)}onDelete(e){return this.onMethod(`DELETE`,e)}onHead(e){return this.onMethod(`HEAD`,e)}onOptions(e){return this.onMethod(`OPTIONS`,e)}resetHistory(){return this.requests.length=0,this}resetHandlers(){return this.handlers.clear(),this.rules.length=0,this}reset(){return this.resetHandlers().resetHistory().clearRecordings()}async request(e){this.requests.push(e);let t=e.method??`GET`,n=this.rules.findIndex(n=>(n.method===void 0||n.method===t)&&_(n.matcher,e));if(n!==-1){let t=this.rules[n];return t.once&&this.rules.splice(n,1),w(await t.respond(e),e)}let r=this.handlers.get(String(e.url));if(!r){if(this.recorder)return this.recorder.request(e);throw Error(`No mock handler found for ${e.url} (${t})`)}return await A(this.delay,e),w(C(e,{status:200,statusText:`OK`,data:await r(e)}),e)}registerReply(e,t,n,r,i,a={}){let o=typeof r==`function`?r:()=>({status:r,data:i,...a});return this.rules.push({method:e,matcher:t,once:n,respond:async e=>{let t=await o(e);return await A(k(t.delay??this.delay),e),C(e,t)}}),this}registerError(t,n,r,i,a){return this.rules.push({method:t,matcher:n,once:r,respond:async t=>{throw await A(this.delay,t),new e(a,{code:i,config:t})}}),this}},RouteBuilder=class{constructor(e){this.registrar=e}reply(e,t,n={}){return this.registrar.reply(!1,e,t,n)}replyOnce(e,t,n={}){return this.registrar.reply(!0,e,t,n)}networkError(e=`Mock network error`){return this.registrar.error(!1,`NETWORK_ERROR`,e)}networkErrorOnce(e=`Mock network error`){return this.registrar.error(!0,`NETWORK_ERROR`,e)}timeout(e=`Mock request timeout`){return this.registrar.error(!1,`TIMEOUT_ERROR`,e)}timeoutOnce(e=`Mock request timeout`){return this.registrar.error(!0,`TIMEOUT_ERROR`,e)}};function g(e){return typeof e==`string`||e instanceof RegExp?{url:e}:e}function _(e,t){return v(e.url,String(t.url))&&y(e.query,t.query)&&x(e.searchParams,t.searchParams)&&S(e.headers,t.headers)}function v(e,t){return typeof e==`string`?e===t:(e.lastIndex=0,e.test(t))}function y(e,t){return!e||b(e)===b(t)}function b(e){if(!e)return`[]`;let t=[];for(let n of Object.keys(e).sort()){let r=e[n],i=Array.isArray(r)?r:[r];for(let e of i)e!==void 0&&t.push([n,e===null?``:String(e)])}return JSON.stringify(t)}function x(e,t){return!e||JSON.stringify([...e.entries()])===JSON.stringify([...t?.entries()??[]])}function S(e,t){if(!e)return!0;let n=new Headers(e),r=new Headers(t);for(let[e,t]of n.entries())if(r.get(e)!==t)return!1;return!0}function C(e,t){let n=new Headers(t.headers),r=D(t.data,n,t.status),i=t.statusText??T(t.status),a=new Response(r,{status:t.status,statusText:i,headers:n});return{data:t.data,status:t.status,statusText:i,headers:a.headers,config:e,raw:a}}function w(t,n){if(!o(t.status,n))throw new e(t.statusText||`Mock request failed`,{code:`HTTP_ERROR`,response:t});return t}function T(e){return E[e]??``}const E={200:`OK`,201:`Created`,202:`Accepted`,204:`No Content`,400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,408:`Request Timeout`,409:`Conflict`,422:`Unprocessable Content`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`,504:`Gateway Timeout`};function D(e,t,n){return e==null||i(void 0,n)?null:typeof e==`string`||O(e)?e:(t.has(`content-type`)||t.set(`content-type`,`application/json`),JSON.stringify(e))}function O(e){return t(e)||a(e)||n(e)||s(e)||r(e)||ArrayBuffer.isView(e)}function k(e){return Number.isFinite(e)?Math.min(Math.max(0,e??0),l):e&&e>0?l:0}function A(t,n){let r=n.signal;if(r?.aborted)return Promise.reject(j(r.reason,n));let i=n.timeout&&n.timeout>0?n.timeout:void 0,a=i!==void 0&&i<=t,o=a?i:t;return o<=0?Promise.resolve():new Promise((t,s)=>{let c,l=!1,u=()=>{c!==void 0&&(clearTimeout(c),c=void 0);try{r?.removeEventListener(`abort`,f)}catch{}},d=e=>{l||(l=!0,u(),s(e))},f=()=>{d(j(r?.reason,n))};try{r?.addEventListener(`abort`,f,{once:!0})}catch(e){d(e);return}if(r?.aborted&&f(),!l)try{c=setTimeout(()=>{a?d(new e(`Request timeout after ${i}ms`,{code:`TIMEOUT_ERROR`,config:n})):(l=!0,u(),t())},o)}catch(e){d(e)}})}function j(t,n){return new e(`Mock request aborted`,{code:`ABORT_ERROR`,config:n,cause:t})}export{MockAdapter as t};