@npora/request 1.22.0 → 1.22.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.
@@ -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};
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.1",
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};