@creejs/commons-retrier 2.1.13 → 2.1.15

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.
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).CommonsLang={})}(this,function(t){"use strict";var e=function(t,...e){if(null==t)throw new TypeError('"target" must not be null or undefined');for(const s of e)if(null!=s)for(const e in s)void 0===t[e]&&(t[e]=s[e]);return t};var s={isNumber:r,isNil:n};function n(t){return null==t}function r(t){return null!=t&&"number"==typeof t}function i(t){return null!=t&&"function"==typeof t.then}var o={assertNumber:c,assertPositive:function(t,e){if(!function(t){return!!r(t)&&t>0}(t))throw new Error(`${e?'"'+e+'" ':" "}Not Positive: ${t}`)},assertNotNegative:l,assertFunction:h,assertNotNil:function(t,e){if(n(t))throw new Error((e?'"'+e+'" ':" ")+"Should Not Nil")},assertString:function(t,e){if(!function(t){return null!=t&&"string"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':" "}Not String: type=${typeof t} value=${JSON.stringify(t)}`)}};function a(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':" "}Not Array: type=${typeof t} value=${JSON.stringify(t)}`)}function c(t,e){if(!r(t))throw new Error(`${e?'"'+e+'" ':" "}Not Number: type=${typeof t} value=${JSON.stringify(t)}`)}function l(t,e){if(!function(t){return!!r(t)&&t>=0}(t))throw new Error(`${e?'"'+e+'" ':" "}Not "0 or Positive": ${t}`)}function h(t,e){if(!function(t){return"function"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':" "}Not Function: type=${typeof t} value=${JSON.stringify(t)}`)}function u(t,e){if(!i(t))throw new Error(`${e?'"'+e+'" ':" "}Not Promise: type=${typeof t} value=${JSON.stringify(t)}`)}var f={defer:m,delay:function(t,e){r(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&u(t),c(e=e??1e3);const s=m(),n=Date.now();return t.then((...t)=>{const r=Date.now()-n;r<e?setTimeout(()=>s.resolve(...t),e-r):s.resolve(...t)}).catch(t=>{const r=Date.now()-n;r<e?setTimeout(()=>s.reject(t),e-r):s.reject(t)}),s.promise},timeout:function(t,e,s){u(t),c(e=e??1);const n=m(e,s),r=Date.now();return t.then((...t)=>{Date.now()-r<=e?n.resolve(...t):n.reject(new Error(s??`Promise Timeout: ${e}ms`))}).catch(t=>{!n.resolved&&!n.rejected&&n.reject(t)}),n.promise},allSettled:_,returnValuePromised:w,series:async function(t){a(t);const e=[];for(const s of t)h(s),e.push(await s());return e},seriesAllSettled:async function(t){a(t);const e=[];for(const s of t){h(s);try{e.push({ok:!0,result:await s()})}catch(t){e.push({ok:!1,result:t})}}return e},parallel:async function(t,e=5){if(a(t),c(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>h(t));const s=[];if(t.length<=e){const e=await Promise.all(t.map(t=>w(t)));return s.push(...e),s}const n=[];for(const r of t)if(h(r),n.push(r),n.length>=e){const t=await Promise.all(n.map(t=>w(t)));s.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await Promise.all(n.map(t=>w(t)));s.push(...t)}return s},parallelAllSettled:async function(t,e=5){if(a(t),c(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>h(t));const s=[];if(t.length<=e){const e=await _(t.map(t=>w(t)));return s.push(...e),s}const n=[];for(const r of t)if(h(r),n.push(r),n.length>=e){const t=await _(n.map(t=>w(t)));s.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await _(n.map(t=>w(t)));s.push(...t)}return s},wait:function(t){l(t);const e={};let s;return e.timerHandler=s=setTimeout(()=>{clearTimeout(s),e.resolve()},t),e.promise=new Promise((t,n)=>{e.resolve=e=>{null!=s&&clearTimeout(s),t(e)}}),e}};function m(t=-1,e){c(t);const s={};let n;return t>=0&&(s.timerHandler=n=setTimeout(()=>{clearTimeout(n),s.timerCleared=!0,s.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),s.promise=new Promise((t,e)=>{s.resolve=e=>{null!=n&&(clearTimeout(n),s.timerCleared=!0),s.resolved=!0,t(e)},s.reject=t=>{null!=n&&(clearTimeout(n),s.timerCleared=!0),s.rejected=!0,e(t)}}),s.promise.cancel=()=>{null!=n&&(clearTimeout(n),s.timerCleared=!0),s.rejected=!0,s.canceled=s.promise.canceled=!0,s.reject(new Error("Cancelled"))},s}async function _(t){a(t);const e=await Promise.allSettled(t),s=[];for(const t of e)"fulfilled"===t.status&&s.push({ok:!0,result:t.value}),"rejected"===t.status&&s.push({ok:!1,result:t.reason});return s}function w(t){try{const e=t();return i(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:d,assertNotNegative:p}=o,{isNumber:g}=s;class v{constructor(){this._min=50,this._max=3e4,this._nextInterval=this._min,this._jitter=0}get jitter(){return this._jitter}set jitter(t){p(t,"jitter"),this._jitter=t}copyPolicySettingTo(t){t.range(this._min,this._max),t._nextInterval=this._nextInterval}range(t,e){if(d(t,"min"),d(e,"max"),t>=e)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this._max=e,this._nextInterval>this._max&&(this._nextInterval=this._max),this}min(t){if(d(t,"min"),t>=this._max)throw new Error("min must < max");return this._min=t,this._nextInterval=this._min,this}max(t){if(d(t,"max"),t<=this._min)throw new Error("max must > min");return this._max=t,this._nextInterval>this._max&&(this._nextInterval=this._max),this}reset(){return this._nextInterval=this._min,this}generate(t){const e=this._nextInterval;return this._increase(t),e}_increase(t){const e=this._next(t);if(!g(e))throw new Error("Generated Next Interval Not Number");const s=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return s<this._min?this._nextInterval=this._min:s>this._max?this._nextInterval=this._max:this._nextInterval=s}_next(t){throw new Error("Not Impled Yet")}}var x={isFunction:y,isNil:k};function y(t){return"function"==typeof t}function k(t){return null==t}function L(t){return null!=t&&"string"==typeof t}var E={assertNumber:function(t,e){if(!function(t){return null!=t&&"number"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':" "}Not Number: type=${typeof t} value=${JSON.stringify(t)}`)},assertFunction:function(t,e){if(!y(t))throw new Error(`${e?'"'+e+'" ':" "}Not Function: type=${typeof t} value=${JSON.stringify(t)}`)},assertNotNil:function(t,e){if(k(t))throw new Error((e?'"'+e+'" ':" ")+"Should Not Nil")},assertString:function(t,e){if(!L(t))throw new Error(`${e?'"'+e+'" ':" "}Not String: type=${typeof t} value=${JSON.stringify(t)}`)},assertStringOrSymbol:function(t,e){if(!L(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':" "}Not String or Symbol: type=${typeof t} value=${JSON.stringify(t)}`)}};new TextDecoder,new TextEncoder;const b="DOwner$#$",{assertFunction:N,assertNotNil:S}=E;class T{constructor(t,e,s=!1){S(t,"event"),N(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!s,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===b?void 0:this._owner}get event(){return this._event}get isOnce(){return this._isOnce}isSameCallback(t){return this._callback===t}get callback(){return this._callback}invoke(...t){try{return this._callback(...t)}finally{if(this._isOnce)try{this._event._remove(this)}catch(t){console.warn(t)}}}listener(...t){return this.invoke(...t)}}const{isFunction:O,isNil:R}=x,{assertStringOrSymbol:I,assertFunction:$}=E;class P{static get DefaultOwner(){return b}constructor(t){I(t,"eventName"),this._name=t,this._callbacks=new Set,this._listeners=[],this._callback2Listeners=new Map,this._listener2Owner=new Map,this._owner2Listeners=new Map}get name(){return this._name}isEmpty(){return 0===this._callbacks.size}rawListeners(){return[...this._listeners]}listenerCount(t){return null==t?this._listeners.length:this._callback2Listeners.get(t)?.size??0}callbacks(){return[...this.rawListeners().map(t=>t.callback)]}emit(...t){if(0===this._listeners.length)return!1;for(const e of[...this._listeners])e.invoke(...t);return!0}emitOwner(t,...e){if(0===this._listeners.length)return!1;const s=this._owner2Listeners.get(t);if(null==s)return!1;for(const t of[...s])t.invoke(...e);return!0}hasListener(t){return!!O(t)&&this._callbacks.has(t)}hasOwner(t){return!R(t)&&this._owner2Listeners.has(t)}addListener(t,e){return this._addListener(t,e,!1,!1)}prependListener(t,e){return this._addListener(t,e,!1,!0)}addOnceListener(t,e){return this._addListener(t,e,!0,!1)}prependOnceListener(t,e){return this._addListener(t,e,!0,!0)}_addListener(t,e,s,n){if(R(t))return!1;$(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??b;const r=new T(this,t,s);r.owner=e,n?this._listeners.unshift(r):this._listeners.push(r),this._listener2Owner.set(r,e);let i=this._callback2Listeners.get(t);null==i&&(i=new Set,this._callback2Listeners.set(t,i)),i.add(r);let o=this._owner2Listeners.get(e);return null==o&&(o=new Set,this._owner2Listeners.set(e,o)),o.add(r),!0}removeListener(t){if(R(t))return!1;if(!this._callbacks.has(t))return!1;this._callbacks.delete(t);const e=this._callback2Listeners.get(t);if(null==e)return!1;this._callback2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1);const e=this._listener2Owner.get(t);if(null==e)continue;this._listener2Owner.delete(t);const s=this._owner2Listeners.get(e);null!=s&&(s.delete(t),0===s.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:s}=t,n=this._callback2Listeners.get(s);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(s),this._callbacks.delete(s)));const r=this._listener2Owner.get(t);if(null==r)return;this._listener2Owner.delete(t);const i=this._owner2Listeners.get(r);null!=i&&(i.delete(t),0===i.size&&this._owner2Listeners.delete(r))}removeAllListeners(t){if(R(t))return this._callbacks.clear(),this._listeners.length=0,this._callback2Listeners.clear(),this._listener2Owner.clear(),this._owner2Listeners.clear(),this;const e=this._owner2Listeners.get(t);if(null==e)return this;this._owner2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1),this._listener2Owner.delete(t);const{callback:e}=t,s=this._callback2Listeners.get(e);null!=s&&(s.delete(t),0===s.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:F}=x,{assertString:j,assertFunction:M,assertNumber:C,assertStringOrSymbol:B,assertNotNil:A}=E,D=["on","once","addListener","prependListener","prependOnceListener","off","offAll","offOwner","removeAllListeners","removeListener","emit","emitOwner","setMaxListeners","getMaxListeners","hasOwner","listeners","listenerCount","eventNames","rawListeners"];let J=10;class z{static mixin(t){const e=new z;t.__emitter=e;for(const s of D){const n=e[s];t[s]=n.bind(e)}return t}static get defaultMaxListeners(){return J}static set defaultMaxListeners(t){C(t),J=t??10}constructor(){this._name2Event=new Map,this._maxListeners=J}addListener(t,e,s){return this.on(t,e,s)}prependListener(t,e,s){return j(t),M(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,s),this}prependOnceListener(t,e,s){return j(t),M(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,s),this}emit(t,...e){const s=this._name2Event.get(t);return null!=s&&!s.isEmpty()&&(s.emit(...e),!0)}emitOwner(t,e,...s){if(null==e)throw new Error('Missing "owner"');const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emitOwner(e,...s),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){B(t,"eventName");const s=this._name2Event.get(t);return null==s||s.isEmpty()?0:s.listenerCount(e)}listeners(t){B(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const s=this._name2Event.get(t);return null==s?this:(s.removeListener(e),s.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){B(t,"eventName");const s=this._name2Event.get(t);return null==s?this:(s.removeAllListeners(e),s.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){A(t,"owner");const e=[...this._name2Event.values()];for(const s of e)s.removeAllListeners(t),s.isEmpty()&&this._name2Event.delete(s.name);return this}on(t,e,s){return j(t),M(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,s),this}_checkMaxListeners(t){let e=0;0!==this._maxListeners&&this._maxListeners!==1/0&&(e=this.listenerCount(t))>=this._maxListeners&&console.warn(`maxlistenersexceededwarning: Possible EventEmitter memory leak detected. ${e} ${t} listeners added to [${this}]. Use emitter.setMaxListeners() to increase limit`)}once(t,e,s){return j(t),M(e),this._getOrCreateEvent(t).addOnceListener(e,s),this}rawListeners(t){return this._name2Event.get(t)?.rawListeners()||[]}removeAllListeners(t,e){return this.offAll(t,e)}removeListener(t,e){return this.off(t,e)}setMaxListeners(t){if(C(t),t<0)throw new RangeError("maxListeners must >=0");return this._maxListeners=t,this}_getOrCreateEvent(t){if(this._name2Event.has(t))return this._name2Event.get(t);const e=new P(t);return this._name2Event.set(t,e),e}hasOwner(t){if(F(t))return!1;for(const e of this._name2Event.values())if(e.hasOwner(t))return!0;return!1}}var W={Start:"start",Retry:"retry",Success:"success",Failure:"failure",Timeout:"timeout",TaskTimeout:"task-timeout",Stop:"stop",Completed:"complete",MaxRetries:"max-retries"};const{assertPositive:H}=o;class G extends v{constructor(t){super(),H(t,"interval"),this._interval=t}set interval(t){H(t,"interval"),this._interval=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:U}=o;class V extends v{constructor(t){super(),U(t,"increasement"),this._increasement=t}set increasement(t){U(t,"increasement"),this._increasement=t}get increasement(){return this._increasement}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval+this.increasement}}const{assertPositive:Y}=o;class q extends v{constructor(t){if(super(),Y(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(Y(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}get factor(){return this._factor}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval*this.factor}}const{assertPositive:K}=o;class Q extends v{constructor(t){super(),K(t,"stepLength"),this._stepLength=t,this.increasement=t}set stepLength(t){K(t,"stepLength"),this._stepLength=t,this.increasement=t}get stepLength(){return this._stepLength}_next(t){const e=this._nextInterval+this.increasement;return e>=this._max?(this.increasement=-this.stepLength,this._max):e<=this._min?(this.increasement=this.stepLength,this._min):e}}const{assertNotNegative:X}=o;class Z extends G{constructor(t,e=500){super(t),X(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:tt}=o;class et extends q{constructor(t=500){super(2),tt(t,"jitter"),this._jitter=t??500}}const{assertNotNegative:st}=o;class nt extends V{constructor(t,e=500){super(t),st(e,"jitter"),this._jitter=e??500}}const{assertNotNil:rt,assertFunction:it}=o;class ot{constructor(t,e){rt(t,"retrier"),it(e,"task"),this.retrier=t,this.task=e,this.result=void 0,this.error=void 0}get failed(){return null!=this.error}get succeeded(){return null==this.error}async execute(t,e,s){try{this.result=await this.task(t,e,s),this.error=void 0}catch(t){this.error=t instanceof Error?t:new Error(String(t))}}dispose(){this.retrier=void 0}}class at extends ot{static isAlwaysTask(t){return t instanceof at}constructor(t,e,s){super(t,e),this.resetPolicy=s}async execute(t,e,s){await super.execute(t,e,s),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:ct,assertString:lt,assertFunction:ht,assertNumber:ut}=o,{isNil:ft}=s,mt="!#@%$&^*";class _t{static naming(t){const e=new _t;return e.name(t),e}static infinite(){const t=new _t;return t.infinite(),t}static times(t){const e=new _t;return e.times(t),e}static maxRetries(t){const e=new _t;return e.maxRetries(t),e}static min(t){const e=new _t;return e.min(t),e}static max(t){const e=new _t;return e.max(t),e}static range(t,e){const s=new _t;return s.range(t,e),s}static fixedInterval(t){const e=new _t;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const s=new _t;return s.fixedBackoff(t,e),s}static fixedIncrease(t){const e=new _t;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const s=new _t;return s.linearBackoff(t,e),s}static factorIncrease(t){const e=new _t;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new _t;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new _t;return e.shuttleInterval(t),e}static timeout(t){const e=new _t;return e.timeout(t),e}static taskTimeout(t){const e=new _t;return e.taskTimeout(t),e}static start(t){const e=new _t;return e.task(t),e.start()}constructor(t){z.mixin(this),this._policy=new G(t??1e3),this._maxRetries=3,this._currentRetries=1,this._timeout=12e4,this._taskTimeout=2e3,this._name="unamed",this._taskingFlag=void 0,this._breakFlag=void 0,this._breakReason=void 0}get running(){return!ft(this._taskingFlag)}name(t){return lt(t,"retrierName"),this._name=t,this}infinite(){return this._maxRetries=1/0,this}times(t){return this.maxRetries(t)}maxRetries(t){return ct(t,"maxRetries"),this._maxRetries=t,this}min(t){return this._policy.min(t),this}max(t){return this._policy.max(t),this}range(t,e){return this._policy.range(t,e),this}fixedInterval(t){const e=this._policy;if(e instanceof G)return e.interval=t,this;const s=new G(t);return e?.copyPolicySettingTo(s),s.reset(),this._policy=s,this}fixedBackoff(t,e=500){const s=this._policy;if(s instanceof G)return s.interval=t,s.jitter=e,this;const n=new Z(t,e);return s?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedIncrease(t){const e=this._policy;if(e instanceof V)return e.increasement=t,this;const s=new V(t);return e?.copyPolicySettingTo(s),s.reset(),this._policy=s,this}linearBackoff(t,e=500){const s=this._policy;if(s instanceof nt)return s.increasement=t,s.jitter=e,this;const n=new nt(t,e);return s?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}factorIncrease(t){const e=this._policy;if(e instanceof q)return e.factor=t,this;const s=new q(t);return e?.copyPolicySettingTo(s),s.reset(),this._policy=s,this}exponentialBackoff(t=500){const e=this._policy;if(e instanceof et)return e.jitter=t,this;const s=new et(t);return e?.copyPolicySettingTo(s),s.reset(),this._policy=s,this}shuttleInterval(t){const e=this._policy;if(e instanceof Q)return e.stepLength=t,this;const s=new Q(t);return e?.copyPolicySettingTo(s),s.reset(),this._policy=s,this}taskTimeout(t){return ct(t,"timeout"),this._taskTimeout=t,this}timeout(t){return ut(t,"timeout"),this._timeout=t,this}notimeout(){return this._timeout=0,this}task(t){return ht(t,"task"),this._task=new ot(this,t),this}retry(t){return this.task(t),this}always(t,e=!1){return this._task=new at(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");if(null!=this._taskingFlag)return this._taskingFlag.promise;const t=Date.now();let e;this.emit(W.Start,t),this._taskingFlag=f.defer();let s=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(s=Date.now()-t,!wt(this._timeout)&&s>=this._timeout){if(this.emit(W.Timeout,this._currentRetries,s,this._timeout),at.isAlwaysTask(this._task)){this._taskingFlag.resolve();break}this._taskingFlag.reject(e??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(W.Retry,this._currentRetries,s);const n=this._task,r=this._policy.generate(this._currentRetries);try{try{await f.timeout(n.execute(this._currentRetries,s,r),this._taskTimeout,mt)}catch(t){throw t.message===mt&&this.emit(W.TaskTimeout,this._currentRetries,s,this._taskTimeout),t}if(n.failed)throw e=n.error,n.error;const t=n.result;if(this.emit(W.Success,t,this._currentRetries,s),!at.isAlwaysTask(n)){this._taskingFlag.resolve(t);break}}catch(t){this.emit(W.Failure,t,this._currentRetries,s)}const i=++this._currentRetries;if(this._currentRetries>this._maxRetries){if(this.emit(W.MaxRetries,i,this._maxRetries),at.isAlwaysTask(n)){this._taskingFlag.resolve();break}this._taskingFlag.reject(e??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=f.wait(r),await this._sleepWaiter.promise}return this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const e=Date.now()-t;this.emit(W.Completed,this._currentRetries,e)}),this._taskingFlag.promise}wakeup(){this.running?null!=this._sleepWaiter&&this._sleepWaiter.resolve():this.start()}async stop(t){if(this.emit(W.Stop,t),null!=this._taskingFlag)return null!=this._breakFlag||(this._breakFlag=f.defer(),this._breakReason=t??new Error("Manually Stop"),this.once(W.Completed,()=>{this._breakFlag?.resolve()}),this._breakFlag.promise.finally(()=>{this._breakFlag=void 0,this._breakReason=void 0})),this._breakFlag.promise}resetRetryPolicy(){this._policy.reset()}onRetry(t){return this.on(W.Retry,t),this}onError(t){return this.on(W.Error,t),this}onFailure(t){return this.on(W.Failure,t),this}onSuccess(t){return this.on(W.Success,t),this}onStart(t){return this.on(W.Start,t),this}onStop(t){return this.on(W.Stop,t),this}onTimeout(t){return this.on(W.Timeout,t),this}onTaskTimeout(t){return this.on(W.TaskTimeout,t),this}onCompleted(t){return this.on(W.Completed,t),this}onMaxRetries(t){return this.on(W.MaxRetries,t),this}}function wt(t){return t<=0||t===1/0}function dt(t){const e=new _t;return e.name(t),e}function pt(){const t=new _t;return t.infinite(),t}function gt(t){const e=new _t;return e.times(t),e}function vt(t){const e=new _t;return e.maxRetries(t),e}function xt(t){const e=new _t;return e.min(t),e}function yt(t){const e=new _t;return e.max(t),e}function kt(t,e){const s=new _t;return s.range(t,e),s}function Lt(t){const e=new _t;return e.fixedInterval(t),e}function Et(t,e=500){const s=new _t;return s.fixedBackoff(t,e),s}function bt(t){const e=new _t;return e.fixedIncrease(t),e}function Nt(t,e=500){const s=new _t;return s.linearBackoff(t,e),s}function St(t){const e=new _t;return e.factorIncrease(t),e}function Tt(t=500){const e=new _t;return e.exponentialBackoff(t),e}function Ot(t){const e=new _t;return e.shuttleInterval(t),e}function Rt(t){const e=new _t;return e.timeout(t),e}function It(t){const e=new _t;return e.taskTimeout(t),e}function $t(t){const e=new _t;return e.task(t),e.start()}var Pt={name:dt,infinite:pt,times:gt,maxRetries:vt,min:xt,max:yt,range:kt,fixedInterval:Lt,fixedBackoff:Et,fixedIncrease:bt,linearBackoff:Nt,factorIncrease:St,exponentialBackoff:Tt,shuttleInterval:Ot,timeout:Rt,taskTimeout:It,start:$t};e(_t,Pt);var Ft={Policy:v,Retrier:_t,Event:W,RetrierFactory:Pt,...Pt};t.Event=W,t.Policy=v,t.Retrier=_t,t.RetrierFactory=Pt,t.default=Ft,t.exponentialBackoff=Tt,t.factorIncrease=St,t.fixedBackoff=Et,t.fixedIncrease=bt,t.fixedInterval=Lt,t.infinite=pt,t.linearBackoff=Nt,t.max=yt,t.maxRetries=vt,t.min=xt,t.name=dt,t.range=kt,t.shuttleInterval=Ot,t.start=$t,t.taskTimeout=It,t.timeout=Rt,t.times=gt,Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).CommonsLang={})}(this,function(t){"use strict";let e=class t extends Error{static isAggregatedErrorLike(t){return t&&Array.isArray(t.errors)}static isAggregatedError(e){return e instanceof t}constructor(t,e){super(t),this.errors=e??[]}addError(t){this.errors.push(t)}removeError(t){const e=this.errors.indexOf(t);return-1!==e&&(this.errors.splice(e,1),!0)}};var n=function(t,...e){if(null==t)throw new TypeError('"target" must not be null or undefined');for(const n of e)if(null!=n)for(const e in n)void 0===t[e]&&(t[e]=n[e]);return t};var r={isArray:function(t){return Array.isArray(t)},isBoolean:function(t){return"boolean"==typeof t},isBuffer:function(t){return null!=t&&Buffer.isBuffer(t)},isFunction:s,isInstance:function(t){return null!=t&&"object"==typeof t&&!l(t)},isIterable:function(t){return null!=t&&"function"==typeof t[Symbol.iterator]},isDate:function(t){return null!=t&&t instanceof Date},isError:function(t){return null!=t&&t instanceof Error},isMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===Map},isWeakMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakMap},isNumber:c,isPositive:o,isNegative:function(t){return!!c(t)&&t<0},isNotNegative:a,isNil:i,isNullOrUndefined:function(t){return null==t},isNull:function(t){return null===t},isUndefined:function(t){return void 0===t},isPlainObject:l,isObject:function(t){return null!=t&&"object"==typeof t},isPromise:u,isRegExp:function(t){return null!=t&&"object"==typeof t&&t.constructor===RegExp},isSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===Set},isWeakSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakSet},isStream:function(t){return null!=t&&"function"==typeof t.pipe},isString:h,isSymbol:function(t){return null!=t&&"symbol"==typeof t},isPrimitive:function(t){return null!==t&&("string"==typeof t||"number"==typeof t||"boolean"==typeof t)},isInt8Array:function(t){return t instanceof Int8Array},isUint8Array:function(t){return t instanceof Uint8Array},isUint8ClampedArray:function(t){return t instanceof Uint8ClampedArray},isInt16Array:function(t){return t instanceof Int16Array},isUint16Array:function(t){return t instanceof Uint16Array},isInt32Array:function(t){return t instanceof Int32Array},isUint32Array:function(t){return t instanceof Uint32Array},isFloat32Array:function(t){return t instanceof Float32Array},isFloat64Array:function(t){return t instanceof Float64Array},isBigInt64Array:function(t){return t instanceof BigInt64Array},isBigUint64Array:function(t){return t instanceof BigUint64Array},isTypedArray:function(t){return ArrayBuffer.isView(t)&&t.constructor!==DataView},isArrayBuffer:function(t){return t instanceof ArrayBuffer}};function s(t){return"function"==typeof t}function i(t){return null==t}function o(t){return!!c(t)&&t>0}function a(t){return!!c(t)&&t>=0}function c(t){return null!=t&&"number"==typeof t}function l(t){return null!==t&&"object"==typeof t&&(t.constructor===Object||void 0===t.constructor)}function u(t){return null!=t&&"function"==typeof t.then}function h(t){return null!=t&&"string"==typeof t}var f={assertNumber:_,assertPositive:function(t,e){if(!o(t))throw new Error(`${e?'"'+e+'" ':""}Not Positive: ${t}`)},assertNotNegative:d,assertFunction:p,assertNotNil:function(t,e){if(i(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!h(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${y(t)}`)}};function m(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':""}Not Array: type=${typeof t} value=${y(t)}`)}function _(t,e){if(!c(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${y(t)}`)}function d(t,e){if(!a(t))throw new Error(`${e?'"'+e+'" ':""}Not "0 or Positive": ${t}`)}function p(t,e){if(!s(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${y(t)}`)}function w(t,e){if(!u(t))throw new Error(`${e?'"'+e+'" ':""}Not Promise: type=${typeof t} value=${y(t)}`)}function y(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(n){e=t.toString()}return e}var g={any:function(t){if(m(t),0===t.length)throw new Error("Empty Tasks");const n=v(),s=[];for(let i=0;i<t.length;i++){const o=t[i];let a;if(r.isPromise(o))a=o;else{if(!r.isFunction(o)){s.push(new Error(`Invalid Task at index ${i}/${t.length-1}: ${o}`));continue}a=k(o)}a.then(t=>{n.resolve(t)}).catch(r=>{s.push(r),s.length>=t.length&&n.reject(new e("All Tasks Failed",s))})}return s.length===t.length&&n.reject(new e("All Tasks Failed",s)),n.promise},defer:v,delay:function(t,e){r.isNumber(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&w(t),_(e=e??1e3);const n=v(),s=Date.now();return t.then((...t)=>{const r=Date.now()-s;r<e?setTimeout(()=>n.resolve(...t),e-r):n.resolve(...t)}).catch(t=>{const r=Date.now()-s;r<e?setTimeout(()=>n.reject(t),e-r):n.reject(t)}),n.promise},timeout:function(t,e,n){w(t),_(e=e??1);const r=v(e,n),s=Date.now();return t.then((...t)=>{Date.now()-s<=e?r.resolve(...t):r.reject(new Error(n??`Promise Timeout: ${e}ms`))}).catch(t=>{!r.resolved&&!r.rejected&&r.reject(t)}),r.promise},allSettled:x,returnValuePromised:k,series:async function(t){m(t);const e=[];for(const n of t)if(p(n),r.isFunction(n))e.push(await k(n));else{if(!r.isPromise(n))throw new Error(`Invalid Task: ${n}`);e.push(await n)}return e},seriesAllSettled:async function(t){m(t);const e=[];for(const n of t){p(n);try{e.push({ok:!0,result:await n()})}catch(t){e.push({ok:!1,result:t})}}return e},parallel:async function(t,e=5){if(m(t),_(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>p(t));const n=[];if(t.length<=e){const e=await Promise.all(t.map(t=>k(t)));return n.push(...e),n}const r=[];for(const s of t)if(p(s),r.push(s),r.length>=e){const t=await Promise.all(r.map(t=>k(t)));n.push(...t),r.length=0}if(r.length>0&&r.length<e){const t=await Promise.all(r.map(t=>k(t)));n.push(...t)}return n},parallelAny:async function(t,n=5){if(m(t,"tasks"),_(n),0===t.length)throw new Error("Empty Tasks");if(n<=0)throw new Error(`Invalid maxParallel: ${n}, should > 0`);const s=[];let i=0,o=0;const a=v();function c(){if(i>=t.length)return;if(o>n)return;const l=t[i++];let u;if(o++,r.isPromise(l))u=l;else{if(!r.isFunction(l))return s.push(new TypeError(`Invalid task: ${l}`)),void c();u=k(l)}u.then(t=>{a.resolve(t)}).catch(n=>{s.push(n),s.length>=t.length&&a.pending?a.reject(new e("All Tasks Failed",s)):c()}).finally(()=>{o--})}for(;o<n;)c();return a.promise},parallelAllSettled:async function(t,e=5){if(m(t),_(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>p(t));const n=[];if(t.length<=e){const e=await x(t.map(t=>k(t)));return n.push(...e),n}const r=[];for(const s of t)if(r.push(s),r.length>=e){const t=await x(r.map(t=>k(t)));n.push(...t),r.length=0}if(r.length>0&&r.length<e){const t=await x(r.map(t=>k(t)));n.push(...t)}return n},wait:function(t){d(t);const e={};let n;return e.timerHandler=n=setTimeout(()=>{clearTimeout(n),e._resolve()},t),e.promise=new Promise((t,r)=>{e._resolve=e=>{null!=n&&clearTimeout(n),t(e)}}),e.wakeup=()=>{e._resolve()},e}};function v(t=-1,e){_(t);const n={};let r;return n.pending=!0,n.canceled=!1,n.rejected=!1,n.resolved=!1,t>=0&&(n.timerCleared=!1,n.timerHandler=r=setTimeout(()=>{clearTimeout(r),n.timerCleared=!0,n.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),n.promise=new Promise((t,e)=>{n.resolve=e=>{n.resolved||n.rejected||n.canceled||(null!=r&&(clearTimeout(r),n.timerCleared=!0),n.pending=!1,n.canceled=!1,n.rejected=!1,n.resolved=!0,t(e))},n.reject=t=>{n.resolved||n.rejected||n.canceled||(null!=r&&(clearTimeout(r),n.timerCleared=!0),n.pending=!1,n.canceled=!1,n.resolved=!1,n.rejected=!0,e(t))}}),n.cancel=n.promise.cancel=t=>{n.resolved||n.rejected||n.canceled||(null!=r&&(clearTimeout(r),n.timerCleared=!0),n.reject(t??new Error("Cancelled")),n.canceled=n.promise.canceled=!0)},n}async function x(t){m(t);const e=await Promise.allSettled(t),n=[];for(const t of e)"fulfilled"===t.status&&n.push({ok:!0,result:t.value}),"rejected"===t.status&&n.push({ok:!1,result:t.reason});return n}function k(t){try{const e=t();return r.isPromise(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:b,assertNotNegative:E}=f,{isNumber:L}=r;class N{constructor(){this._min=50,this._max=3e4,this._nextInterval=this._min,this._jitter=0}get jitter(){return this._jitter}set jitter(t){E(t,"jitter"),this._jitter=t}copyPolicySettingTo(t){t.range(this._min,this._max),t._nextInterval=this._nextInterval}range(t,e){if(b(t,"min"),b(e,"max"),t>=e)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this._max=e,this._nextInterval>this._max&&(this._nextInterval=this._max),this}min(t){if(b(t,"min"),t>=this._max)throw new Error("min must < max");return this._min=t,this._nextInterval=this._min,this}max(t){if(b(t,"max"),t<=this._min)throw new Error("max must > min");return this._max=t,this._nextInterval>this._max&&(this._nextInterval=this._max),this}reset(){return this._nextInterval=this._min,this}generate(t){const e=this._nextInterval;return this._increase(t),e}_increase(t){const e=this._next(t);if(!L(e))throw new Error("Generated Next Interval Not Number");const n=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return n<this._min?this._nextInterval=this._min:n>this._max?this._nextInterval=this._max:this._nextInterval=n}_next(t){throw new Error("Not Impled Yet")}}var T={isFunction:I,isNil:S};function I(t){return"function"==typeof t}function S(t){return null==t}function A(t){return null!=t&&"string"==typeof t}var j={assertNumber:function(t,e){if(!function(t){return null!=t&&"number"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${F(t)}`)},assertFunction:function(t,e){if(!I(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${F(t)}`)},assertNotNil:function(t,e){if(S(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!A(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${F(t)}`)},assertStringOrSymbol:function(t,e){if(!A(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not String or Symbol: type=${typeof t} value=${F(t)}`)}};function F(t){let e;try{e=JSON.stringify(t)}catch(n){e=t.toString()}return e}new TextDecoder,new TextEncoder;const O="DOwner$#$",{assertFunction:P,assertNotNil:R}=j;class ${constructor(t,e,n=!1){R(t,"event"),P(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!n,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===O?void 0:this._owner}get event(){return this._event}get isOnce(){return this._isOnce}isSameCallback(t){return this._callback===t}get callback(){return this._callback}invoke(...t){try{return this._callback(...t)}finally{if(this._isOnce)try{this._event._remove(this)}catch(t){console.warn(t)}}}listener(...t){return this.invoke(...t)}}const{isFunction:B,isNil:M}=T,{assertStringOrSymbol:C,assertFunction:D}=j;class U{static get DefaultOwner(){return O}constructor(t){C(t,"eventName"),this._name=t,this._callbacks=new Set,this._listeners=[],this._callback2Listeners=new Map,this._listener2Owner=new Map,this._owner2Listeners=new Map}get name(){return this._name}isEmpty(){return 0===this._callbacks.size}rawListeners(){return[...this._listeners]}listenerCount(t){return null==t?this._listeners.length:this._callback2Listeners.get(t)?.size??0}callbacks(){return[...this.rawListeners().map(t=>t.callback)]}emit(...t){if(0===this._listeners.length)return!1;for(const e of[...this._listeners])e.invoke(...t);return!0}emitOwner(t,...e){if(0===this._listeners.length)return!1;const n=this._owner2Listeners.get(t);if(null==n)return!1;for(const t of[...n])t.invoke(...e);return!0}hasListener(t){return!!B(t)&&this._callbacks.has(t)}hasOwner(t){return!M(t)&&this._owner2Listeners.has(t)}addListener(t,e){return this._addListener(t,e,!1,!1)}prependListener(t,e){return this._addListener(t,e,!1,!0)}addOnceListener(t,e){return this._addListener(t,e,!0,!1)}prependOnceListener(t,e){return this._addListener(t,e,!0,!0)}_addListener(t,e,n,r){if(M(t))return!1;D(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??O;const s=new $(this,t,n);s.owner=e,r?this._listeners.unshift(s):this._listeners.push(s),this._listener2Owner.set(s,e);let i=this._callback2Listeners.get(t);null==i&&(i=new Set,this._callback2Listeners.set(t,i)),i.add(s);let o=this._owner2Listeners.get(e);return null==o&&(o=new Set,this._owner2Listeners.set(e,o)),o.add(s),!0}removeListener(t){if(M(t))return!1;if(!this._callbacks.has(t))return!1;this._callbacks.delete(t);const e=this._callback2Listeners.get(t);if(null==e)return!1;this._callback2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1);const e=this._listener2Owner.get(t);if(null==e)continue;this._listener2Owner.delete(t);const n=this._owner2Listeners.get(e);null!=n&&(n.delete(t),0===n.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:n}=t,r=this._callback2Listeners.get(n);null!=r&&(r.delete(t),0===r.size&&(this._callback2Listeners.delete(n),this._callbacks.delete(n)));const s=this._listener2Owner.get(t);if(null==s)return;this._listener2Owner.delete(t);const i=this._owner2Listeners.get(s);null!=i&&(i.delete(t),0===i.size&&this._owner2Listeners.delete(s))}removeAllListeners(t){if(M(t))return this._callbacks.clear(),this._listeners.length=0,this._callback2Listeners.clear(),this._listener2Owner.clear(),this._owner2Listeners.clear(),this;const e=this._owner2Listeners.get(t);if(null==e)return this;this._owner2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1),this._listener2Owner.delete(t);const{callback:e}=t,n=this._callback2Listeners.get(e);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:W}=T,{assertString:z,assertFunction:H,assertNumber:V,assertStringOrSymbol:J,assertNotNil:G}=j,Y=["on","once","addListener","prependListener","prependOnceListener","off","offAll","offOwner","removeAllListeners","removeListener","emit","emitOwner","setMaxListeners","getMaxListeners","hasOwner","listeners","listenerCount","eventNames","rawListeners"];let q=10;class K{static mixin(t){const e=new K;t.__emitter=e;for(const n of Y){const r=e[n];t[n]=r.bind(e)}return t}static get defaultMaxListeners(){return q}static set defaultMaxListeners(t){V(t),q=t??10}constructor(){this._name2Event=new Map,this._maxListeners=q}addListener(t,e,n){return this.on(t,e,n)}prependListener(t,e,n){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,n),this}prependOnceListener(t,e,n){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,n),this}emit(t,...e){const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emit(...e),!0)}emitOwner(t,e,...n){if(null==e)throw new Error('Missing "owner"');const r=this._name2Event.get(t);return null!=r&&!r.isEmpty()&&(r.emitOwner(e,...n),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){J(t,"eventName");const n=this._name2Event.get(t);return null==n||n.isEmpty()?0:n.listenerCount(e)}listeners(t){J(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const n=this._name2Event.get(t);return null==n?this:(n.removeListener(e),n.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){J(t,"eventName");const n=this._name2Event.get(t);return null==n?this:(n.removeAllListeners(e),n.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){G(t,"owner");const e=[...this._name2Event.values()];for(const n of e)n.removeAllListeners(t),n.isEmpty()&&this._name2Event.delete(n.name);return this}on(t,e,n){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,n),this}_checkMaxListeners(t){let e=0;0!==this._maxListeners&&this._maxListeners!==1/0&&(e=this.listenerCount(t))>=this._maxListeners&&console.warn(`maxlistenersexceededwarning: Possible EventEmitter memory leak detected. ${e} ${t} listeners added to [${this}]. Use emitter.setMaxListeners() to increase limit`)}once(t,e,n){return z(t),H(e),this._getOrCreateEvent(t).addOnceListener(e,n),this}rawListeners(t){return this._name2Event.get(t)?.rawListeners()||[]}removeAllListeners(t,e){return this.offAll(t,e)}removeListener(t,e){return this.off(t,e)}setMaxListeners(t){if(V(t),t<0)throw new RangeError("maxListeners must >=0");return this._maxListeners=t,this}_getOrCreateEvent(t){if(this._name2Event.has(t))return this._name2Event.get(t);const e=new U(t);return this._name2Event.set(t,e),e}hasOwner(t){if(W(t))return!1;for(const e of this._name2Event.values())if(e.hasOwner(t))return!0;return!1}}var Q={Start:"start",Retry:"retry",Success:"success",Failure:"failure",Timeout:"timeout",TaskTimeout:"task-timeout",Stop:"stop",Completed:"complete",MaxRetries:"max-retries"};const{assertPositive:X}=f;class Z extends N{constructor(t){super(),X(t,"interval"),this._interval=t}set interval(t){X(t,"interval"),this._interval=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:tt}=f;class et extends N{constructor(t){super(),tt(t,"increasement"),this._increasement=t}set increasement(t){tt(t,"increasement"),this._increasement=t}get increasement(){return this._increasement}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval+this.increasement}}const{assertPositive:nt}=f;class rt extends N{constructor(t){if(super(),nt(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(nt(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}get factor(){return this._factor}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval*this.factor}}const{assertPositive:st}=f;class it extends N{constructor(t){super(),st(t,"stepLength"),this._stepLength=t,this.increasement=t}set stepLength(t){st(t,"stepLength"),this._stepLength=t,this.increasement=t}get stepLength(){return this._stepLength}_next(t){const e=this._nextInterval+this.increasement;return e>=this._max?(this.increasement=-this.stepLength,this._max):e<=this._min?(this.increasement=this.stepLength,this._min):e}}const{assertNotNegative:ot}=f;class at extends Z{constructor(t,e=500){super(t),ot(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:ct}=f;class lt extends rt{constructor(t=500){super(2),ct(t,"jitter"),this._jitter=t??500}}const{assertNotNegative:ut}=f;class ht extends et{constructor(t,e=500){super(t),ut(e,"jitter"),this._jitter=e??500}}const{assertNotNil:ft,assertFunction:mt}=f;class _t{constructor(t,e){ft(t,"retrier"),mt(e,"task"),this.retrier=t,this.task=e,this.result=void 0,this.error=void 0}get failed(){return null!=this.error}get succeeded(){return null==this.error}async execute(t,e,n){try{this.result=await this.task(t,e,n),this.error=void 0}catch(t){this.error=t instanceof Error?t:new Error(String(t))}}dispose(){this.retrier=void 0}}class dt extends _t{static isAlwaysTask(t){return t instanceof dt}constructor(t,e,n){super(t,e),this.resetPolicy=n}async execute(t,e,n){await super.execute(t,e,n),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:pt,assertString:wt,assertFunction:yt,assertNumber:gt}=f,{isNil:vt}=r,xt="!#@%$&^*";class kt{static naming(t){const e=new kt;return e.name(t),e}static infinite(){const t=new kt;return t.infinite(),t}static times(t){const e=new kt;return e.times(t),e}static maxRetries(t){const e=new kt;return e.maxRetries(t),e}static min(t){const e=new kt;return e.min(t),e}static max(t){const e=new kt;return e.max(t),e}static range(t,e){const n=new kt;return n.range(t,e),n}static fixedInterval(t){const e=new kt;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const n=new kt;return n.fixedBackoff(t,e),n}static fixedIncrease(t){const e=new kt;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const n=new kt;return n.linearBackoff(t,e),n}static factorIncrease(t){const e=new kt;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new kt;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new kt;return e.shuttleInterval(t),e}static timeout(t){const e=new kt;return e.timeout(t),e}static taskTimeout(t){const e=new kt;return e.taskTimeout(t),e}static start(t){const e=new kt;return e.task(t),e.start()}constructor(t){K.mixin(this),this._policy=new Z(t??1e3),this._maxRetries=3,this._currentRetries=1,this._timeout=12e4,this._taskTimeout=2e3,this._name="unamed",this._taskingFlag=void 0,this._breakFlag=void 0,this._breakReason=void 0}get running(){return!vt(this._taskingFlag)}name(t){return wt(t,"retrierName"),this._name=t,this}infinite(){return this._maxRetries=1/0,this}times(t){return this.maxRetries(t)}maxRetries(t){return pt(t,"maxRetries"),this._maxRetries=t,this}min(t){return this._policy.min(t),this}max(t){return this._policy.max(t),this}range(t,e){return this._policy.range(t,e),this}fixedInterval(t){const e=this._policy;if(e instanceof Z)return e.interval=t,this;const n=new Z(t);return e?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedBackoff(t,e=500){const n=this._policy;if(n instanceof Z)return n.interval=t,n.jitter=e,this;const r=new at(t,e);return n?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}fixedIncrease(t){const e=this._policy;if(e instanceof et)return e.increasement=t,this;const n=new et(t);return e?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}linearBackoff(t,e=500){const n=this._policy;if(n instanceof ht)return n.increasement=t,n.jitter=e,this;const r=new ht(t,e);return n?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}factorIncrease(t){const e=this._policy;if(e instanceof rt)return e.factor=t,this;const n=new rt(t);return e?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}exponentialBackoff(t=500){const e=this._policy;if(e instanceof lt)return e.jitter=t,this;const n=new lt(t);return e?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}shuttleInterval(t){const e=this._policy;if(e instanceof it)return e.stepLength=t,this;const n=new it(t);return e?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}taskTimeout(t){return pt(t,"timeout"),this._taskTimeout=t,this}timeout(t){return gt(t,"timeout"),this._timeout=t,this}notimeout(){return this._timeout=0,this}task(t){return yt(t,"task"),this._task=new _t(this,t),this}retry(t){return this.task(t),this}always(t,e=!1){return this._task=new dt(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");if(null!=this._taskingFlag)return this._taskingFlag.promise;const t=Date.now();let e;this.emit(Q.Start,t),this._taskingFlag=g.defer();let n=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(n=Date.now()-t,!bt(this._timeout)&&n>=this._timeout){if(this.emit(Q.Timeout,this._currentRetries,n,this._timeout),dt.isAlwaysTask(this._task)){this._taskingFlag.resolve();break}this._taskingFlag.reject(e??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(Q.Retry,this._currentRetries,n);const r=this._task,s=this._policy.generate(this._currentRetries);try{try{await g.timeout(r.execute(this._currentRetries,n,s),this._taskTimeout,xt)}catch(t){throw t.message===xt&&this.emit(Q.TaskTimeout,this._currentRetries,n,this._taskTimeout),t}if(r.failed)throw e=r.error,r.error;const t=r.result;if(this.emit(Q.Success,t,this._currentRetries,n),!dt.isAlwaysTask(r)){this._taskingFlag.resolve(t);break}}catch(t){this.emit(Q.Failure,t,this._currentRetries,n)}const i=++this._currentRetries;if(this._currentRetries>this._maxRetries){if(this.emit(Q.MaxRetries,i,this._maxRetries),dt.isAlwaysTask(r)){this._taskingFlag.resolve();break}this._taskingFlag.reject(e??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=g.wait(s),await this._sleepWaiter.promise}return this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const e=Date.now()-t;this.emit(Q.Completed,this._currentRetries,e)}),dt.isAlwaysTask(this._task)?void 0:this._taskingFlag.promise}wakeup(){this.running?null!=this._sleepWaiter&&this._sleepWaiter.wakeup():this.start()}async stop(t){if(this.emit(Q.Stop,t),null!=this._taskingFlag)return null!=this._breakFlag||(this._breakFlag=g.defer(),this._breakReason=t??new Error("Manually Stop"),this.once(Q.Completed,()=>{this._breakFlag?.resolve()}),this._breakFlag.promise.finally(()=>{this._breakFlag=void 0,this._breakReason=void 0})),this._breakFlag.promise}resetRetryPolicy(){this._policy.reset()}onRetry(t){return this.on(Q.Retry,t),this}onError(t){return this.on(Q.Error,t),this}onFailure(t){return this.on(Q.Failure,t),this}onSuccess(t){return this.on(Q.Success,t),this}onStart(t){return this.on(Q.Start,t),this}onStop(t){return this.on(Q.Stop,t),this}onTimeout(t){return this.on(Q.Timeout,t),this}onTaskTimeout(t){return this.on(Q.TaskTimeout,t),this}onCompleted(t){return this.on(Q.Completed,t),this}onMaxRetries(t){return this.on(Q.MaxRetries,t),this}}function bt(t){return t<=0||t===1/0}function Et(t){const e=new kt;return e.name(t),e}function Lt(){const t=new kt;return t.infinite(),t}function Nt(t){const e=new kt;return e.times(t),e}function Tt(t){const e=new kt;return e.maxRetries(t),e}function It(t){const e=new kt;return e.min(t),e}function St(t){const e=new kt;return e.max(t),e}function At(t,e){const n=new kt;return n.range(t,e),n}function jt(t){const e=new kt;return e.fixedInterval(t),e}function Ft(t,e=500){const n=new kt;return n.fixedBackoff(t,e),n}function Ot(t){const e=new kt;return e.fixedIncrease(t),e}function Pt(t,e=500){const n=new kt;return n.linearBackoff(t,e),n}function Rt(t){const e=new kt;return e.factorIncrease(t),e}function $t(t=500){const e=new kt;return e.exponentialBackoff(t),e}function Bt(t){const e=new kt;return e.shuttleInterval(t),e}function Mt(t){const e=new kt;return e.timeout(t),e}function Ct(t){const e=new kt;return e.taskTimeout(t),e}function Dt(t){const e=new kt;return e.task(t),e.start()}var Ut={name:Et,infinite:Lt,times:Nt,maxRetries:Tt,min:It,max:St,range:At,fixedInterval:jt,fixedBackoff:Ft,fixedIncrease:Ot,linearBackoff:Pt,factorIncrease:Rt,exponentialBackoff:$t,shuttleInterval:Bt,timeout:Mt,taskTimeout:Ct,start:Dt};n(kt,Ut);var Wt={Policy:N,Retrier:kt,Event:Q,RetrierFactory:Ut,...Ut};t.Event=Q,t.Policy=N,t.Retrier=kt,t.RetrierFactory=Ut,t.default=Wt,t.exponentialBackoff=$t,t.factorIncrease=Rt,t.fixedBackoff=Ft,t.fixedIncrease=Ot,t.fixedInterval=jt,t.infinite=Lt,t.linearBackoff=Pt,t.max=St,t.maxRetries=Tt,t.min=It,t.name=Et,t.range=At,t.shuttleInterval=Bt,t.start=Dt,t.taskTimeout=Ct,t.timeout=Mt,t.times=Nt,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=index.min.js.map