Comparing version 2.9.0 to 3.0.0
@@ -1,2 +0,2 @@ | ||
"use strict";var fetchff=(()=>{var _=Object.defineProperty,Fe=Object.defineProperties,qe=Object.getOwnPropertyDescriptor,He=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,le=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,Se=Object.prototype.propertyIsEnumerable;var ee=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C=(e,t)=>{for(var n in t||(t={}))ue.call(t,n)&&ee(e,n,t[n]);if(le)for(var n of le(t))Se.call(t,n)&&ee(e,n,t[n]);return e},B=(e,t)=>Fe(e,He(t));var Be=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},Me=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ne(t))!ue.call(e,s)&&s!==n&&_(e,s,{get:()=>t[s],enumerable:!(o=qe(t,s))||o.enumerable});return e};var Ue=e=>Me(_({},"__esModule",{value:!0}),e);var A=(e,t,n)=>ee(e,typeof t!="symbol"?t+"":t,n);var Le={};Be(Le,{createApiFetcher:()=>_e,fetchf:()=>xe});async function O(e,t){if(t){if(typeof t=="function"){let n=await t(e);n&&Object.assign(e,n)}else if(Array.isArray(t))for(let n of t){let o=await n(e);o&&Object.assign(e,o)}}}var L=class extends Error{constructor(n,o,s){super(n);A(this,"response");A(this,"request");A(this,"config");A(this,"status");A(this,"statusText");this.name="ResponseError",this.message=n,this.status=s.status,this.statusText=s.statusText,this.request=o,this.config=o,this.response=s}};var M="application/json",j="Content-Type",x="undefined",b="object",J="string",$="AbortError",fe="TimeoutError",pe="CanceledError",U="GET",de="HEAD";function te(e){return e instanceof URLSearchParams}function Re(e){let t="";for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=n+":"+e[n]);return t}function ne(e){let t={},n=Object.keys(e);n.sort();for(let o=0,s=n.length;o<s;o++){let i=n[o];t[i]=e[i]}return t}function ye(e,t){return t?e.includes("?")?`${e}&${t}`:`${e}?${t}`:e}function me(e,t){if(!t)return e;if(te(t)){let l=t.toString();return ye(e,l)}let n=[],o=encodeURIComponent,s=(l,a)=>{a=typeof a=="function"?a():a,a=a===null||a===void 0?"":a,n[n.length]=o(l)+"="+o(a)},i=(l,a)=>{let d,g,y;if(l)if(Array.isArray(a))for(d=0,g=a.length;d<g;d++)i(l+"["+(typeof a[d]===b&&a[d]?d:"")+"]",a[d]);else if(typeof a===b&&a!==null)for(y in a)i(l+"["+y+"]",a[y]);else s(l,a);else if(Array.isArray(a))for(d=0,g=a.length;d<g;d++)s(a[d].name,a[d].value);else for(y in a)i(y,a[y]);return n},m=i("",t).join("&").replace(/%5B%5D/g,"[]");return ye(e,m)}function he(e,t){return t?e.replace(/:\w+/g,n=>{let o=n.substring(1);return String(t[o]?t[o]:n)}):e}function ge(e){let t=typeof e;if(t===x||e===null)return!1;if(t===J||t==="number"||t==="boolean"||Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;if(t===b){let n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null||typeof e.toJSON=="function")return!0}return!1}async function re(e){return new Promise(t=>setTimeout(()=>t(!0),e))}function se(e){return e&&typeof e===b&&typeof e.data!==x&&Object.keys(e).length===1?se(e.data):e}function Pe(e){if(!e)return{};let t={};if(e instanceof Headers)e.forEach((n,o)=>{t[o]=n});else if(typeof e===b&&e!==null)for(let[n,o]of Object.entries(e))t[n.toLowerCase()]=o;return t}function F(e,t){e&&t in e&&delete e[t]}var k=new Map;async function Ee(e,t,n=0,o=!1,s=!0){let i=Date.now(),h=k.get(e);if(h){let a=h[3],d=h[0],g=h[1];if(!a&&i-h[2]<n)return d;a&&d.abort(new DOMException("Aborted due to new request",$)),g!==null&&clearTimeout(g),k.delete(e)}let m=new AbortController,l=s?setTimeout(()=>{let a=new DOMException(`${e.url} aborted due to timeout`,fe);v(e,a)},t):null;return k.set(e,[m,l,i,o]),m}async function v(e,t=null){let n=k.get(e);if(n){let o=n[0],s=n[1];t&&!o.signal.aborted&&o.abort(t),s!==null&&clearTimeout(s),k.delete(e)}}async function Ce(e){var o;if(!(e!=null&&e.body))return null;let t=String(((o=e.headers)==null?void 0:o.get(j))||"").split(";")[0],n;try{if(t.includes(M)||t.includes("+json"))n=await e.json();else if(t.includes("multipart/form-data"))n=await e.formData();else if(t.includes("application/octet-stream"))n=await e.blob();else if(t.includes("application/x-www-form-urlencoded"))n=await e.formData();else if(t.includes("text/"))n=await e.text();else try{n=await e.clone().json()}catch(s){n=await e.text()}}catch(s){n=null}return n}function G(e){let t=0;for(let n=0,o=e.length;n<o;n++){let s=e.charCodeAt(n);t=t*31+s|0}return String(t)}var oe=new Map;function Te(e){let{url:t="",method:n=U,headers:o={},body:s="",mode:i="cors",credentials:h="include",cache:m="default",redirect:l="follow",referrer:a="",integrity:d=""}=e;if(m==="reload")return"";let g=Re(ne(o)),y="";if(s!==null)if(typeof s=="string")y=G(s);else if(s instanceof FormData)s.forEach((r,u)=>{y+=u+"="+r+"&"}),y=G(y);else if(typeof Blob!==x&&s instanceof Blob||typeof File!==x&&s instanceof File)y="BF"+s.size+s.type;else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))y="AB"+s.byteLength;else{let r=typeof s===b?ne(s):String(s);y=G(JSON.stringify(r))}return n+t+i+h+m+l+a+d+g+y}function ke(e,t){return t?Date.now()-e>t*1e3:!1}function be(e,t){let n=oe.get(e);if(n){if(!ke(n.timestamp,t))return n;oe.delete(e)}return null}function we(e,t,n=!1){oe.set(e,{data:t,isLoading:n,timestamp:Date.now()})}var Qe={method:U,strategy:"reject",timeout:3e4,dedupeTime:1e3,defaultResponse:null,headers:{Accept:M+", text/plain, */*","Accept-Encoding":"gzip, deflate, br",[j]:M+";charset=utf-8"},retry:{delay:1e3,maxDelay:3e4,resetTimeout:!0,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504]}};function z(e){let t=C(C({},Qe),e),n=t.fetcher,o=(n==null?void 0:n.create(t))||null,s=()=>o,i=(r,u)=>typeof r[u]!==x?r[u]:t[u],h=(...r)=>{var u;(u=t.logger)!=null&&u.warn&&t.logger.warn(...r)},m=(r,u,f)=>{let R=i(f,"method").toUpperCase(),P=R===U||R===de,c=he(r,i(f,"urlPathParams")),E=i(f,"params"),q=i(f,"body")||i(f,"data"),K=!!(u&&(P||q)),T;P||(T=q||u);let Q=i(f,"withCredentials")?"include":i(f,"credentials");F(f,"data"),F(f,"withCredentials");let D=E||K?me(c,E||u):c,w=D.includes("://")?"":i(f,"baseURL")||i(f,"apiUrl");return T&&typeof T!==J&&!te(T)&&ge(T)&&(T=JSON.stringify(T)),B(C({},f),{credentials:Q,body:T,method:R,url:w+D})},l=async(r,u)=>{d(r)||h("API ERROR",r),await O(r,u==null?void 0:u.onError),await O(r,t==null?void 0:t.onError)},a=async(r,u,f)=>{let R=d(r),P=i(f,"strategy"),c=i(f,"rejectCancelled");if(!(R&&!c)){if(P==="silent")await new Promise(()=>null);else if(P==="reject")return Promise.reject(r)}return y(u,f,r)},d=r=>r.name===$||r.name===pe,g=async(r,u=null,f=null)=>{var ie;let R=f||{},P=C(C({},t),R),c=null,E=m(r,u,P),{timeout:q,cancellable:K,dedupeTime:T,pollingInterval:Y,shouldStopPolling:Q,cacheTime:D,cacheKey:W}=P,w;if(W?w=W(E):w=Te(E),D&&w){let I=P.cacheBuster;if(!I||!I(E)){let p=be(w,D);if(p)return p.data}}let{retries:V=0,delay:Oe,backoff:De,retryOn:X,shouldRetry:ae,maxDelay:Ie,resetTimeout:Ae}=P.retry,H=0,Z=0,N=Oe;for(;H<=V;)try{let I=await Ee(E,q,T,K,!!(q&&(!V||Ae))),p=C({signal:I.signal},E);if(await O(p,R==null?void 0:R.onRequest),await O(p,t==null?void 0:t.onRequest),n!==null&&o!==null?c=await o.request(p):c=await fetch(p.url,p),c instanceof Response&&(c.config=p,c.data=await Ce(c),!c.ok))throw new L(`${p.url} failed! Status: ${c.status||null}`,p,c);if(await O(c,R==null?void 0:R.onResponse),await O(c,t==null?void 0:t.onResponse),v(E),Y&&(!Q||!Q(c,Z))){Z++,h(`Polling attempt ${Z}...`),await re(Y);continue}let S=y(c,p);if(D&&w){let ce=p.skipCache;(!ce||!ce(S,p))&&we(w,S)}return S}catch(I){let p=I,S=((ie=p==null?void 0:p.response)==null?void 0:ie.status)||(p==null?void 0:p.status)||0;if(H===V||!(!ae||await ae(p,H))||!(X!=null&&X.includes(S)))return await l(p,E),v(E),a(p,c,E);h(`Attempt ${H+1} failed. Retry in ${N}ms.`),await re(N),N*=De,N=Math.min(N,Ie),H++}return y(c,E)},y=(r,u,f=null)=>{let R=i(u,"defaultResponse"),P=i(u,"flattenResponse");if(!r)return P?R:{error:f,headers:null,data:R,config:u};F(f,"response"),F(f,"request"),F(f,"config");let c=r==null?void 0:r.data;return(c==null||typeof c===b&&Object.keys(c).length===0)&&(c=R),P?se(c):r instanceof Response?{body:r.body,bodyUsed:r.bodyUsed,formData:r.formData,ok:r.ok,redirected:r.redirected,type:r.type,url:r.url,status:r.status,statusText:r.statusText,blob:r.blob.bind(r),json:r.json.bind(r),text:r.text.bind(r),clone:r.clone.bind(r),arrayBuffer:r.arrayBuffer.bind(r),error:f,data:c,headers:Pe(r.headers),config:u}:r};return{getInstance:s,buildConfig:m,config:e,request:g}}function _e(e){let t=e.endpoints,n=z(e);function o(){return n.getInstance()}function s(l){return console.error(`Add ${l} to 'endpoints'.`),Promise.resolve(null)}async function i(l,a={},d={},g={}){let y=t[l];return await n.request(y.url,a,B(C(C({},y||{}),g),{urlPathParams:d}))}function h(l){return l in m?m[l]:t[l]?m.request.bind(null,l):s.bind(null,l)}let m={config:e,endpoints:t,requestHandler:n,getInstance:o,request:i};return new Proxy(m,{get:(l,a)=>h(a)})}async function xe(e,t={}){return z(t).request(e,null,t)}return Ue(Le);})(); | ||
"use strict";var fetchff=(()=>{var M=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var Fe=(e,t,n)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ie=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of xe(t))!Oe.call(e,r)&&r!==n&&M(e,r,{get:()=>t[r],enumerable:!(a=we(t,r))||a.enumerable});return e};var Ae=e=>qe(M({},"__esModule",{value:!0}),e);var w=(e,t,n)=>Fe(e,typeof t!="symbol"?t+"":t,n);var Be={};Ie(Be,{createApiFetcher:()=>Ue,fetchf:()=>Se});async function T(e,t){if(t){if(typeof t=="function"){let n=await t(e);n&&Object.assign(e,n)}else if(Array.isArray(t))for(let n of t){let a=await n(e);a&&Object.assign(e,a)}}}var _=class extends Error{constructor(n,a,r){super(n);w(this,"response");w(this,"request");w(this,"config");w(this,"status");w(this,"statusText");this.name="ResponseError",this.message=n,this.status=r.status,this.statusText=r.statusText,this.request=a,this.config=a,this.response=r}};var Q="application/",A=Q+"json",L="Content-Type",C="undefined",E="object",v="string",j="AbortError",ie="TimeoutError",le="CanceledError",N="GET",ue="HEAD";function W(e){return e instanceof URLSearchParams}function fe(e){let t="";for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=n+":"+e[n]);return t}function X(e){let t={},n=Object.keys(e);n.sort();for(let a=0,r=n.length;a<r;a++){let u=n[a];t[u]=e[u]}return t}function ce(e,t){return t?e.includes("?")?`${e}&${t}`:`${e}?${t}`:e}function pe(e,t){if(!t)return e;if(W(t)){let f=t.toString();return ce(e,f)}let n=[],a=encodeURIComponent,r=(f,o)=>{o=typeof o=="function"?o():o,o=o===null||o===void 0?"":o,n[n.length]=a(f)+"="+a(o)},u=(f,o)=>{let p,g,R;if(f)if(Array.isArray(o))for(p=0,g=o.length;p<g;p++)u(f+"["+(typeof o[p]===E&&o[p]?p:"")+"]",o[p]);else if(typeof o===E&&o!==null)for(R in o)u(f+"["+R+"]",o[R]);else r(f,o);else if(Array.isArray(o))for(p=0,g=o.length;p<g;p++)r(o[p].name,o[p].value);else for(R in o)u(R,o[R]);return n},y=u("",t).join("&").replace(/%5B%5D/g,"[]");return ce(e,y)}function de(e,t){return t?e.replace(/:\w+/g,n=>{let a=n.substring(1);return t[a]?String(t[a]):n}):e}function Re(e){let t=typeof e;if(t===C||e===null)return!1;if(t===v||t==="number"||t==="boolean"||Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;if(t===E){let n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null||typeof e.toJSON=="function")return!0}return!1}async function Z(e){return new Promise(t=>setTimeout(()=>t(!0),e))}function ee(e){return e&&typeof e===E&&typeof e.data!==C&&Object.keys(e).length===1?ee(e.data):e}function me(e){if(!e)return{};let t={};if(e instanceof Headers)e.forEach((n,a)=>{t[a]=n});else if(typeof e===E&&e!==null)for(let[n,a]of Object.entries(e))t[n.toLowerCase()]=a;return t}function J(e,t){e&&t in e&&delete e[t]}var H=new Map;async function ye(e,t,n=0,a=!1,r=!0){let u=Date.now(),m=H.get(e);if(m){let o=m[3],p=m[0],g=m[1];if(!o&&u-m[2]<n)return p;o&&p.abort(new DOMException("Aborted due to new request",j)),g!==null&&clearTimeout(g),H.delete(e)}let y=new AbortController,f=r?setTimeout(()=>{let o=new DOMException(`${e.url} aborted due to timeout`,ie);$(e,o)},t):null;return H.set(e,[y,f,u,a]),y}async function $(e,t=null){let n=H.get(e);if(n){let a=n[0],r=n[1];t&&!a.signal.aborted&&a.abort(t),r!==null&&clearTimeout(r),H.delete(e)}}async function he(e){var a;if(!(e!=null&&e.body))return null;let t=String(((a=e.headers)==null?void 0:a.get(L))||"").split(";")[0],n;try{if(t.includes(A)||t.includes("+json"))n=await e.json();else if(t.includes("multipart/form-data"))n=await e.formData();else if(t.includes(Q+"octet-stream"))n=await e.blob();else if(t.includes(Q+"x-www-form-urlencoded"))n=await e.formData();else if(t.includes("text/"))n=await e.text();else try{n=await e.clone().json()}catch(r){n=await e.text()}}catch(r){n=null}return n}function G(e){let t=0;for(let n=0,a=e.length;n<a;n++){let r=e.charCodeAt(n);t=t*31+r|0}return String(t)}var te=new Map;function ge(e){let{url:t="",method:n=N,headers:a={},body:r="",mode:u="cors",credentials:m="include",cache:y="default",redirect:f="follow",referrer:o="",integrity:p=""}=e;if(y==="reload")return"";let g=fe(X(a)),R="";if(r!==null)if(typeof r=="string")R=G(r);else if(r instanceof FormData)r.forEach((s,i)=>{R+=i+"="+s+"&"}),R=G(R);else if(typeof Blob!==C&&r instanceof Blob||typeof File!==C&&r instanceof File)R="BF"+r.size+r.type;else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))R="AB"+r.byteLength;else{let s=typeof r===E?X(r):String(r);R=G(JSON.stringify(s))}return n+t+u+m+y+f+o+p+g+R}function Ne(e,t){return t?Date.now()-e>t*1e3:!1}function Pe(e,t){let n=te.get(e);if(n){if(!Ne(n.timestamp,t))return n;te.delete(e)}return null}function De(e,t,n=!1){te.set(e,{data:t,isLoading:n,timestamp:Date.now()})}var He={method:N,strategy:"reject",timeout:3e4,dedupeTime:1e3,defaultResponse:null,headers:{Accept:A+", text/plain, */*","Accept-Encoding":"gzip, deflate, br",[L]:A+";charset=utf-8"},retry:{delay:1e3,maxDelay:3e4,resetTimeout:!0,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504]}};function z(e){let t={...He,...e},n=t.fetcher,a=(n==null?void 0:n.create(t))||null,r=()=>a,u=(s,i)=>typeof s[i]!==C?s[i]:t[i],m=(...s)=>{var i;(i=t.logger)!=null&&i.warn&&t.logger.warn(...s)},y=(s,i)=>{let d=u(i,"method").toUpperCase(),P=d===N||d===ue,l=de(s,u(i,"urlPathParams")),h=u(i,"params"),U=u(i,"body")||u(i,"data"),D;P||(D=U);let S=u(i,"withCredentials")?"include":u(i,"credentials"),x=h?pe(l,h):l,k=x.includes("://")?"":u(i,"baseURL")||u(i,"apiUrl");return D&&typeof D!==v&&!W(D)&&Re(D)&&(D=JSON.stringify(D)),{...i,credentials:S,body:D,method:d,url:k+x}},f=async(s,i)=>{p(s)||m("API ERROR",s),await T(s,i==null?void 0:i.onError),await T(s,t==null?void 0:t.onError)},o=async(s,i,d)=>{let P=p(s),l=u(d,"strategy"),h=u(d,"rejectCancelled");if(!(P&&!h)){if(l==="silent")await new Promise(()=>null);else if(l==="reject")return Promise.reject(s)}return R(i,d,s)},p=s=>s.name===j||s.name===le,g=async(s,i=null)=>{var ae;let d=i||{},P={...t,...d},l=null,h=y(s,P),{timeout:U,cancellable:D,dedupeTime:ne,pollingInterval:S,shouldStopPolling:x,cacheTime:B,cacheKey:k}=P,b;if(k?b=k(h):b=ge(h),B&&b){let I=P.cacheBuster;if(!I||!I(h)){let c=Pe(b,B);if(c)return c.data}}let{retries:Y=0,delay:Ee,backoff:Ce,retryOn:K,shouldRetry:se,maxDelay:Te,resetTimeout:be}=P.retry,O=0,V=0,F=Ee,re=Y>0?Y:0;for(;O<=re;)try{let c={signal:(await ye(h,U,ne,D,!!(U&&(!re||be)))).signal,...h};if(await T(c,d==null?void 0:d.onRequest),await T(c,t==null?void 0:t.onRequest),n!==null&&a!==null?l=await a.request(c):l=await fetch(c.url,c),l instanceof Response&&(l.config=c,l.data=await he(l),!l.ok))throw new _(`${c.url} failed! Status: ${l.status||null}`,c,l);if(await T(l,d==null?void 0:d.onResponse),await T(l,t==null?void 0:t.onResponse),$(h),S&&(!x||!x(l,V))){V++,m(`Polling attempt ${V}...`),await Z(S);continue}let q=R(l,c);if(B&&b){let oe=c.skipCache;(!oe||!oe(q,c))&&De(b,q)}return q}catch(I){let c=I,q=((ae=c==null?void 0:c.response)==null?void 0:ae.status)||(c==null?void 0:c.status)||0;if(O===Y||!(!se||await se(c,O))||!(K!=null&&K.includes(q)))return await f(c,h),$(h),o(c,l,h);m(`Attempt ${O+1} failed. Retry in ${F}ms.`),await Z(F),F*=Ce,F=Math.min(F,Te),O++}return R(l,h)},R=(s,i,d=null)=>{let P=u(i,"defaultResponse");if(!s)return{ok:!1,error:d,data:P,headers:null,config:i};J(d,"response"),J(d,"request"),J(d,"config");let l=s==null?void 0:s.data;return(l==null||typeof l===E&&Object.keys(l).length===0)&&(l=P),u(i,"flattenResponse")&&(s.data=ee(l)),s instanceof Response?{body:s.body,bodyUsed:s.bodyUsed,formData:s.formData,ok:s.ok,redirected:s.redirected,type:s.type,url:s.url,status:s.status,statusText:s.statusText,blob:s.blob.bind(s),json:s.json.bind(s),text:s.text.bind(s),clone:s.clone.bind(s),arrayBuffer:s.arrayBuffer.bind(s),error:d,data:l,headers:me(s.headers),config:i}:s};return{getInstance:r,buildConfig:y,config:e,request:g}}function Ue(e){let t=e.endpoints,n=z(e);function a(){return n.getInstance()}function r(y){return console.error(`Add ${y} to 'endpoints'.`),Promise.resolve(null)}async function u(y,f={}){let o=t[y]||{url:y};return await n.request(o.url,{...o,...f})}let m={config:e,endpoints:t,requestHandler:n,getInstance:a,request:u};return new Proxy(m,{get(y,f){return f in m?m[f]:t[f]?m.request.bind(null,f):r.bind(null,f)}})}async function Se(e,t={}){return z(t).request(e,t)}return Ae(Be);})(); | ||
//# sourceMappingURL=index.global.js.map |
@@ -1,12 +0,13 @@ | ||
type RequestInterceptor<D = any> = (config: RequestHandlerConfig<D>) => RequestHandlerConfig<D> | void | Promise<RequestHandlerConfig<D>> | Promise<void>; | ||
type ResponseInterceptor<D = any> = (response: FetchResponse<D>) => FetchResponse<D> | void | Promise<FetchResponse<D>> | Promise<void>; | ||
type ErrorInterceptor = (error: ResponseError) => unknown; | ||
type RequestInterceptor<RequestBody = any, ResponseData = any> = (config: RequestHandlerConfig<ResponseData, RequestBody>) => RequestHandlerConfig<ResponseData, RequestBody> | void | Promise<RequestHandlerConfig<ResponseData, RequestBody>> | Promise<void>; | ||
type ResponseInterceptor<ResponseData = any> = (response: FetchResponse<ResponseData>) => FetchResponse<ResponseData> | void | Promise<FetchResponse<ResponseData>> | Promise<void>; | ||
type ErrorInterceptor<ResponseData = any, RequestBody = any> = (error: ResponseError<ResponseData, RequestBody>) => unknown; | ||
type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK'; | ||
type DefaultResponse = any; | ||
type NativeFetch = typeof fetch; | ||
interface FetcherInstance { | ||
create: <RequestInstance = CreatedCustomFetcherInstance>(config?: BaseRequestHandlerConfig) => RequestInstance; | ||
create: <RequestInstance = CreatedCustomFetcherInstance>(config?: RequestHandlerConfig) => RequestInstance; | ||
} | ||
interface CreatedCustomFetcherInstance { | ||
request<ResponseData = any>(requestConfig: RequestConfig): FetchResponse<ResponseData> | PromiseLike<FetchResponse<ResponseData>>; | ||
request<ResponseData = DefaultResponse, QueryParams = DefaultParams, PathParams = DefaultUrlParams, RequestBody = DefaultPayload>(requestConfig: RequestConfig<ResponseData, QueryParams, PathParams, RequestBody>): PromiseLike<FetchResponse<ResponseData>>; | ||
} | ||
@@ -17,22 +18,30 @@ type ErrorHandlingStrategy = 'reject' | 'silent' | 'defaultResponse' | 'softFail'; | ||
} | ||
interface ExtendedResponse<D = any> extends Omit<Response, 'headers'> { | ||
data: D extends unknown ? any : D; | ||
error: ResponseError<D> | null; | ||
interface ExtendedResponse<ResponseData = any, RequestBody = any> extends Omit<Response, 'headers'> { | ||
data: ResponseData extends [unknown] ? any : ResponseData; | ||
error: ResponseError<ResponseData, RequestBody> | null; | ||
headers: HeadersObject & HeadersInit; | ||
config: ExtendedRequestConfig<D>; | ||
config: ExtendedRequestConfig<ResponseData, RequestBody>; | ||
} | ||
type FetchResponse<T = any> = ExtendedResponse<T>; | ||
interface ResponseError<D = any> extends Error { | ||
config: ExtendedRequestConfig<D>; | ||
/** | ||
* Represents the response from a `fetchf()` request. | ||
* | ||
* @template ResponseData - The type of the data returned in the response. | ||
*/ | ||
type FetchResponse<ResponseData = any, RequestBody = any> = ExtendedResponse<ResponseData, RequestBody>; | ||
interface ResponseError<ResponseData = any, RequestBody = any> extends Error { | ||
config: ExtendedRequestConfig<ResponseData, RequestBody>; | ||
code?: string; | ||
status?: number; | ||
statusText?: string; | ||
request?: ExtendedRequestConfig<D>; | ||
response?: FetchResponse<D>; | ||
request?: ExtendedRequestConfig<ResponseData, RequestBody>; | ||
response?: FetchResponse<ResponseData, RequestBody>; | ||
} | ||
type RetryFunction = <T = any>(error: ResponseError<T>, attempts: number) => Promise<boolean>; | ||
type PollingFunction = <ResponseData = any>(response: FetchResponse<ResponseData>, attempts: number, error?: ResponseError) => boolean; | ||
type RetryFunction = <ResponseData = any, RequestBody = any>(error: ResponseError<ResponseData, RequestBody>, attempts: number) => Promise<boolean>; | ||
type PollingFunction<ResponseData = any, RequestBody = any> = (response: FetchResponse<ResponseData, RequestBody>, attempts: number, error?: ResponseError<ResponseData, RequestBody>) => boolean; | ||
type CacheKeyFunction = (config: FetcherConfig) => string; | ||
type CacheBusterFunction = (config: FetcherConfig) => boolean; | ||
type CacheSkipFunction = <ResponseData = any>(data: ResponseData, config: RequestConfig) => boolean; | ||
type CacheSkipFunction = <ResponseData = any, RequestBody = any>(data: ResponseData, config: RequestConfig<ResponseData, RequestBody>) => boolean; | ||
/** | ||
* Configuration object for retry related options | ||
*/ | ||
interface RetryOptions { | ||
@@ -120,3 +129,3 @@ /** | ||
/** | ||
* ExtendedRequestConfig<D = any> | ||
* ExtendedRequestConfig<ResponseData = any, RequestBody = any> | ||
* | ||
@@ -126,3 +135,3 @@ * This interface extends the standard `RequestInit` from the Fetch API, providing additional options | ||
*/ | ||
interface ExtendedRequestConfig<D = any> extends Omit<RequestInit, 'body'>, CacheOptions { | ||
interface ExtendedRequestConfig<ResponseData = any, QueryParams_ = any, PathParams = any, RequestBody = any> extends Omit<RequestInit, 'body'>, CacheOptions { | ||
/** | ||
@@ -158,3 +167,3 @@ * Custom error handling strategy for the request. | ||
*/ | ||
urlPathParams?: UrlPathParams; | ||
urlPathParams?: UrlPathParams<PathParams>; | ||
/** | ||
@@ -188,3 +197,3 @@ * Configuration options for retrying failed requests. | ||
*/ | ||
params?: QueryParams; | ||
params?: QueryParams<QueryParams_>; | ||
/** | ||
@@ -202,19 +211,19 @@ * Indicates whether credentials (such as cookies) should be included with the request. | ||
*/ | ||
body?: BodyPayload<D>; | ||
body?: BodyPayload<RequestBody>; | ||
/** | ||
* Alias for "body" | ||
*/ | ||
data?: BodyPayload<D>; | ||
data?: BodyPayload<RequestBody>; | ||
/** | ||
* A function or array of functions to intercept the request before it is sent. | ||
*/ | ||
onRequest?: RequestInterceptor<D> | RequestInterceptor<D>[]; | ||
onRequest?: RequestInterceptor<RequestBody, ResponseData> | RequestInterceptor<RequestBody, ResponseData>[]; | ||
/** | ||
* A function or array of functions to intercept the response before it is resolved. | ||
*/ | ||
onResponse?: ResponseInterceptor<D> | ResponseInterceptor<D>[]; | ||
onResponse?: ResponseInterceptor<ResponseData> | ResponseInterceptor<ResponseData>[]; | ||
/** | ||
* A function to handle errors that occur during the request or response processing. | ||
*/ | ||
onError?: ErrorInterceptor | ErrorInterceptor[]; | ||
onError?: ErrorInterceptor<ResponseData, RequestBody> | ErrorInterceptor<ResponseData, RequestBody>[]; | ||
/** | ||
@@ -240,24 +249,23 @@ * The maximum time (in milliseconds) the request can take before automatically being aborted. | ||
*/ | ||
shouldStopPolling?: PollingFunction; | ||
shouldStopPolling?: PollingFunction<ResponseData, RequestBody>; | ||
} | ||
interface BaseRequestHandlerConfig<RequestData = any> extends RequestConfig<RequestData> { | ||
interface RequestHandlerConfig<ResponseData = any, RequestBody = any> extends RequestConfig<ResponseData, RequestBody> { | ||
fetcher?: FetcherInstance | null; | ||
logger?: any; | ||
} | ||
type RequestConfig<RequestData = any> = ExtendedRequestConfig<RequestData>; | ||
type FetcherConfig = Omit<ExtendedRequestConfig, 'url'> & { | ||
type RequestConfig<ResponseData = any, QueryParams = any, PathParams = any, RequestBody = any> = ExtendedRequestConfig<ResponseData, QueryParams, PathParams, RequestBody>; | ||
type FetcherConfig<ResponseData = any, QueryParams = any, PathParams = any, RequestBody = any> = Omit<ExtendedRequestConfig<ResponseData, QueryParams, PathParams, RequestBody>, 'url'> & { | ||
url: string; | ||
}; | ||
type RequestHandlerConfig<RequestData = any> = BaseRequestHandlerConfig<RequestData>; | ||
interface RequestHandlerReturnType { | ||
config: RequestHandlerConfig; | ||
getInstance: () => CreatedCustomFetcherInstance | null; | ||
buildConfig: (url: string, data: QueryParamsOrBody, config: RequestConfig) => RequestConfig; | ||
request: <ResponseData = unknown>(url: string, data?: QueryParamsOrBody, config?: RequestConfig | null) => Promise<ResponseData & FetchResponse<ResponseData>>; | ||
buildConfig: (url: string, config: RequestConfig) => RequestConfig; | ||
request: <ResponseData = DefaultResponse, QueryParams = DefaultParams, PathParams = DefaultUrlParams, RequestBody = DefaultPayload>(url: string, config?: RequestConfig<ResponseData, QueryParams, PathParams, RequestBody> | null) => Promise<FetchResponse<ResponseData, RequestBody>>; | ||
} | ||
type NameValuePair = { | ||
interface NameValuePair { | ||
name: string; | ||
value: string; | ||
}; | ||
} | ||
declare const emptyObjectSymbol: unique symbol; | ||
@@ -267,18 +275,57 @@ type EmptyObject = { | ||
}; | ||
declare type QueryParams<T = unknown> = (Record<string, T> & EmptyObject) | URLSearchParams | NameValuePair[] | null; | ||
declare type BodyPayload<T = any> = BodyInit | (Record<string, T> & EmptyObject) | T[] | string | null; | ||
declare type QueryParamsOrBody<T = unknown> = QueryParams<T> | BodyPayload<T>; | ||
declare type UrlPathParams<T = unknown> = (Record<string, T> & EmptyObject) | null; | ||
declare type APIResponse = unknown; | ||
declare type Endpoint<ResponseData = APIResponse, QueryParams = QueryParamsOrBody, PathParams = UrlPathParams> = { | ||
(queryParams?: QueryParams, urlPathParams?: PathParams, requestConfig?: RequestConfig): Promise<ResponseData & FetchResponse<ResponseData>>; | ||
} | { | ||
<ReturnedData = ResponseData, T = QueryParams, T2 = PathParams>(queryParams?: T, urlPathParams?: T2, requestConfig?: RequestConfig): Promise<ReturnedData & FetchResponse<ReturnedData>>; | ||
}; | ||
type EndpointDefaults = Endpoint<never>; | ||
type DefaultParams = Record<string, unknown>; | ||
type DefaultUrlParams = Record<string, unknown>; | ||
type DefaultPayload = Record<string, any>; | ||
declare type QueryParams<ParamsType = DefaultParams> = (ParamsType & EmptyObject) | URLSearchParams | NameValuePair[] | null; | ||
declare type UrlPathParams<UrlParamsType = DefaultUrlParams> = ([UrlParamsType] extends [DefaultUrlParams] ? UrlParamsType & EmptyObject : UrlParamsType) | EmptyObject | null; | ||
declare type BodyPayload<PayloadType = DefaultPayload> = BodyInit | (PayloadType & EmptyObject) | PayloadType[] | null; | ||
type FallbackValue<T, U, D = T> = [T] extends [never] ? U : D; | ||
type FinalResponse<Response, ResponseData> = FallbackValue<Response, ResponseData>; | ||
type FinalParams<Response, ParamsType, DefaultParams> = [ | ||
ParamsType | ||
] extends [never] ? DefaultParams : [Response] extends [never] ? DefaultParams : ParamsType | EmptyObject; | ||
interface EndpointFunction<ResponseData, QueryParams_, PathParams, RequestBody_> { | ||
<Resp = never, QueryParams = never, UrlParams = never, RequestBody = never>(requestConfig?: ExtendedRequestConfig<FallbackValue<Resp, ResponseData>, FinalParams<Resp, QueryParams, QueryParams_>, FinalParams<Resp, UrlParams, PathParams>, FallbackValue<Resp, RequestBody_, RequestBody>>): Promise<FetchResponse<FallbackValue<Resp, ResponseData>>>; | ||
} | ||
interface RequestEndpointFunction<EndpointsMethods> { | ||
<ResponseData = never, QueryParams_ = never, UrlParams = never, RequestBody = never>(endpointName: keyof EndpointsMethods | string, requestConfig?: RequestConfig<FinalResponse<ResponseData, DefaultResponse>, FinalParams<ResponseData, QueryParams_, QueryParams>, FinalParams<ResponseData, UrlParams, UrlPathParams>, FallbackValue<ResponseData, DefaultPayload, RequestBody>>): Promise<FetchResponse<FinalResponse<ResponseData, DefaultResponse>>>; | ||
} | ||
/** | ||
* Represents an API endpoint handler with support for customizable query parameters, URL path parameters, | ||
* and request configuration. | ||
* | ||
* The overloads allow customization of the returned data type (`ReturnedData`), query parameters (`T`), | ||
* and URL path parameters (`T2`). | ||
* | ||
* @template ResponseData - The type of the response data (default: `DefaultResponse`). | ||
* @template QueryParams - The type of the query parameters (default: `QueryParams`). | ||
* @template PathParams - The type of the URL path parameters (default: `UrlPathParams`). | ||
* @template RequestBody - The type of the Requesty Body (default: `BodyPayload`). | ||
* | ||
* @example | ||
* interface EndpointsMethods { | ||
* getUser: Endpoint<UserResponse>; | ||
* getPosts: Endpoint<PostsResponse, PostsQueryParams, PostsUrlPathParams>; | ||
* } | ||
*/ | ||
declare type Endpoint<ResponseData = DefaultResponse, QueryParams_ = QueryParams, PathParams = UrlPathParams, RequestBody = BodyPayload> = EndpointFunction<ResponseData, QueryParams_, PathParams, RequestBody>; | ||
type EndpointDefaults = Endpoint<DefaultResponse>; | ||
type AFunction = (...args: any[]) => any; | ||
/** | ||
* Maps the method names from `EndpointsMethods` to their corresponding `Endpoint` type definitions. | ||
* | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
*/ | ||
type EndpointsRecord<EndpointsMethods> = { | ||
[K in keyof EndpointsMethods]: EndpointsMethods[K] extends Endpoint<infer ResponseData, infer QueryParams, infer UrlPathParams> ? Endpoint<ResponseData, QueryParams, UrlPathParams> : Endpoint<never>; | ||
[K in keyof EndpointsMethods]: EndpointsMethods[K] extends AFunction ? EndpointsMethods[K] : EndpointsMethods[K] extends Endpoint<infer ResponseData, infer QueryParams, infer UrlPathParams> ? Endpoint<ResponseData, QueryParams, UrlPathParams> : EndpointDefaults; | ||
}; | ||
type DefaultEndpoints<EndpointsCfg> = { | ||
[K in keyof EndpointsCfg]: EndpointDefaults; | ||
/** | ||
* Defines default endpoints based on the provided `EndpointsSettings`. | ||
* | ||
* This type provides default implementations for endpoints in `EndpointsSettings`, using `EndpointDefaults`. | ||
* | ||
* @template EndpointsSettings - The configuration object for endpoints. | ||
*/ | ||
type DefaultEndpoints<EndpointsSettings> = { | ||
[K in keyof EndpointsSettings]: EndpointDefaults; | ||
}; | ||
@@ -288,8 +335,37 @@ type RequestConfigUrlRequired = Omit<RequestConfig, 'url'> & { | ||
}; | ||
/** | ||
* Configuration for API endpoints, where each key is an endpoint name or string, and the value is the request configuration. | ||
* | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
*/ | ||
type EndpointsConfig<EndpointsMethods> = Record<keyof EndpointsMethods | string, RequestConfigUrlRequired>; | ||
type EndpointsConfigPart<EndpointsCfg, EndpointsMethods extends object> = [ | ||
EndpointsCfg | ||
] extends [never] ? unknown : DefaultEndpoints<Omit<EndpointsCfg, keyof EndpointsMethods>>; | ||
type ApiHandlerReturnType<EndpointsMethods extends object, EndpointsCfg> = EndpointsRecord<EndpointsMethods> & EndpointsConfigPart<EndpointsCfg, EndpointsMethods> & ApiHandlerMethods<EndpointsMethods>; | ||
type ApiHandlerMethods<EndpointsMethods> = { | ||
/** | ||
* Part of the endpoints configuration, derived from `EndpointsSettings` based on the `EndpointsMethods`. | ||
* | ||
* This type handles defaulting to endpoints configuration when particular Endpoints Methods are not provided. | ||
* | ||
* @template EndpointsSettings - The configuration object for endpoints. | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
*/ | ||
type EndpointsConfigPart<EndpointsSettings, EndpointsMethods extends object> = [ | ||
EndpointsSettings | ||
] extends [never] ? unknown : DefaultEndpoints<Omit<EndpointsSettings, keyof EndpointsMethods>>; | ||
/** | ||
* Provides the methods available from the API handler, combining endpoint record types, endpoints configuration, | ||
* and default methods. | ||
* | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
* @template EndpointsSettings - The configuration object for endpoints. | ||
*/ | ||
type ApiHandlerMethods<EndpointsMethods extends object, EndpointsSettings> = EndpointsRecord<EndpointsMethods> & // Provided interface | ||
EndpointsConfigPart<EndpointsSettings, EndpointsMethods> & // Derived defaults from 'endpoints' | ||
ApiHandlerDefaultMethods<EndpointsMethods>; | ||
/** | ||
* Defines the default methods available within the API handler. | ||
* | ||
* This includes configuration, endpoint settings, request handler, instance retrieval, and a generic request method. | ||
* | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
*/ | ||
type ApiHandlerDefaultMethods<EndpointsMethods> = { | ||
config: ApiHandlerConfig<EndpointsMethods>; | ||
@@ -299,4 +375,9 @@ endpoints: EndpointsConfig<EndpointsMethods>; | ||
getInstance: () => CreatedCustomFetcherInstance | null; | ||
request: <ResponseData = APIResponse>(endpointName: keyof EndpointsMethods | string, queryParams?: QueryParams, urlPathParams?: UrlPathParams, requestConfig?: RequestConfig) => Promise<ResponseData & FetchResponse<ResponseData>>; | ||
request: RequestEndpointFunction<EndpointsMethods>; | ||
}; | ||
/** | ||
* Configuration for the API handler, including API URL and endpoints. | ||
* | ||
* @template EndpointsMethods - The object containing endpoint method definitions. | ||
*/ | ||
interface ApiHandlerConfig<EndpointsMethods> extends RequestHandlerConfig { | ||
@@ -321,3 +402,3 @@ apiUrl: string; | ||
* @param {string} config.strategy - Error Handling Strategy | ||
* @param {string} config.flattenResponse - Whether to flatten response "data" object within "data" one | ||
* @param {string} config.flattenResponse - Whether to flatten response "data" object within "data". It works only if the response structure includes a single data property. | ||
* @param {*} config.defaultResponse - Default response when there is no data or when endpoint fails depending on the chosen strategy. It's "null" by default | ||
@@ -361,3 +442,3 @@ * @param {Object} [config.retry] - Options for retrying requests. | ||
*/ | ||
declare function createApiFetcher<EndpointsMethods extends object, EndpointsCfg = never>(config: ApiHandlerConfig<EndpointsMethods>): ApiHandlerReturnType<EndpointsMethods, EndpointsCfg>; | ||
declare function createApiFetcher<EndpointsMethods extends object, EndpointsSettings = never>(config: ApiHandlerConfig<EndpointsMethods>): ApiHandlerMethods<EndpointsMethods, EndpointsSettings>; | ||
@@ -370,6 +451,6 @@ /** | ||
* @param {RequestHandlerConfig} config - Configuration object for the request handler. | ||
* @returns {Promise<ResponseData & FetchResponse<ResponseData>>} Response Data. | ||
* @returns {Promise<FetchResponse<ResponseData>>} Response Data. | ||
*/ | ||
declare function fetchf<ResponseData = APIResponse>(url: string, config?: RequestHandlerConfig<ResponseData>): Promise<ResponseData & FetchResponse<ResponseData>>; | ||
declare function fetchf<ResponseData = DefaultResponse>(url: string, config?: RequestHandlerConfig<ResponseData>): Promise<FetchResponse<ResponseData>>; | ||
export { type APIResponse, type ApiHandlerConfig, type ApiHandlerMethods, type ApiHandlerReturnType, type BodyPayload, type CacheBusterFunction, type CacheKeyFunction, type CacheOptions, type CacheSkipFunction, type CreatedCustomFetcherInstance, type EmptyObject, type Endpoint, type EndpointsConfig, type ErrorHandlingStrategy, type ExtendedResponse, type FetchResponse, type FetcherConfig, type FetcherInstance, type HeadersObject, type Method, type NativeFetch, type PollingFunction, type QueryParams, type QueryParamsOrBody, type RequestConfig, type RequestHandlerConfig, type RequestHandlerReturnType, type ResponseError, type RetryFunction, type RetryOptions, type UrlPathParams, createApiFetcher, fetchf }; | ||
export { type ApiHandlerConfig, type ApiHandlerDefaultMethods, type ApiHandlerMethods, type BodyPayload, type CacheBusterFunction, type CacheKeyFunction, type CacheOptions, type CacheSkipFunction, type CreatedCustomFetcherInstance, type DefaultParams, type DefaultPayload, type DefaultResponse, type DefaultUrlParams, type EmptyObject, type Endpoint, type EndpointsConfig, type ErrorHandlingStrategy, type ExtendedRequestConfig, type ExtendedResponse, type FallbackValue, type FetchResponse, type FetcherConfig, type FetcherInstance, type FinalParams, type FinalResponse, type HeadersObject, type Method, type NativeFetch, type PollingFunction, type QueryParams, type RequestConfig, type RequestConfigUrlRequired, type RequestEndpointFunction, type RequestHandlerConfig, type RequestHandlerReturnType, type ResponseError, type RetryFunction, type RetryOptions, type UrlPathParams, createApiFetcher, fetchf }; |
@@ -1,2 +0,2 @@ | ||
"use strict";var _=Object.defineProperty,Fe=Object.defineProperties,qe=Object.getOwnPropertyDescriptor,He=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,le=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,Se=Object.prototype.propertyIsEnumerable;var ee=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,C=(e,t)=>{for(var n in t||(t={}))ue.call(t,n)&&ee(e,n,t[n]);if(le)for(var n of le(t))Se.call(t,n)&&ee(e,n,t[n]);return e},B=(e,t)=>Fe(e,He(t));var Be=(e,t)=>{for(var n in t)_(e,n,{get:t[n],enumerable:!0})},Me=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ne(t))!ue.call(e,s)&&s!==n&&_(e,s,{get:()=>t[s],enumerable:!(o=qe(t,s))||o.enumerable});return e};var Ue=e=>Me(_({},"__esModule",{value:!0}),e);var A=(e,t,n)=>ee(e,typeof t!="symbol"?t+"":t,n);var Le={};Be(Le,{createApiFetcher:()=>_e,fetchf:()=>xe});module.exports=Ue(Le);async function O(e,t){if(t){if(typeof t=="function"){let n=await t(e);n&&Object.assign(e,n)}else if(Array.isArray(t))for(let n of t){let o=await n(e);o&&Object.assign(e,o)}}}var L=class extends Error{constructor(n,o,s){super(n);A(this,"response");A(this,"request");A(this,"config");A(this,"status");A(this,"statusText");this.name="ResponseError",this.message=n,this.status=s.status,this.statusText=s.statusText,this.request=o,this.config=o,this.response=s}};var M="application/json",j="Content-Type",x="undefined",b="object",J="string",$="AbortError",fe="TimeoutError",pe="CanceledError",U="GET",de="HEAD";function te(e){return e instanceof URLSearchParams}function Re(e){let t="";for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=n+":"+e[n]);return t}function ne(e){let t={},n=Object.keys(e);n.sort();for(let o=0,s=n.length;o<s;o++){let i=n[o];t[i]=e[i]}return t}function ye(e,t){return t?e.includes("?")?`${e}&${t}`:`${e}?${t}`:e}function me(e,t){if(!t)return e;if(te(t)){let l=t.toString();return ye(e,l)}let n=[],o=encodeURIComponent,s=(l,a)=>{a=typeof a=="function"?a():a,a=a===null||a===void 0?"":a,n[n.length]=o(l)+"="+o(a)},i=(l,a)=>{let d,g,y;if(l)if(Array.isArray(a))for(d=0,g=a.length;d<g;d++)i(l+"["+(typeof a[d]===b&&a[d]?d:"")+"]",a[d]);else if(typeof a===b&&a!==null)for(y in a)i(l+"["+y+"]",a[y]);else s(l,a);else if(Array.isArray(a))for(d=0,g=a.length;d<g;d++)s(a[d].name,a[d].value);else for(y in a)i(y,a[y]);return n},m=i("",t).join("&").replace(/%5B%5D/g,"[]");return ye(e,m)}function he(e,t){return t?e.replace(/:\w+/g,n=>{let o=n.substring(1);return String(t[o]?t[o]:n)}):e}function ge(e){let t=typeof e;if(t===x||e===null)return!1;if(t===J||t==="number"||t==="boolean"||Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;if(t===b){let n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null||typeof e.toJSON=="function")return!0}return!1}async function re(e){return new Promise(t=>setTimeout(()=>t(!0),e))}function se(e){return e&&typeof e===b&&typeof e.data!==x&&Object.keys(e).length===1?se(e.data):e}function Pe(e){if(!e)return{};let t={};if(e instanceof Headers)e.forEach((n,o)=>{t[o]=n});else if(typeof e===b&&e!==null)for(let[n,o]of Object.entries(e))t[n.toLowerCase()]=o;return t}function F(e,t){e&&t in e&&delete e[t]}var k=new Map;async function Ee(e,t,n=0,o=!1,s=!0){let i=Date.now(),h=k.get(e);if(h){let a=h[3],d=h[0],g=h[1];if(!a&&i-h[2]<n)return d;a&&d.abort(new DOMException("Aborted due to new request",$)),g!==null&&clearTimeout(g),k.delete(e)}let m=new AbortController,l=s?setTimeout(()=>{let a=new DOMException(`${e.url} aborted due to timeout`,fe);v(e,a)},t):null;return k.set(e,[m,l,i,o]),m}async function v(e,t=null){let n=k.get(e);if(n){let o=n[0],s=n[1];t&&!o.signal.aborted&&o.abort(t),s!==null&&clearTimeout(s),k.delete(e)}}async function Ce(e){var o;if(!(e!=null&&e.body))return null;let t=String(((o=e.headers)==null?void 0:o.get(j))||"").split(";")[0],n;try{if(t.includes(M)||t.includes("+json"))n=await e.json();else if(t.includes("multipart/form-data"))n=await e.formData();else if(t.includes("application/octet-stream"))n=await e.blob();else if(t.includes("application/x-www-form-urlencoded"))n=await e.formData();else if(t.includes("text/"))n=await e.text();else try{n=await e.clone().json()}catch(s){n=await e.text()}}catch(s){n=null}return n}function G(e){let t=0;for(let n=0,o=e.length;n<o;n++){let s=e.charCodeAt(n);t=t*31+s|0}return String(t)}var oe=new Map;function Te(e){let{url:t="",method:n=U,headers:o={},body:s="",mode:i="cors",credentials:h="include",cache:m="default",redirect:l="follow",referrer:a="",integrity:d=""}=e;if(m==="reload")return"";let g=Re(ne(o)),y="";if(s!==null)if(typeof s=="string")y=G(s);else if(s instanceof FormData)s.forEach((r,u)=>{y+=u+"="+r+"&"}),y=G(y);else if(typeof Blob!==x&&s instanceof Blob||typeof File!==x&&s instanceof File)y="BF"+s.size+s.type;else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))y="AB"+s.byteLength;else{let r=typeof s===b?ne(s):String(s);y=G(JSON.stringify(r))}return n+t+i+h+m+l+a+d+g+y}function ke(e,t){return t?Date.now()-e>t*1e3:!1}function be(e,t){let n=oe.get(e);if(n){if(!ke(n.timestamp,t))return n;oe.delete(e)}return null}function we(e,t,n=!1){oe.set(e,{data:t,isLoading:n,timestamp:Date.now()})}var Qe={method:U,strategy:"reject",timeout:3e4,dedupeTime:1e3,defaultResponse:null,headers:{Accept:M+", text/plain, */*","Accept-Encoding":"gzip, deflate, br",[j]:M+";charset=utf-8"},retry:{delay:1e3,maxDelay:3e4,resetTimeout:!0,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504]}};function z(e){let t=C(C({},Qe),e),n=t.fetcher,o=(n==null?void 0:n.create(t))||null,s=()=>o,i=(r,u)=>typeof r[u]!==x?r[u]:t[u],h=(...r)=>{var u;(u=t.logger)!=null&&u.warn&&t.logger.warn(...r)},m=(r,u,f)=>{let R=i(f,"method").toUpperCase(),P=R===U||R===de,c=he(r,i(f,"urlPathParams")),E=i(f,"params"),q=i(f,"body")||i(f,"data"),K=!!(u&&(P||q)),T;P||(T=q||u);let Q=i(f,"withCredentials")?"include":i(f,"credentials");F(f,"data"),F(f,"withCredentials");let D=E||K?me(c,E||u):c,w=D.includes("://")?"":i(f,"baseURL")||i(f,"apiUrl");return T&&typeof T!==J&&!te(T)&&ge(T)&&(T=JSON.stringify(T)),B(C({},f),{credentials:Q,body:T,method:R,url:w+D})},l=async(r,u)=>{d(r)||h("API ERROR",r),await O(r,u==null?void 0:u.onError),await O(r,t==null?void 0:t.onError)},a=async(r,u,f)=>{let R=d(r),P=i(f,"strategy"),c=i(f,"rejectCancelled");if(!(R&&!c)){if(P==="silent")await new Promise(()=>null);else if(P==="reject")return Promise.reject(r)}return y(u,f,r)},d=r=>r.name===$||r.name===pe,g=async(r,u=null,f=null)=>{var ie;let R=f||{},P=C(C({},t),R),c=null,E=m(r,u,P),{timeout:q,cancellable:K,dedupeTime:T,pollingInterval:Y,shouldStopPolling:Q,cacheTime:D,cacheKey:W}=P,w;if(W?w=W(E):w=Te(E),D&&w){let I=P.cacheBuster;if(!I||!I(E)){let p=be(w,D);if(p)return p.data}}let{retries:V=0,delay:Oe,backoff:De,retryOn:X,shouldRetry:ae,maxDelay:Ie,resetTimeout:Ae}=P.retry,H=0,Z=0,N=Oe;for(;H<=V;)try{let I=await Ee(E,q,T,K,!!(q&&(!V||Ae))),p=C({signal:I.signal},E);if(await O(p,R==null?void 0:R.onRequest),await O(p,t==null?void 0:t.onRequest),n!==null&&o!==null?c=await o.request(p):c=await fetch(p.url,p),c instanceof Response&&(c.config=p,c.data=await Ce(c),!c.ok))throw new L(`${p.url} failed! Status: ${c.status||null}`,p,c);if(await O(c,R==null?void 0:R.onResponse),await O(c,t==null?void 0:t.onResponse),v(E),Y&&(!Q||!Q(c,Z))){Z++,h(`Polling attempt ${Z}...`),await re(Y);continue}let S=y(c,p);if(D&&w){let ce=p.skipCache;(!ce||!ce(S,p))&&we(w,S)}return S}catch(I){let p=I,S=((ie=p==null?void 0:p.response)==null?void 0:ie.status)||(p==null?void 0:p.status)||0;if(H===V||!(!ae||await ae(p,H))||!(X!=null&&X.includes(S)))return await l(p,E),v(E),a(p,c,E);h(`Attempt ${H+1} failed. Retry in ${N}ms.`),await re(N),N*=De,N=Math.min(N,Ie),H++}return y(c,E)},y=(r,u,f=null)=>{let R=i(u,"defaultResponse"),P=i(u,"flattenResponse");if(!r)return P?R:{error:f,headers:null,data:R,config:u};F(f,"response"),F(f,"request"),F(f,"config");let c=r==null?void 0:r.data;return(c==null||typeof c===b&&Object.keys(c).length===0)&&(c=R),P?se(c):r instanceof Response?{body:r.body,bodyUsed:r.bodyUsed,formData:r.formData,ok:r.ok,redirected:r.redirected,type:r.type,url:r.url,status:r.status,statusText:r.statusText,blob:r.blob.bind(r),json:r.json.bind(r),text:r.text.bind(r),clone:r.clone.bind(r),arrayBuffer:r.arrayBuffer.bind(r),error:f,data:c,headers:Pe(r.headers),config:u}:r};return{getInstance:s,buildConfig:m,config:e,request:g}}function _e(e){let t=e.endpoints,n=z(e);function o(){return n.getInstance()}function s(l){return console.error(`Add ${l} to 'endpoints'.`),Promise.resolve(null)}async function i(l,a={},d={},g={}){let y=t[l];return await n.request(y.url,a,B(C(C({},y||{}),g),{urlPathParams:d}))}function h(l){return l in m?m[l]:t[l]?m.request.bind(null,l):s.bind(null,l)}let m={config:e,endpoints:t,requestHandler:n,getInstance:o,request:i};return new Proxy(m,{get:(l,a)=>h(a)})}async function xe(e,t={}){return z(t).request(e,null,t)}0&&(module.exports={createApiFetcher,fetchf}); | ||
"use strict";var Y=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})},xe=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of be(t))!we.call(e,a)&&a!==n&&Y(e,a,{get:()=>t[a],enumerable:!(s=Te(t,a))||s.enumerable});return e};var qe=e=>xe(Y({},"__esModule",{value:!0}),e);var He={};Oe(He,{createApiFetcher:()=>Ae,fetchf:()=>Ne});module.exports=qe(He);async function T(e,t){if(t){if(typeof t=="function"){let n=await t(e);n&&Object.assign(e,n)}else if(Array.isArray(t))for(let n of t){let s=await n(e);s&&Object.assign(e,s)}}}var B=class extends Error{response;request;config;status;statusText;constructor(t,n,s){super(t),this.name="ResponseError",this.message=t,this.status=s.status,this.statusText=s.statusText,this.request=n,this.config=n,this.response=s}};var k="application/",I=k+"json",M="Content-Type",E="undefined",C="object",Q="string",L="AbortError",se="TimeoutError",oe="CanceledError",A="GET",ae="HEAD";function K(e){return e instanceof URLSearchParams}function le(e){let t="";for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=n+":"+e[n]);return t}function V(e){let t={},n=Object.keys(e);n.sort();for(let s=0,a=n.length;s<a;s++){let l=n[s];t[l]=e[l]}return t}function ie(e,t){return t?e.includes("?")?`${e}&${t}`:`${e}?${t}`:e}function ue(e,t){if(!t)return e;if(K(t)){let c=t.toString();return ie(e,c)}let n=[],s=encodeURIComponent,a=(c,o)=>{o=typeof o=="function"?o():o,o=o===null||o===void 0?"":o,n[n.length]=s(c)+"="+s(o)},l=(c,o)=>{let f,h,d;if(c)if(Array.isArray(o))for(f=0,h=o.length;f<h;f++)l(c+"["+(typeof o[f]===C&&o[f]?f:"")+"]",o[f]);else if(typeof o===C&&o!==null)for(d in o)l(c+"["+d+"]",o[d]);else a(c,o);else if(Array.isArray(o))for(f=0,h=o.length;f<h;f++)a(o[f].name,o[f].value);else for(d in o)l(d,o[d]);return n},y=l("",t).join("&").replace(/%5B%5D/g,"[]");return ie(e,y)}function ce(e,t){return t?e.replace(/:\w+/g,n=>{let s=n.substring(1);return t[s]?String(t[s]):n}):e}function fe(e){let t=typeof e;if(t===E||e===null)return!1;if(t===Q||t==="number"||t==="boolean"||Array.isArray(e))return!0;if(Buffer.isBuffer(e)||e instanceof Date)return!1;if(t===C){let n=Object.getPrototypeOf(e);if(n===Object.prototype||n===null||typeof e.toJSON=="function")return!0}return!1}async function W(e){return new Promise(t=>setTimeout(()=>t(!0),e))}function X(e){return e&&typeof e===C&&typeof e.data!==E&&Object.keys(e).length===1?X(e.data):e}function pe(e){if(!e)return{};let t={};if(e instanceof Headers)e.forEach((n,s)=>{t[s]=n});else if(typeof e===C&&e!==null)for(let[n,s]of Object.entries(e))t[n.toLowerCase()]=s;return t}function v(e,t){e&&t in e&&delete e[t]}var N=new Map;async function de(e,t,n=0,s=!1,a=!0){let l=Date.now(),R=N.get(e);if(R){let o=R[3],f=R[0],h=R[1];if(!o&&l-R[2]<n)return f;o&&f.abort(new DOMException("Aborted due to new request",L)),h!==null&&clearTimeout(h),N.delete(e)}let y=new AbortController,c=a?setTimeout(()=>{let o=new DOMException(`${e.url} aborted due to timeout`,se);j(e,o)},t):null;return N.set(e,[y,c,l,s]),y}async function j(e,t=null){let n=N.get(e);if(n){let s=n[0],a=n[1];t&&!s.signal.aborted&&s.abort(t),a!==null&&clearTimeout(a),N.delete(e)}}async function Re(e){if(!e?.body)return null;let t=String(e.headers?.get(M)||"").split(";")[0],n;try{if(t.includes(I)||t.includes("+json"))n=await e.json();else if(t.includes("multipart/form-data"))n=await e.formData();else if(t.includes(k+"octet-stream"))n=await e.blob();else if(t.includes(k+"x-www-form-urlencoded"))n=await e.formData();else if(t.includes("text/"))n=await e.text();else try{n=await e.clone().json()}catch{n=await e.text()}}catch{n=null}return n}function J(e){let t=0;for(let n=0,s=e.length;n<s;n++){let a=e.charCodeAt(n);t=t*31+a|0}return String(t)}var Z=new Map;function me(e){let{url:t="",method:n=A,headers:s={},body:a="",mode:l="cors",credentials:R="include",cache:y="default",redirect:c="follow",referrer:o="",integrity:f=""}=e;if(y==="reload")return"";let h=le(V(s)),d="";if(a!==null)if(typeof a=="string")d=J(a);else if(a instanceof FormData)a.forEach((r,u)=>{d+=u+"="+r+"&"}),d=J(d);else if(typeof Blob!==E&&a instanceof Blob||typeof File!==E&&a instanceof File)d="BF"+a.size+a.type;else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))d="AB"+a.byteLength;else{let r=typeof a===C?V(a):String(a);d=J(JSON.stringify(r))}return n+t+l+R+y+c+o+f+h+d}function Fe(e,t){return t?Date.now()-e>t*1e3:!1}function ye(e,t){let n=Z.get(e);if(n){if(!Fe(n.timestamp,t))return n;Z.delete(e)}return null}function ge(e,t,n=!1){Z.set(e,{data:t,isLoading:n,timestamp:Date.now()})}var Ie={method:A,strategy:"reject",timeout:3e4,dedupeTime:1e3,defaultResponse:null,headers:{Accept:I+", text/plain, */*","Accept-Encoding":"gzip, deflate, br",[M]:I+";charset=utf-8"},retry:{delay:1e3,maxDelay:3e4,resetTimeout:!0,backoff:1.5,retryOn:[408,409,425,429,500,502,503,504]}};function $(e){let t={...Ie,...e},n=t.fetcher,s=n?.create(t)||null,a=()=>s,l=(r,u)=>typeof r[u]!==E?r[u]:t[u],R=(...r)=>{t.logger?.warn&&t.logger.warn(...r)},y=(r,u)=>{let m=l(u,"method").toUpperCase(),P=m===A||m===ae,i=ce(r,l(u,"urlPathParams")),g=l(u,"params"),H=l(u,"body")||l(u,"data"),D;P||(D=H);let U=l(u,"withCredentials")?"include":l(u,"credentials"),w=g?ue(i,g):i,_=w.includes("://")?"":l(u,"baseURL")||l(u,"apiUrl");return D&&typeof D!==Q&&!K(D)&&fe(D)&&(D=JSON.stringify(D)),{...u,credentials:U,body:D,method:m,url:_+w}},c=async(r,u)=>{f(r)||R("API ERROR",r),await T(r,u?.onError),await T(r,t?.onError)},o=async(r,u,m)=>{let P=f(r),i=l(m,"strategy"),g=l(m,"rejectCancelled");if(!(P&&!g)){if(i==="silent")await new Promise(()=>null);else if(i==="reject")return Promise.reject(r)}return d(u,m,r)},f=r=>r.name===L||r.name===oe,h=async(r,u=null)=>{let m=u||{},P={...t,...m},i=null,g=y(r,P),{timeout:H,cancellable:D,dedupeTime:ee,pollingInterval:U,shouldStopPolling:w,cacheTime:S,cacheKey:_}=P,b;if(_?b=_(g):b=me(g),S&&b){let q=P.cacheBuster;if(!q||!q(g)){let p=ye(b,S);if(p)return p.data}}let{retries:G=0,delay:he,backoff:Pe,retryOn:De,shouldRetry:te,maxDelay:Ce,resetTimeout:Ee}=P.retry,O=0,z=0,x=he,ne=G>0?G:0;for(;O<=ne;)try{let p={signal:(await de(g,H,ee,D,!!(H&&(!ne||Ee)))).signal,...g};if(await T(p,m?.onRequest),await T(p,t?.onRequest),n!==null&&s!==null?i=await s.request(p):i=await fetch(p.url,p),i instanceof Response&&(i.config=p,i.data=await Re(i),!i.ok))throw new B(`${p.url} failed! Status: ${i.status||null}`,p,i);if(await T(i,m?.onResponse),await T(i,t?.onResponse),j(g),U&&(!w||!w(i,z))){z++,R(`Polling attempt ${z}...`),await W(U);continue}let F=d(i,p);if(S&&b){let re=p.skipCache;(!re||!re(F,p))&&ge(b,F)}return F}catch(q){let p=q,F=p?.response?.status||p?.status||0;if(O===G||!(!te||await te(p,O))||!De?.includes(F))return await c(p,g),j(g),o(p,i,g);R(`Attempt ${O+1} failed. Retry in ${x}ms.`),await W(x),x*=Pe,x=Math.min(x,Ce),O++}return d(i,g)},d=(r,u,m=null)=>{let P=l(u,"defaultResponse");if(!r)return{ok:!1,error:m,data:P,headers:null,config:u};v(m,"response"),v(m,"request"),v(m,"config");let i=r?.data;return(i==null||typeof i===C&&Object.keys(i).length===0)&&(i=P),l(u,"flattenResponse")&&(r.data=X(i)),r instanceof Response?{body:r.body,bodyUsed:r.bodyUsed,formData:r.formData,ok:r.ok,redirected:r.redirected,type:r.type,url:r.url,status:r.status,statusText:r.statusText,blob:r.blob.bind(r),json:r.json.bind(r),text:r.text.bind(r),clone:r.clone.bind(r),arrayBuffer:r.arrayBuffer.bind(r),error:m,data:i,headers:pe(r.headers),config:u}:r};return{getInstance:a,buildConfig:y,config:e,request:h}}function Ae(e){let t=e.endpoints,n=$(e);function s(){return n.getInstance()}function a(y){return console.error(`Add ${y} to 'endpoints'.`),Promise.resolve(null)}async function l(y,c={}){let o=t[y]||{url:y};return await n.request(o.url,{...o,...c})}let R={config:e,endpoints:t,requestHandler:n,getInstance:s,request:l};return new Proxy(R,{get(y,c){return c in R?R[c]:t[c]?R.request.bind(null,c):a.bind(null,c)}})}async function Ne(e,t={}){return $(t).request(e,t)}0&&(module.exports={createApiFetcher,fetchf}); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"version": "2.9.0", | ||
"name": "fetchff", | ||
"version": "3.0.0", | ||
"license": "UNLICENSED", | ||
"name": "fetchff", | ||
"author": "Matt Czapliński <deindesign.pl@gmail.com>", | ||
@@ -14,2 +14,3 @@ "repository": { | ||
"types": "dist/index.d.ts", | ||
"unpkg": "./dist/browser/index.mjs", | ||
"keywords": [ | ||
@@ -19,8 +20,14 @@ "fetch", | ||
"fetch-wrapper", | ||
"fetch-client", | ||
"request", | ||
"cache", | ||
"fetch-cache", | ||
"fetch-retry", | ||
"api", | ||
"api-handler", | ||
"http-request", | ||
"http-client", | ||
"browser", | ||
"node" | ||
"node", | ||
"nodejs" | ||
], | ||
@@ -30,6 +37,7 @@ "engines": { | ||
}, | ||
"sideEffects": false, | ||
"scripts": { | ||
"build": "npm run build:node && npm run build:browser && npm run build:cleanup", | ||
"build:browser": "tsup --format esm,iife --out-dir dist/browser --env.NODE_ENV production", | ||
"build:node": "tsup --format cjs --out-dir dist/node --env.NODE_ENV production", | ||
"build:node": "tsup --format cjs --out-dir dist/node --env.NODE_ENV production --target node18", | ||
"build:cleanup": "rm -f dist/browser/index.d.mts dist/node/index.d.ts && mv dist/browser/index.d.ts dist/index.d.ts", | ||
@@ -53,24 +61,28 @@ "type-check": "tsc --noEmit", | ||
"path": "dist/browser/index.mjs", | ||
"limit": "10 KB" | ||
"limit": "5 KB" | ||
}, | ||
{ | ||
"path": "dist/browser/index.global.js", | ||
"limit": "50 KB" | ||
"limit": "5 KB" | ||
}, | ||
{ | ||
"path": "dist/node/index.js", | ||
"limit": "5 KB" | ||
} | ||
], | ||
"devDependencies": { | ||
"@size-limit/preset-small-lib": "11.1.4", | ||
"@types/jest": "29.5.12", | ||
"eslint": "9.10.0", | ||
"@size-limit/preset-small-lib": "11.1.5", | ||
"@types/jest": "29.5.13", | ||
"eslint": "9.11.1", | ||
"eslint-config-prettier": "9.1.0", | ||
"eslint-plugin-prettier": "5.2.1", | ||
"fetch-mock": "11.0.0", | ||
"fetch-mock": "11.1.5", | ||
"jest": "29.7.0", | ||
"prettier": "3.3.3", | ||
"size-limit": "11.1.4", | ||
"ts-jest": "29.2.4", | ||
"size-limit": "11.1.5", | ||
"ts-jest": "29.2.5", | ||
"tslib": "2.7.0", | ||
"tsup": "8.2.4", | ||
"tsup": "8.3.0", | ||
"typescript": "5.6.2", | ||
"typescript-eslint": "8.5.0" | ||
"typescript-eslint": "8.8.0" | ||
}, | ||
@@ -77,0 +89,0 @@ "optionalDependencies": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
129606
539
1718