idmp
Version:
A lightweight TypeScript library for deduplicating and caching async function calls with automatic retries, designed for idempotent network requests in React and Node.js.
3 lines (2 loc) • 1.63 kB
JavaScript
/*! idmp v3.4.4 | (c) github/haozi | MIT */
(function(o,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(o=typeof globalThis!="undefined"?globalThis:o||self,u(o.idmp={}))})(this,function(o){"use strict";var _=Math.pow;const M=()=>{},x=setTimeout,T=(t,s)=>t>s?t:s,F=(t,s)=>t<s?t:s,L=t=>t<0?0:t>6048e5?6048e5:t;let f={};const D=t=>{const{maxRetry:s=30,maxAge:d=3e3,minRetryDelay:a=50,maxRetryDelay:h=5e3,onBeforeRetry:p=M,signal:y}=t||{},A=L(d);return{maxRetry:s,maxAge:A,minRetryDelay:a,maxRetryDelay:h,onBeforeRetry:p,f:d===1/0,signal:y}},m=t=>{t&&delete f[t]},N=()=>{f={}},c=(t,s,d)=>{if(!t)return s();const{maxRetry:a,minRetryDelay:h,maxRetryDelay:p,maxAge:y,onBeforeRetry:A,f:O,signal:l}=D(d);f[t]=f[t]||[0,0,[]];const e=f[t],E=()=>{e[1]=0,e[3]=e[4]=void 0},P=()=>{const i=e[2].length;for(let n=0;n<i;++n)e[2][n][0](e[3]);e[2]=[],O||x(()=>{m(t)},y)},R=()=>{const i=e[2].length;let n;n=i-a,(n<0||!isFinite(i))&&(n=T(1,e[2].length-3));for(let r=0;r<n;++r)e[2][r][1](e[4]);m(t)},g=()=>new Promise((i,n)=>{if(!e[5]&&(e[5]=s),e[3]){i(e[3]);return}if(l){if(l.aborted)return;l.addEventListener("abort",()=>{E(),e[4]=new DOMException(l.reason,"AbortError"),R()})}e[1]===0?(e[1]=1,e[2].push([i,n]),e[5]().then(r=>{e[3]=r,P(),e[1]=4}).catch(r=>{if(e[1]=3,e[4]=r,++e[0],e[0]>a)R();else{A(r,{globalKey:t,retryCount:e[0]}),E();const U=F(p,h*_(2,e[0]-1));x(g,U)}})):e[1]===1&&e[2].push([i,n])});return g()};c.flush=m,c.flushAll=N,o.default=c,o.getOptions=D,o.idmp=c,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});