UNPKG

1.65 kBJavaScriptView Raw
1var g=t=>[...t.entries()].reduce((n,[f,o])=>(n[f]=o,n),{}),q=t=>new URL(t),m=(t,n,f=null)=>t.reduce((o,i)=>i.call(f,o),n);function H({namespace:t=globalThis||window,fetch:n=t.fetch}={}){if(t==null&&(t=globalThis||window),typeof t!="object")throw new Error("[xfetch-hook] - `namespace` should be an object");if(typeof n!="function")throw new Error("[xfetch-hook] - `fetch` should be a function");if(typeof n.onRequest=="function")return n.stopIntercepting;let f="fetch",o=[];async function i(...a){let s=[],l=[],c=new Request(...a),p=null,d=null,b=null,y=null;for(let r of o){let e=await r({request:c,fetch:n,get url(){return b||(b=q(c.url))},get headers(){return y||(y=g(c.headers))}});!e||(e.request instanceof Request&&(c=e.request),e.response instanceof Response&&(p=e.response),typeof e.listen=="function"&&s.push(e.listen),typeof e.as=="string"&&(d=e.as,typeof e.transformResponse=="function"&&l.push(e.transformResponse)))}async function R(r){let e=r,x=d&&typeof r[d]=="function",T=await(x&&r.clone()[d]());if(l.length>0){let u=m(l,T);typeof u!="string"&&(u=JSON.stringify(u)),e=new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return s.forEach(u=>{let h=e.clone();x?h[d]().then(u.bind(null,h)):u(h)}),e}return p?R(p):n(c).then(R)}Object.defineProperty(i,"name",{value:f,configurable:!0});function E(){t[f]=i}E();function w(){t[f]=n}function P(a){o=o.filter(s=>s!==a)}function U(a){o.push(a)}return i.stopProxying=w,i.onRequest=function(s){if(typeof s!="function")throw new Error("[xfetch-hook] - `onRequest`: argument must be a function");let l=()=>P(s);return o.find(p=>p===s)||U(s),l},w}export{H as default};