@creejs/commons-retrier 2.1.23 → 2.1.24
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.
- package/dist/cjs/index-dev.cjs +1 -1
- package/dist/cjs/index-dev.cjs.map +1 -1
- package/dist/cjs/index-min.cjs +1 -1
- package/dist/cjs/index-min.cjs.map +1 -1
- package/dist/esm/index-dev.js +1 -1
- package/dist/esm/index-dev.js.map +1 -1
- package/dist/esm/index-min.js +1 -1
- package/dist/esm/index-min.js.map +1 -1
- package/dist/umd/index.dev.js +1 -1
- package/dist/umd/index.dev.js.map +1 -1
- package/dist/umd/index.min.js +1 -1
- package/dist/umd/index.min.js.map +1 -1
- package/package.json +3 -3
package/dist/umd/index.min.js
CHANGED
|
@@ -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";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 r=function(t,...e){if(null==t)throw new TypeError('"target" Should Not Nil');for(const r of e)if(null!=r)for(const e in r)void 0===t[e]&&(t[e]=r[e]);return t};var n={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:a,isNegative:function(t){return!!c(t)&&t<0},isNotNegative:o,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 a(t){return!!c(t)&&t>0}function o(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(!a(t))throw new Error(`${e?'"'+e+'" ':""}Not Positive: ${t}`)},assertNotNegative:w,assertFunction:d,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=${g(t)}`)}};function m(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':""}Not Array: type=${typeof t} value=${g(t)}`)}function _(t,e){if(!c(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${g(t)}`)}function w(t,e){if(!o(t))throw new Error(`${e?'"'+e+'" ':""}Not "0 or Positive": ${t}`)}function d(t,e){if(!s(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${g(t)}`)}function p(t,e){if(!u(t))throw new Error(`${e?'"'+e+'" ':""}Not Promise: type=${typeof t} value=${g(t)}`)}function g(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}var y={any:function(t){if(m(t),0===t.length)throw new Error("Empty Tasks");const r=v(),s=[];for(let i=0;i<t.length;i++){const a=t[i];let o;if(n.isPromise(a))o=a;else{if(!n.isFunction(a)){s.push(new Error(`Invalid Task at index ${i}/${t.length-1}: ${a}`));continue}o=x(a)}o.then(t=>{r.resolve(t)}).catch(n=>{s.push(n),s.length>=t.length&&r.reject(new e("All Tasks Failed",s))})}return s.length===t.length&&r.reject(new e("All Tasks Failed",s)),r.promise},defer:v,delay:function(t,e){n.isNumber(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&p(t),_(e=e??1e3);const r=v(),s=Date.now();return t.then((...t)=>{const n=Date.now()-s;n<e?setTimeout(()=>r.resolve(...t),e-n):r.resolve(...t)}).catch(t=>{const n=Date.now()-s;n<e?setTimeout(()=>r.reject(t),e-n):r.reject(t)}),r.promise},timeout:function(t,e,r){p(t),_(e=e??1);const n=v(e,r),s=Date.now();return t.then((...t)=>{Date.now()-s<=e?n.resolve(...t):n.reject(new Error(r??`Promise Timeout: ${e}ms`))}).catch(t=>{!n.resolved&&!n.rejected&&n.reject(t)}),n.promise},allSettled:k,returnValuePromised:x,series:async function(t){m(t);const e=[];for(const r of t)if(d(r),n.isFunction(r))e.push(await x(r));else{if(!n.isPromise(r))throw new Error(`Invalid Task: ${r}`);e.push(await r)}return e},seriesAllSettled:async function(t){m(t);const e=[];for(const r of t){d(r);try{e.push({ok:!0,result:await r()})}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=>d(t));const r=[];if(t.length<=e){const e=await Promise.all(t.map(t=>x(t)));return r.push(...e),r}const n=[];for(const s of t)if(d(s),n.push(s),n.length>=e){const t=await Promise.all(n.map(t=>x(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await Promise.all(n.map(t=>x(t)));r.push(...t)}return r},parallelAny:async function(t,r=5,s){if(m(t,"tasks"),_(r),0===t.length)throw new Error("Empty Tasks");if(r<=0)throw new Error(`Invalid maxParallel: ${r}, should > 0`);const i=[];let a=0,o=0;const c=v();function l(){if(a>=t.length)return;if(o>r)return;const u=t[a++];let h;o++,h=n.isPromise(u)?u:n.isFunction(u)?x(u):Promise.reject(new TypeError(`Invalid task: ${typeof u}, Only Promise or Function allowed`)),h.then(t=>{o--,c.resolve(t)}).catch(r=>{i.push(r),i.length>=t.length&&c.pending?c.reject(new e(s??"All Tasks Failed",i)):(o--,l())})}const u=Math.min(t.length,r);for(let t=0;t<u;t++)l();return c.promise},parallelAllSettled:async function(t,e=5){if(m(t),_(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>d(t));const r=[];if(t.length<=e){const e=await k(t.map(t=>x(t)));return r.push(...e),r}const n=[];for(const s of t)if(n.push(s),n.length>=e){const t=await k(n.map(t=>x(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await k(n.map(t=>x(t)));r.push(...t)}return r},wait:function(t){w(t);const e={};let r;return e.timerHandler=r=setTimeout(()=>{clearTimeout(r),e._resolve()},t),e.promise=new Promise((t,n)=>{e._resolve=e=>{null!=r&&clearTimeout(r),t(e)}}),e.wakeup=()=>{e._resolve()},e}};function v(t=-1,e){_(t);const r={};let n;return r.pending=!0,r.canceled=!1,r.rejected=!1,r.resolved=!1,t>=0&&(r.timerCleared=!1,r.timerHandler=n=setTimeout(()=>{clearTimeout(n),r.timerCleared=!0,r.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),r.promise=new Promise((t,e)=>{r.resolve=e=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.rejected=!1,r.resolved=!0,t(e))},r.reject=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.resolved=!1,r.rejected=!0,e(t))}}),r.cancel=r.promise.cancel=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.reject(t??new Error("Cancelled")),r.canceled=r.promise.canceled=!0)},r}async function k(t){m(t);const e=await Promise.allSettled(t),r=[];for(const t of e)"fulfilled"===t.status&&r.push({ok:!0,result:t.value}),"rejected"===t.status&&r.push({ok:!1,result:t.reason});return r}function x(t){try{const e=t();return n.isPromise(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:b,assertNotNegative:E}=f,{isNumber:L}=n;class T{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._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 r=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return r<this._min?this._nextInterval=this._min:r>this._max?this._nextInterval=this._max:this._nextInterval=r}_next(t){throw new Error("Not Impled Yet")}}var N={isFunction:I,isNil:F};function I(t){return"function"==typeof t}function F(t){return null==t}function R(t){return null!=t&&"string"==typeof t}var S={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=${A(t)}`)},assertFunction:function(t,e){if(!I(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${A(t)}`)},assertNotNil:function(t,e){if(F(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!R(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${A(t)}`)},assertStringOrSymbol:function(t,e){if(!R(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not String or Symbol: type=${typeof t} value=${A(t)}`)}};function A(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}new TextDecoder,new TextEncoder;const P="DOwner$#$",{assertFunction:j,assertNotNil:O}=S;class ${constructor(t,e,r=!1){O(t,"event"),j(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!r,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===P?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:C,isNil:B}=N,{assertStringOrSymbol:M,assertFunction:D}=S;class U{static get DefaultOwner(){return P}constructor(t){M(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 r=this._owner2Listeners.get(t);if(null==r)return!1;for(const t of[...r])t.invoke(...e);return!0}hasListener(t){return!!C(t)&&this._callbacks.has(t)}hasOwner(t){return!B(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,r,n){if(B(t))return!1;D(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??P;const s=new $(this,t,r);s.owner=e,n?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 a=this._owner2Listeners.get(e);return null==a&&(a=new Set,this._owner2Listeners.set(e,a)),a.add(s),!0}removeListener(t){if(B(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 r=this._owner2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:r}=t,n=this._callback2Listeners.get(r);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(r),this._callbacks.delete(r)));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(B(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,r=this._callback2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:W}=N,{assertString:z,assertFunction:H,assertNumber:V,assertStringOrSymbol:J,assertNotNil:G}=S,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 r of Y){const n=e[r];t[r]=n.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,r){return this.on(t,e,r)}prependListener(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,r),this}prependOnceListener(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,r),this}emit(t,...e){const r=this._name2Event.get(t);return null!=r&&!r.isEmpty()&&(r.emit(...e),!0)}emitOwner(t,e,...r){if(null==e)throw new Error('Missing "owner"');const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emitOwner(e,...r),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){J(t,"eventName");const r=this._name2Event.get(t);return null==r||r.isEmpty()?0:r.listenerCount(e)}listeners(t){J(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const r=this._name2Event.get(t);return null==r?this:(r.removeListener(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){J(t,"eventName");const r=this._name2Event.get(t);return null==r?this:(r.removeAllListeners(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){G(t,"owner");const e=[...this._name2Event.values()];for(const r of e)r.removeAllListeners(t),r.isEmpty()&&this._name2Event.delete(r.name);return this}on(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,r),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,r){return z(t),H(e),this._getOrCreateEvent(t).addOnceListener(e,r),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 T{constructor(t){super(),this.interval=t}set interval(t){X(t,"interval"),this._interval=t,this._nextInterval=t,this._min=t,this._max=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:tt}=f;class et extends T{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:rt}=f;class nt extends T{constructor(t){if(super(),rt(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(rt(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 T{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:at}=f;class ot extends Z{constructor(t,e=500){super(t),at(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:ct}=f;class lt extends nt{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,r){try{this.result=await this.task(t,e,r),this.error=void 0}catch(t){this.error=t instanceof Error?t:new Error(String(t))}}dispose(){this.retrier=void 0}}class wt extends _t{static isAlwaysTask(t){return t instanceof wt}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}class dt extends _t{static isForeverTask(t){return t instanceof dt}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:pt,assertString:gt,assertFunction:yt,assertNumber:vt}=f,{isNil:kt}=n,xt="!#@%$&^*";class bt{static naming(t){const e=new bt;return e.name(t),e}static infinite(){const t=new bt;return t.infinite(),t}static times(t){const e=new bt;return e.times(t),e}static maxRetries(t){const e=new bt;return e.maxRetries(t),e}static min(t){const e=new bt;return e.min(t),e}static max(t){const e=new bt;return e.max(t),e}static range(t,e){const r=new bt;return r.range(t,e),r}static fixedInterval(t){const e=new bt;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const r=new bt;return r.fixedBackoff(t,e),r}static fixedIncrease(t){const e=new bt;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const r=new bt;return r.linearBackoff(t,e),r}static factorIncrease(t){const e=new bt;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new bt;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new bt;return e.shuttleInterval(t),e}static timeout(t){const e=new bt;return e.timeout(t),e}static taskTimeout(t){const e=new bt;return e.taskTimeout(t),e}static start(t){const e=new bt;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!kt(this._taskingFlag)}name(t){return gt(t,"name"),this._assertChangeable(t),this._name=t,this}infinite(){return this._assertChangeable("infinite"),this._maxRetries=1/0,this}times(t){return this._assertChangeable("times"),this.maxRetries(t)}maxRetries(t){return pt(t,"maxRetries"),this._assertChangeable("maxRetries"),this._maxRetries=t,this}min(t){return this._assertChangeable("min"),this._policy.min(t),this}max(t){return this._assertChangeable("max"),this._policy.max(t),this}range(t,e){return this._assertChangeable("range"),this._policy.range(t,e),this}fixedInterval(t){this._assertChangeable("fixedInterval");const e=this._policy;if(e instanceof Z)return e.interval=t,this;const r=new Z(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}fixedBackoff(t,e=500){this._assertChangeable("fixedBackoff");const r=this._policy;if(r instanceof Z)return r.interval=t,r.jitter=e,this;const n=new ot(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedIncrease(t){this._assertChangeable("fixedIncrease");const e=this._policy;if(e instanceof et)return e.increasement=t,this;const r=new et(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}linearBackoff(t,e=500){this._assertChangeable("linearBackoff");const r=this._policy;if(r instanceof ht)return r.increasement=t,r.jitter=e,this;const n=new ht(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}factorIncrease(t){this._assertChangeable("factorIncrease");const e=this._policy;if(e instanceof nt)return e.factor=t,this;const r=new nt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}exponentialBackoff(t=500){this._assertChangeable("exponentialBackoff");const e=this._policy;if(e instanceof lt)return e.jitter=t,this;const r=new lt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}shuttleInterval(t){this._assertChangeable("shuttleInterval");const e=this._policy;if(e instanceof it)return e.stepLength=t,this;const r=new it(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}taskTimeout(t){return pt(t,"taskTimeout"),this._assertChangeable("taskTimeout"),this._taskTimeout=t,this}timeout(t){return vt(t,"timeout"),this._assertChangeable("timeout"),this._timeout=t,this}noTimeout(){return this._assertChangeable("noTimeout"),this._timeout=0,this}task(t){return yt(t,"task"),this._assertChangeable("task"),this._task=new _t(this,t),this}retry(t){return this._assertChangeable("retry"),this.task(t),this}always(t,e=!0){return this._assertChangeable("always"),this._task=new wt(this,t,e),this}forever(t,e=!0){return this._assertChangeable("forever"),this.noTimeout(),this.infinite(),this._task=new dt(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");return null!=this._taskingFlag||(this._taskingFlag=y.defer(),dt.isForeverTask(this._task)?(this._executeForeverTask(this._task),this._taskingFlag.resolve()):this._executeEndableTask(this._task)),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||(null!=this._sleepWaiter&&this._sleepWaiter.wakeup(),this._breakFlag=y.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._taskingFlag=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}async _executeForeverTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();this.emit(Q.Start,e);let r=null;for(;;){if(null!=this._breakFlag){const t=Date.now()-e;this.emit(Q.Completed,this._currentRetries,t);break}r=Date.now()-e,this.emit(Q.Retry,this._currentRetries,r);const n=this._policy.generate(this._currentRetries);try{try{await y.timeout(t.execute(this._currentRetries,r,n),this._taskTimeout,xt)}catch(t){throw t.message===xt&&this.emit(Q.TaskTimeout,this._currentRetries,r,this._taskTimeout),t}if(t.failed)throw t.error;const e=t.result;this.emit(Q.Success,e,this._currentRetries,r)}catch(t){this.emit(Q.Failure,t,this._currentRetries,r)}++this._currentRetries,this._sleepWaiter=y.wait(n),await this._sleepWaiter.promise}}async _executeEndableTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();let r;this.emit(Q.Start,e);let n=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(n=Date.now()-e,!Et(this._timeout)&&n>=this._timeout){if(this.emit(Q.Timeout,this._currentRetries,n,this._timeout),wt.isAlwaysTask(this._task)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(Q.Retry,this._currentRetries,n);const s=this._policy.generate(this._currentRetries);try{try{await y.timeout(t.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(t.failed)throw r=t.error,t.error;const e=t.result;if(this.emit(Q.Success,e,this._currentRetries,n),!wt.isAlwaysTask(t)){this._taskingFlag.resolve(e);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),wt.isAlwaysTask(t)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=y.wait(s),await this._sleepWaiter.promise}if(this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const t=Date.now()-e;this.emit(Q.Completed,this._currentRetries,t)}),!wt.isAlwaysTask(this._task))return this._taskingFlag.promise}_assertChangeable(t){if(null!=this._taskingFlag)throw new Error(`No Change "${t}" After Retrier Started`)}}function Et(t){return t<=0||t===1/0}function Lt(t){const e=new bt;return e.name(t),e}function Tt(){const t=new bt;return t.infinite(),t}function Nt(t){const e=new bt;return e.times(t),e}function It(t){const e=new bt;return e.maxRetries(t),e}function Ft(t){const e=new bt;return e.min(t),e}function Rt(t){const e=new bt;return e.max(t),e}function St(t,e){const r=new bt;return r.range(t,e),r}function At(t){const e=new bt;return e.fixedInterval(t),e}function Pt(t,e=500){const r=new bt;return r.fixedBackoff(t,e),r}function jt(t){const e=new bt;return e.fixedIncrease(t),e}function Ot(t,e=500){const r=new bt;return r.linearBackoff(t,e),r}function $t(t){const e=new bt;return e.factorIncrease(t),e}function Ct(t=500){const e=new bt;return e.exponentialBackoff(t),e}function Bt(t){const e=new bt;return e.shuttleInterval(t),e}function Mt(t){const e=new bt;return e.timeout(t),e}function Dt(t){const e=new bt;return e.taskTimeout(t),e}function Ut(t){const e=new bt;return e.task(t),e.start()}var Wt={retry:function(t){const e=new bt;return e.retry(t),e},always:function(t){const e=new bt;return e.always(t),e},forever:function(t){const e=new bt;return e.forever(t),e},name:Lt,infinite:Tt,times:Nt,maxRetries:It,min:Ft,max:Rt,range:St,fixedInterval:At,fixedBackoff:Pt,fixedIncrease:jt,linearBackoff:Ot,factorIncrease:$t,exponentialBackoff:Ct,shuttleInterval:Bt,timeout:Mt,taskTimeout:Dt,start:Ut};r(bt,Wt);var zt={Policy:T,Retrier:bt,Event:Q,RetrierFactory:Wt,...Wt};t.Event=Q,t.Policy=T,t.Retrier=bt,t.RetrierFactory=Wt,t.default=zt,t.exponentialBackoff=Ct,t.factorIncrease=$t,t.fixedBackoff=Pt,t.fixedIncrease=jt,t.fixedInterval=At,t.infinite=Tt,t.linearBackoff=Ot,t.max=Rt,t.maxRetries=It,t.min=Ft,t.name=Lt,t.range=St,t.shuttleInterval=Bt,t.start=Ut,t.taskTimeout=Dt,t.timeout=Mt,t.times=Nt,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 r=function(t,...e){if(null==t)throw new TypeError('"target" Should Not Nil');for(const r of e)if(null!=r)for(const e in r)void 0===t[e]&&(t[e]=r[e]);return t};var n={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:a,isNegative:function(t){return!!c(t)&&t<0},isNotNegative:o,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 a(t){return!!c(t)&&t>0}function o(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(!a(t))throw new Error(`${e?'"'+e+'" ':""}Not Positive: ${t}`)},assertNotNegative:d,assertFunction:w,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=${g(t)}`)}};function m(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':""}Not Array: type=${typeof t} value=${g(t)}`)}function _(t,e){if(!c(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${g(t)}`)}function d(t,e){if(!o(t))throw new Error(`${e?'"'+e+'" ':""}Not "0 or Positive": ${t}`)}function w(t,e){if(!s(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${g(t)}`)}function p(t,e){if(!u(t))throw new Error(`${e?'"'+e+'" ':""}Not Promise: type=${typeof t} value=${g(t)}`)}function g(t){if(null===t)return"null";if(void 0===t)return"undefined";const e=typeof t;if("string"===e)return t;if("symbol"===e)return`Symbol(${t.description})`;if("function"===e)return`Function ${t.name}(){}`;if(t instanceof String)return t.toString();if(Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";if(t instanceof Error)return`${t.constructor.name}: ${t.message}`;if(t instanceof Promise)return"Promise";if(t instanceof Set)return`Set: ${g(Array.from(t))}`;if(t instanceof Map)return`Map: ${g(Array.from(t.entries()))}`;if(t instanceof RegExp)return t.toString();if(Array.isArray(t))return`[${t.map(g).join(", ")}]`;let r;try{r=JSON.stringify(t)}catch(e){r=t.toString()}return r}var y={any:function(t){if(m(t),0===t.length)throw new Error("Empty Tasks");const r=v(),s=[];for(let i=0;i<t.length;i++){const a=t[i];let o;if(n.isPromise(a))o=a;else{if(!n.isFunction(a)){s.push(new Error(`Invalid Task at index ${i}/${t.length-1}: ${a}`));continue}o=x(a)}o.then(t=>{r.resolve(t)}).catch(n=>{s.push(n),s.length>=t.length&&r.reject(new e("All Tasks Failed",s))})}return s.length===t.length&&r.reject(new e("All Tasks Failed",s)),r.promise},defer:v,delay:function(t,e){n.isNumber(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&p(t),_(e=e??1e3);const r=v(),s=Date.now();return t.then((...t)=>{const n=Date.now()-s;n<e?setTimeout(()=>r.resolve(...t),e-n):r.resolve(...t)}).catch(t=>{const n=Date.now()-s;n<e?setTimeout(()=>r.reject(t),e-n):r.reject(t)}),r.promise},timeout:function(t,e,r){p(t),_(e=e??1);const n=v(e,r),s=Date.now();return t.then((...t)=>{Date.now()-s<=e?n.resolve(...t):n.reject(new Error(r??`Promise Timeout: ${e}ms`))}).catch(t=>{!n.resolved&&!n.rejected&&n.reject(t)}),n.promise},allSettled:k,returnValuePromised:x,series:async function(t){m(t);const e=[];for(const r of t)if(w(r),n.isFunction(r))e.push(await x(r));else{if(!n.isPromise(r))throw new Error(`Invalid Task: ${r}`);e.push(await r)}return e},seriesAllSettled:async function(t){m(t);const e=[];for(const r of t){w(r);try{e.push({ok:!0,result:await r()})}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=>w(t));const r=[];if(t.length<=e){const e=await Promise.all(t.map(t=>x(t)));return r.push(...e),r}const n=[];for(const s of t)if(w(s),n.push(s),n.length>=e){const t=await Promise.all(n.map(t=>x(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await Promise.all(n.map(t=>x(t)));r.push(...t)}return r},parallelAny:async function(t,r=5,s){if(m(t,"tasks"),_(r),0===t.length)throw new Error("Empty Tasks");if(r<=0)throw new Error(`Invalid maxParallel: ${r}, should > 0`);const i=[];let a=0,o=0;const c=v();function l(){if(a>=t.length)return;if(o>r)return;const u=t[a++];let h;o++,h=n.isPromise(u)?u:n.isFunction(u)?x(u):Promise.reject(new TypeError(`Invalid task: ${typeof u}, Only Promise or Function allowed`)),h.then(t=>{o--,c.resolve(t)}).catch(r=>{i.push(r),i.length>=t.length&&c.pending?c.reject(new e(s??"All Tasks Failed",i)):(o--,l())})}const u=Math.min(t.length,r);for(let t=0;t<u;t++)l();return c.promise},parallelAllSettled:async function(t,e=5){if(m(t),_(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>w(t));const r=[];if(t.length<=e){const e=await k(t.map(t=>x(t)));return r.push(...e),r}const n=[];for(const s of t)if(n.push(s),n.length>=e){const t=await k(n.map(t=>x(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await k(n.map(t=>x(t)));r.push(...t)}return r},wait:function(t){d(t);const e={};let r;return e.timerHandler=r=setTimeout(()=>{clearTimeout(r),e._resolve()},t),e.promise=new Promise((t,n)=>{e._resolve=e=>{null!=r&&clearTimeout(r),t(e)}}),e.wakeup=()=>{e._resolve()},e}};function v(t=-1,e){_(t);const r={};let n;return r.pending=!0,r.canceled=!1,r.rejected=!1,r.resolved=!1,t>=0&&(r.timerCleared=!1,r.timerHandler=n=setTimeout(()=>{clearTimeout(n),r.timerCleared=!0,r.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),r.promise=new Promise((t,e)=>{r.resolve=e=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.rejected=!1,r.resolved=!0,t(e))},r.reject=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.resolved=!1,r.rejected=!0,e(t))}}),r.cancel=r.promise.cancel=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.reject(t??new Error("Cancelled")),r.canceled=r.promise.canceled=!0)},r}async function k(t){m(t);const e=await Promise.allSettled(t),r=[];for(const t of e)"fulfilled"===t.status&&r.push({ok:!0,result:t.value}),"rejected"===t.status&&r.push({ok:!1,result:t.reason});return r}function x(t){try{const e=t();return n.isPromise(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:b,assertNotNegative:E}=f,{isNumber:L}=n;class T{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._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 r=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return r<this._min?this._nextInterval=this._min:r>this._max?this._nextInterval=this._max:this._nextInterval=r}_next(t){throw new Error("Not Impled Yet")}}var N={isFunction:I,isNil:S};function I(t){return"function"==typeof t}function S(t){return null==t}function F(t){return null!=t&&"string"==typeof t}var R={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=${A(t)}`)},assertFunction:function(t,e){if(!I(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${A(t)}`)},assertNotNil:function(t,e){if(S(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!F(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${A(t)}`)},assertStringOrSymbol:function(t,e){if(!F(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not String or Symbol: type=${typeof t} value=${A(t)}`)}};function A(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}new TextDecoder,new TextEncoder;const P="DOwner$#$",{assertFunction:$,assertNotNil:j}=R;class O{constructor(t,e,r=!1){j(t,"event"),$(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!r,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===P?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:C,isNil:B}=N,{assertStringOrSymbol:M,assertFunction:D}=R;class U{static get DefaultOwner(){return P}constructor(t){M(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 r=this._owner2Listeners.get(t);if(null==r)return!1;for(const t of[...r])t.invoke(...e);return!0}hasListener(t){return!!C(t)&&this._callbacks.has(t)}hasOwner(t){return!B(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,r,n){if(B(t))return!1;D(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??P;const s=new O(this,t,r);s.owner=e,n?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 a=this._owner2Listeners.get(e);return null==a&&(a=new Set,this._owner2Listeners.set(e,a)),a.add(s),!0}removeListener(t){if(B(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 r=this._owner2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:r}=t,n=this._callback2Listeners.get(r);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(r),this._callbacks.delete(r)));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(B(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,r=this._callback2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:W}=N,{assertString:z,assertFunction:H,assertNumber:V,assertStringOrSymbol:J,assertNotNil:G}=R,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 r of Y){const n=e[r];t[r]=n.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,r){return this.on(t,e,r)}prependListener(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,r),this}prependOnceListener(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,r),this}emit(t,...e){const r=this._name2Event.get(t);return null!=r&&!r.isEmpty()&&(r.emit(...e),!0)}emitOwner(t,e,...r){if(null==e)throw new Error('Missing "owner"');const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emitOwner(e,...r),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){J(t,"eventName");const r=this._name2Event.get(t);return null==r||r.isEmpty()?0:r.listenerCount(e)}listeners(t){J(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const r=this._name2Event.get(t);return null==r?this:(r.removeListener(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){J(t,"eventName");const r=this._name2Event.get(t);return null==r?this:(r.removeAllListeners(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){G(t,"owner");const e=[...this._name2Event.values()];for(const r of e)r.removeAllListeners(t),r.isEmpty()&&this._name2Event.delete(r.name);return this}on(t,e,r){return z(t),H(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,r),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,r){return z(t),H(e),this._getOrCreateEvent(t).addOnceListener(e,r),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 T{constructor(t){super(),this.interval=t}set interval(t){X(t,"interval"),this._interval=t,this._nextInterval=t,this._min=t,this._max=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:tt}=f;class et extends T{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:rt}=f;class nt extends T{constructor(t){if(super(),rt(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(rt(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 T{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:at}=f;class ot extends Z{constructor(t,e=500){super(t),at(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:ct}=f;class lt extends nt{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,r){try{this.result=await this.task(t,e,r),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,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}class wt extends _t{static isForeverTask(t){return t instanceof wt}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:pt,assertString:gt,assertFunction:yt,assertNumber:vt}=f,{isNil:kt}=n,xt="!#@%$&^*";class bt{static naming(t){const e=new bt;return e.name(t),e}static infinite(){const t=new bt;return t.infinite(),t}static times(t){const e=new bt;return e.times(t),e}static maxRetries(t){const e=new bt;return e.maxRetries(t),e}static min(t){const e=new bt;return e.min(t),e}static max(t){const e=new bt;return e.max(t),e}static range(t,e){const r=new bt;return r.range(t,e),r}static fixedInterval(t){const e=new bt;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const r=new bt;return r.fixedBackoff(t,e),r}static fixedIncrease(t){const e=new bt;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const r=new bt;return r.linearBackoff(t,e),r}static factorIncrease(t){const e=new bt;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new bt;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new bt;return e.shuttleInterval(t),e}static timeout(t){const e=new bt;return e.timeout(t),e}static taskTimeout(t){const e=new bt;return e.taskTimeout(t),e}static start(t){const e=new bt;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!kt(this._taskingFlag)}name(t){return gt(t,"name"),this._assertChangeable(t),this._name=t,this}infinite(){return this._assertChangeable("infinite"),this._maxRetries=1/0,this}times(t){return this._assertChangeable("times"),this.maxRetries(t)}maxRetries(t){return pt(t,"maxRetries"),this._assertChangeable("maxRetries"),this._maxRetries=t,this}min(t){return this._assertChangeable("min"),this._policy.min(t),this}max(t){return this._assertChangeable("max"),this._policy.max(t),this}range(t,e){return this._assertChangeable("range"),this._policy.range(t,e),this}fixedInterval(t){this._assertChangeable("fixedInterval");const e=this._policy;if(e instanceof Z)return e.interval=t,this;const r=new Z(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}fixedBackoff(t,e=500){this._assertChangeable("fixedBackoff");const r=this._policy;if(r instanceof Z)return r.interval=t,r.jitter=e,this;const n=new ot(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedIncrease(t){this._assertChangeable("fixedIncrease");const e=this._policy;if(e instanceof et)return e.increasement=t,this;const r=new et(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}linearBackoff(t,e=500){this._assertChangeable("linearBackoff");const r=this._policy;if(r instanceof ht)return r.increasement=t,r.jitter=e,this;const n=new ht(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}factorIncrease(t){this._assertChangeable("factorIncrease");const e=this._policy;if(e instanceof nt)return e.factor=t,this;const r=new nt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}exponentialBackoff(t=500){this._assertChangeable("exponentialBackoff");const e=this._policy;if(e instanceof lt)return e.jitter=t,this;const r=new lt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}shuttleInterval(t){this._assertChangeable("shuttleInterval");const e=this._policy;if(e instanceof it)return e.stepLength=t,this;const r=new it(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}taskTimeout(t){return pt(t,"taskTimeout"),this._assertChangeable("taskTimeout"),this._taskTimeout=t,this}timeout(t){return vt(t,"timeout"),this._assertChangeable("timeout"),this._timeout=t,this}noTimeout(){return this._assertChangeable("noTimeout"),this._timeout=0,this}task(t){return yt(t,"task"),this._assertChangeable("task"),this._task=new _t(this,t),this}retry(t){return this._assertChangeable("retry"),this.task(t),this}always(t,e=!0){return this._assertChangeable("always"),this._task=new dt(this,t,e),this}forever(t,e=!0){return this._assertChangeable("forever"),this.noTimeout(),this.infinite(),this._task=new wt(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");return null!=this._taskingFlag||(this._taskingFlag=y.defer(),wt.isForeverTask(this._task)?(this._executeForeverTask(this._task),this._taskingFlag.resolve()):this._executeEndableTask(this._task)),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||(null!=this._sleepWaiter&&this._sleepWaiter.wakeup(),this._breakFlag=y.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._taskingFlag=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}async _executeForeverTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();this.emit(Q.Start,e);let r=null;for(;;){if(null!=this._breakFlag){const t=Date.now()-e;this.emit(Q.Completed,this._currentRetries,t);break}r=Date.now()-e,this.emit(Q.Retry,this._currentRetries,r);const n=this._policy.generate(this._currentRetries);try{try{await y.timeout(t.execute(this._currentRetries,r,n),this._taskTimeout,xt)}catch(t){throw t.message===xt&&this.emit(Q.TaskTimeout,this._currentRetries,r,this._taskTimeout),t}if(t.failed)throw t.error;const e=t.result;this.emit(Q.Success,e,this._currentRetries,r)}catch(t){this.emit(Q.Failure,t,this._currentRetries,r)}++this._currentRetries,this._sleepWaiter=y.wait(n),await this._sleepWaiter.promise}}async _executeEndableTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();let r;this.emit(Q.Start,e);let n=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(n=Date.now()-e,!Et(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(r??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(Q.Retry,this._currentRetries,n);const s=this._policy.generate(this._currentRetries);try{try{await y.timeout(t.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(t.failed)throw r=t.error,t.error;const e=t.result;if(this.emit(Q.Success,e,this._currentRetries,n),!dt.isAlwaysTask(t)){this._taskingFlag.resolve(e);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(t)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=y.wait(s),await this._sleepWaiter.promise}if(this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const t=Date.now()-e;this.emit(Q.Completed,this._currentRetries,t)}),!dt.isAlwaysTask(this._task))return this._taskingFlag.promise}_assertChangeable(t){if(null!=this._taskingFlag)throw new Error(`No Change "${t}" After Retrier Started`)}}function Et(t){return t<=0||t===1/0}function Lt(t){const e=new bt;return e.name(t),e}function Tt(){const t=new bt;return t.infinite(),t}function Nt(t){const e=new bt;return e.times(t),e}function It(t){const e=new bt;return e.maxRetries(t),e}function St(t){const e=new bt;return e.min(t),e}function Ft(t){const e=new bt;return e.max(t),e}function Rt(t,e){const r=new bt;return r.range(t,e),r}function At(t){const e=new bt;return e.fixedInterval(t),e}function Pt(t,e=500){const r=new bt;return r.fixedBackoff(t,e),r}function $t(t){const e=new bt;return e.fixedIncrease(t),e}function jt(t,e=500){const r=new bt;return r.linearBackoff(t,e),r}function Ot(t){const e=new bt;return e.factorIncrease(t),e}function Ct(t=500){const e=new bt;return e.exponentialBackoff(t),e}function Bt(t){const e=new bt;return e.shuttleInterval(t),e}function Mt(t){const e=new bt;return e.timeout(t),e}function Dt(t){const e=new bt;return e.taskTimeout(t),e}function Ut(t){const e=new bt;return e.task(t),e.start()}var Wt={retry:function(t){const e=new bt;return e.retry(t),e},always:function(t){const e=new bt;return e.always(t),e},forever:function(t){const e=new bt;return e.forever(t),e},name:Lt,infinite:Tt,times:Nt,maxRetries:It,min:St,max:Ft,range:Rt,fixedInterval:At,fixedBackoff:Pt,fixedIncrease:$t,linearBackoff:jt,factorIncrease:Ot,exponentialBackoff:Ct,shuttleInterval:Bt,timeout:Mt,taskTimeout:Dt,start:Ut};r(bt,Wt);var zt={Policy:T,Retrier:bt,Event:Q,RetrierFactory:Wt,...Wt};t.Event=Q,t.Policy=T,t.Retrier=bt,t.RetrierFactory=Wt,t.default=zt,t.exponentialBackoff=Ct,t.factorIncrease=Ot,t.fixedBackoff=Pt,t.fixedIncrease=$t,t.fixedInterval=At,t.infinite=Tt,t.linearBackoff=jt,t.max=Ft,t.maxRetries=It,t.min=St,t.name=Lt,t.range=Rt,t.shuttleInterval=Bt,t.start=Ut,t.taskTimeout=Dt,t.timeout=Mt,t.times=Nt,Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=index.min.js.map
|