@stackone/transport 2.2.4 → 2.3.0
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/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const l=c(require(`@stackone/utils`)),u=c(require(`redis`)),d=c(require(`axios`)),f=c(require(`node:https`)),p=c(require(`crypto`)),m=c(require(`node:timers`)),h=c(require(`jsonpath`)),g=c(require(`@stackone/redaction`)),_=c(require(`qs`)),v=c(require(`@stackone/expressions`)),y=e=>{switch(e.type){case`none`:return{};case`basic`:return b(e);case`bearer`:return x(e);case`oauth2`:return x(e);default:throw Error(`Invalid authentication type`)}},b=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},x=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var S=class{locks;constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const ee=1e3,C=100,te=60,w=6e4,T=te,ne=w,re=w*10,ie=C,E=10;let D=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ae=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new S,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ne,this.staleDataThreshold=e?.staleDataThreshold??re,this.truncateThreshold=e?.truncateThreshold??ie,this.truncationPercentage=e?.truncationPercentage??E,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async setData({key:e,value:t,cacheTTL:n=T}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,l.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ee,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{((0,l.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,l.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/C;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if((0,l.notMissing)(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:D.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if((0,l.notMissing)(t?.dataStoreSize)&&(0,l.notMissing)(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,l.notMissing)(this.evictionInterval)&&(0,l.notMissing)(this.dataStore)&&(0,l.notMissing)(this.expiryMap)&&(0,l.notMissing)(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const oe=1e3,se=6e4;let ce=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var le=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new ae(i),this.promiseStore=new ae(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/oe;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,l.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,l.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??se),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:ce.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,l.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,l.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,l.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},ue=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,l.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,l.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const de=async(e,t,n)=>{try{let r=await fe.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var fe=class e{#redisClient;#logger;static async build({getRedisClient:t=u.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=me(c??`RedisClient`,l.#logger);return pe(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return(0,l.isString)(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:O.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=(0,l.isString)(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),(0,l.notMissing)(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:O.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:O.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:O.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:O.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:O.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:O.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:O.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:O.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:O.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);(0,l.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:O.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:O.RedisClientDeleteError,category:e.name}),!1}}};const pe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},me=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let he=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var ge=class extends ue{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!0;async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await de(e,i,this.name);if((0,l.isMissing)(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,l.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){(0,l.isMissing)(this.scripts)||Object.keys(this.scripts).length===0||(this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts))}async loadScripts(e,t){if((0,l.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);(0,l.notMissing)(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:he.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if((0,l.isMissing)(r))throw Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,l.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:he.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},_e=class{options={getCacheClient:de};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new ae({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),(0,l.notMissing)(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=(0,l.getContentHash)(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return(0,l.notMissing)(this.subscriptionClient)&&(0,l.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const ve=6e4,ye=15e3,be=!1,xe=6e4,Se=15e3,Ce=1e4,we=1;let Te=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),k=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var A=class extends ge{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if((0,l.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new _e({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:xe,truncateThreshold:Ce,truncationPercentage:we}),await this.subscriptionManager?.initialize(),this.eventClient=new le({instantiator:this.name,timeoutResolveValue:be},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?k.lPush:k.rPush,[e],[t,ve.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ye),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:Te.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(k.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Te.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(k.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Te.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,l.notMissing)(this.subscriptionManager)&&(0,l.notMissing)(this.cacheClient)&&(0,l.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Ee=5,De=12e4,Oe=1e4,ke=1,Ae=60,je=90,Me=`__keyevent@0__:`,Ne=`${Me}set`,Pe=`${Me}expire`,Fe=`${Me}expired`,Ie=`${Me}srem`,Le=`config_check_test_key`,Re=[Ne,Pe,Fe],ze=1,Be=2e4,Ve={mainMaxConcurrency:30};let He=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),Ue=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const We={[Ue.tryConcurrency]:`
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const l=c(require(`@stackone/utils`)),u=c(require(`redis`)),d=c(require(`axios`)),f=c(require(`node:https`)),p=c(require(`crypto`)),m=c(require(`node:timers`)),h=c(require(`jsonpath-plus`)),g=c(require(`@stackone/redaction`)),_=c(require(`qs`)),v=c(require(`@stackone/expressions`)),y=e=>{switch(e.type){case`none`:return{};case`basic`:return b(e);case`bearer`:return x(e);case`oauth2`:return x(e);default:throw Error(`Invalid authentication type`)}},b=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},x=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var S=class{locks;constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const ee=1e3,C=100,te=60,w=6e4,T=te,ne=w,re=w*10,ie=C,E=10;let D=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ae=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new S,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ne,this.staleDataThreshold=e?.staleDataThreshold??re,this.truncateThreshold=e?.truncateThreshold??ie,this.truncationPercentage=e?.truncationPercentage??E,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async setData({key:e,value:t,cacheTTL:n=T}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,l.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ee,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{((0,l.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,l.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/C;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if((0,l.notMissing)(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:D.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if((0,l.notMissing)(t?.dataStoreSize)&&(0,l.notMissing)(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,l.notMissing)(this.evictionInterval)&&(0,l.notMissing)(this.dataStore)&&(0,l.notMissing)(this.expiryMap)&&(0,l.notMissing)(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const oe=1e3,se=6e4;let ce=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var le=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new ae(i),this.promiseStore=new ae(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/oe;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return(0,l.notMissing)(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);(0,l.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??se),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:ce.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,l.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,l.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,l.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},ue=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,l.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,(0,l.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const de=async(e,t,n)=>{try{let r=await fe.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var fe=class e{#redisClient;#logger;static async build({getRedisClient:t=u.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=me(c??`RedisClient`,l.#logger);return pe(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return(0,l.isString)(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:O.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=(0,l.isString)(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),(0,l.notMissing)(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:O.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:O.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:O.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:O.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:O.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:O.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:O.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:O.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:O.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);(0,l.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:O.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:O.RedisClientDeleteError,category:e.name}),!1}}};const pe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},me=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let he=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var ge=class extends ue{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!0;async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=t??await de(e,i,this.name);if((0,l.isMissing)(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,l.notMissing)(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){(0,l.isMissing)(this.scripts)||Object.keys(this.scripts).length===0||(this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts))}async loadScripts(e,t){if((0,l.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);(0,l.notMissing)(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:he.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if((0,l.isMissing)(r))throw Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,l.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:he.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},_e=class{options={getCacheClient:de};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new ae({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),(0,l.notMissing)(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=(0,l.getContentHash)(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return(0,l.notMissing)(this.subscriptionClient)&&(0,l.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const ve=6e4,ye=15e3,be=!1,xe=6e4,Se=15e3,Ce=1e4,we=1;let Te=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),k=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var A=class extends ge{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if((0,l.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new _e({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:xe,truncateThreshold:Ce,truncationPercentage:we}),await this.subscriptionManager?.initialize(),this.eventClient=new le({instantiator:this.name,timeoutResolveValue:be},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?k.lPush:k.rPush,[e],[t,ve.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ye),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:Te.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(k.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Te.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(k.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Te.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,l.notMissing)(this.subscriptionManager)&&(0,l.notMissing)(this.cacheClient)&&(0,l.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Ee=5,De=12e4,Oe=1e4,ke=1,Ae=60,je=90,Me=`__keyevent@0__:`,Ne=`${Me}set`,Pe=`${Me}expire`,Fe=`${Me}expired`,Ie=`${Me}srem`,Le=`config_check_test_key`,Re=[Ne,Pe,Fe],ze=1,Be=2e4,Ve={mainMaxConcurrency:30};let He=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),Ue=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const We={[Ue.tryConcurrency]:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -128,7 +128,7 @@ var Or=9e15,kr=1e9,Ar=`0123456789abcdef`,jr=`2.302585092994045684017991454684364
|
|
|
128
128
|
* Copyright (c) 2023, Robert Eisele (robert@raw.org)
|
|
129
129
|
* Dual licensed under the MIT or GPL Version 2 licenses.
|
|
130
130
|
**/
|
|
131
|
-
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),_a=c(ga(),1),va=`Fraction`,ya=[],ba=or(va,ya,()=>(Object.defineProperty(_a.default,`name`,{value:`Fraction`}),_a.default.prototype.constructor=_a.default,_a.default.prototype.type=`Fraction`,_a.default.prototype.isFraction=!0,_a.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},_a.default.fromJSON=function(e){return new _a.default(e)},_a.default),{isClass:!0}),xa=`Matrix`,Sa=[],Ca=or(xa,Sa,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function wa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ta=`DenseMatrix`,Ea=[`Matrix`],Da=or(Ta,Ea,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!Tt(t))throw Error(`Invalid datatype: `+t);if(Et(e))e.type===`DenseMatrix`?(this._data=on(e._data),this._size=on(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&M(e.data)&&M(e.size))this._data=e.data,this._size=e.size,Hn(this._data,this._size),this._datatype=t||e.datatype;else if(M(e))this._data=l(e),this._size=Bn(this._data),Hn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+an(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return Qn(this._data,an)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!M(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new P(e.length,this._size.length);for(var t=0;t<e.length;t++)F(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];F(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!M(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new P(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],F(a,s.length),s=s[a];return a=e[e.length-1],F(a,s.length),s[a]=t,this};function r(e,t){if(!jt(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new P(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)F(o[c],e._size[c]),F(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return F(t,e.length),e[t]}).valueOf():o.map(function(a){F(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Et(n)?(s=n.size(),n=n.valueOf()):s=Bn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!cn(s,i))try{n=s.length===0?rr([n],i):rr(n,i),s=Bn(n)}catch{}if(i.length<e._size.length)throw new P(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=Yn(n,i.length,u,s)}if(!cn(i,s))throw new P(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){F(t),e[t]=n[r[0]]}):s.forEach(function(a,s){F(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Dt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;M(r);)r=r[0];return r}return e._size=t.slice(0),e._data=Un(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=Gn(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=Kn(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:on(this._data),size:on(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=wa(e),i=function n(i,a){return M(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:Qn(a,an);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){M(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(M(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return on(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Mn(this._data,e)},n.prototype.toString=function(){return Mn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(xt(e)&&(e=e.toNumber()),!j(e)||!N(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!M(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(xt(e)&&(e=e.toNumber()),!j(e)||!N(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(xt(r)&&(r=r.toNumber()),!j(r)||!N(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(M(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Et(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=xt(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=Un(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!j(e)||!N(e)||!j(t)||!N(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return F(e,this._size[0]),F(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Et(e)?l(e.valueOf()):M(e)?e.map(l):e}return n},{isClass:!0});function Oa(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Oa(e,t,n)}):t(e)}var ka=`isNumeric`,Aa=[`typed`],ja=or(ka,Aa,e=>{var{typed:t}=e;return t(ka,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Oa(t,e))})}),Ma=`hasNumericValue`,Na=[`typed`,`isNumeric`],Pa=or(Ma,Na,e=>{var{typed:t,isNumeric:n}=e;return t(Ma,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Fa=oa({config:mn}),Ia=ha({}),La=ba({}),Ra=Ca({}),za=Da({Matrix:Ra}),Ba=Cr({BigNumber:Fa,Complex:Ia,DenseMatrix:za,Fraction:La}),Va=ja({typed:Ba}),Ha=Pa({isNumeric:Va,typed:Ba});const Ua=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},Wa=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+_t;if(!Ua(t)&&(0,l.isFutureUnixTimestamp)(t))return vt(t);if(Ua(t))return n+t;{let e=t*ht;return n+e}},Ga=`ratelimitlimit`,Ka=`ratelimitremaining`,qa=`ratelimitreset`,Ja=`ratelimitconcurrencylimit`,Ya=`ratelimitconcurrencyremaining`,Xa=`ratelimitconcurrencyreset`,Za=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Ha(r)?Number(r):null;t[e]=i}return t},Qa=e=>{let t=Za(e);return{rateLimitLimit:t[Ga],rateLimitRemaining:t[Ka],rateLimitReset:Wa(t[qa]),concurrencyLimit:t[Ja],concurrencyRemaining:t[Ya],concurrencyReset:Wa(t[Xa])}},$a=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l.isMissing)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},eo=(e,t=ft,n=dt)=>{let r=Date.now();return(0,l.isFutureUnixTimestamp)(e)||(0,l.isNumber)(e)?to(Number(e),r,t,n):Tt(e)&&e!==``?no(e,r,t,n):n},to=(e,t,n=ft,r=dt)=>{if(e<n)return e;let i=vt(e);if(i>t){let e=Math.floor((i-t)/ht);return e>0&&e<n?e:r}return r},no=(e,t,n=ft,r=dt)=>{if(gt.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/ht);return e>0&&e<n?e:r}return r},ro=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let i=async i=>{let{response:a,config:o}=i,s=o?.signal;if(s?.aborted)return Promise.reject(st(`Request aborted`,o,`ERR_CANCELED`,a));let{status:c,retryAfter:u}=io(a,r,n,t);if(c===429&&(0,l.notMissing)(o)){let n=eo(u);if(o._retryCount>=pt)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${o?.url}. Aborting.`,context:{...r??{},retryAfterHeader:u,retryAfterAsNumber:n}}),Promise.reject(i);let s=o._retryCount??0,c={...o,_retryCount:s+1},d=u?n*ht:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${o?.url}`,context:{...r??{},retryAfterHeader:u,calculatedRetryAfter:d}}),await ct(d,o,a),e?.request(c)}return Promise.reject(i)};return i},io=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=Za(o??{});if((0,l.isMissing)(i)||(0,l.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,l.isMissing)(e),providerIsMissing:(0,l.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,l.notMissing)(u)&&(0,l.notMissing)(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=(0,l.isObject)(s)?h.default.query(s,f)[0]:s,m=ao(p,r);if(t===a&&m){let e=d??oo(o,i),t=so(e,u);return{status:429,retryAfter:c??t}}}return{status:a,retryAfter:c}},ao=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,oo=(e,t)=>(0,l.notMissing)(t)&&(0,l.notMissing)(e)?h.default.query(e,t)[0]:null,so=(e,t=`seconds`)=>(0,l.notMissing)(e)?co(e,t):null,co=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/ht}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},lo=`rateLimitErrorInterceptor`,uo=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if((0,l.isMissing)(r)||(0,l.isMissing)(s))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:lo,...s,httpsAgent:void 0,headers:void 0,hasContext:(0,l.notMissing)(r),hasConfig:(0,l.notMissing)(s)},code:ot.InterceptorContextNotPresent}),Promise.reject(a);if((0,l.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lo,...s,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(i)},code:ot.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=s?.requestMetadata??{},m=(0,l.notMissing)(u)&&(0,l.notMissing)(d)?await i.releaseRequest(u,d):!1;if(!m&&(0,l.notMissing)(s?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:lo,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:ot.RateLimiterReleaseRequestFailed}),c?.aborted)return Promise.reject(st(`Request aborted`,s,`ERR_CANCELED`,o));let{status:h,retryAfter:g}=io(o,r,n,t);if(h===429&&(0,l.notMissing)(s)){let n=eo(g);if(s._retryCount>=pt)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${s.url}. Aborting.`,context:{...r??{},...s.requestMetadata??{},retryAfterHeader:g,retryAfterAsNumber:n}}),Promise.reject(a);let i=s?._retryCount??0,c={...s,_retryCount:i+1},u=g?n*ht:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${s.url}`,context:{...r,retryAfterHeader:g,calculatedRetryAfter:u}}),await ct(u,s,o),e?.request(c)}return Promise.reject(a)};return a},fo=`rateLimitResponseInterceptor`,po=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if((0,l.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:fo,...i,httpsAgent:void 0,headers:void 0}});else if((0,l.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:fo,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(n)},code:ot.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,l.notMissing)(t.provider)&&(0,l.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,l.notMissing)(t)){let n=Qa(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:fo,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:fo,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u},code:ot.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(st(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},mo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ho=[{onFulfilled:mo,onRejected:null,options:void 0}],go=[{onFulfilled:null,onRejected:ro},{onFulfilled:null,onRejected:nt}],_o=[{onFulfilled:mo,onRejected:null,options:void 0},{onFulfilled:ut,onRejected:null,options:void 0}],vo=[{onFulfilled:po,onRejected:uo},{onFulfilled:null,onRejected:nt}],yo=1,bo=1e3,xo=0,So=59,Co=.8,wo=500;var To=class extends ge{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=So,i=Co,a=wo){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=xo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=xo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/bo)),u=yo/l,d=Math.max(rt,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,l.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(at.incr,[a,...u],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},Z=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,l.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,l.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let Eo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Do=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?ko(e,n):Oo(e,n),(0,l.isMissing)(n?.service)||(0,l.isMissing)(n?.organizationId)||o===`test`||(0,l.isMissing)(t)||(0,l.isMissing)(e))return a;let c=Z.getIfReady(To)??void 0,u=Z.getIfReady(Ge)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(..._o),m.push(...vo)}let h=$a(n);if((0,l.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,l.notMissing)(a)}}),a;let g=await tt.get(h);if((0,l.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},v=Qe.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await tt.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,l.notMissing)(a)},error:t,code:Eo.HttpTransportInstanceCreateError}),(0,l.notMissing)(a)?a:Ao()}},Oo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Qe.createInstance(n)??Ao()},ko=(e,t)=>{let n={interceptors:{requestConfigs:ho,responseConfigs:go},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Qe.createInstance(n)??Ao()},Ao=()=>{let e=d.default.create({maxBodyLength:1/0});return e};var jo=class{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;name=`HttpClient`;constructor({transportFactory:e=Do,getRedisClient:t=de,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:r}){let i=20;if(!r?.accountSecureId||r.accountSecureId.length<i||!e||!n)return null;let a=t?(0,l.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#getCachedResponse({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#redisClient||!r||r<=0)return null;let a=this.#generateCacheKey({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#redisClient.getData(a);return o?(this.#logger?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#logger?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#cacheResponse({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#redisClient||!r||r<=0)return!1;let o=this.#generateCacheKey({url:e,payload:t,method:n,context:i});return o?(this.#logger?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#redisClient.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:m}){try{(0,l.notMissing)(this.#redisClientConfig)&&(0,l.isMissing)(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let h=this.#buildUrlWithQueryParams(t,r),g=this.#normalizeHeaders(e),_=this.#getSafePayload(u,e),v=await this.#getCachedResponse({url:h,payload:_,method:n,cacheTTL:o,context:s});if(v)return{...v,responseTime:new Date};let y=et.getInstance(),b=(0,l.notMissing)(c)?await y.get(c):null,x=b?.signal,S=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:s,requestConfig:p,httpsAgentConfig:m}),ee=await S.request({headers:g,url:h,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:x}),C={data:ee.data,status:ee.status,body:_,method:n,headers:this.#extractAxiosHeaders(ee.headers),requestUrl:t,responseType:ee?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:h,payload:_,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=(0,g.redactUrl)(t),this.#logger?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#mapErrorToHttpException(r);throw(0,l.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!((0,l.isMissing)(e)||(0,l.isObject)(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?_.default.stringify(e):e}#mapErrorToHttpException(e){if((0,d.isAxiosError)(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if((0,l.isMissing)(t)||Object.keys(t).length===0)return e;let n=_.default.stringify(t);return`${e}?${n}`}};const Mo=(e,t,n)=>new jo({redisClientConfig:e,logger:t,errorMappingFn:n});var No=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Mo}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Po=[`get`,`post`,`put`,`delete`,`patch`],Fo={[k.rPush]:`
|
|
131
|
+
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),_a=c(ga(),1),va=`Fraction`,ya=[],ba=or(va,ya,()=>(Object.defineProperty(_a.default,`name`,{value:`Fraction`}),_a.default.prototype.constructor=_a.default,_a.default.prototype.type=`Fraction`,_a.default.prototype.isFraction=!0,_a.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},_a.default.fromJSON=function(e){return new _a.default(e)},_a.default),{isClass:!0}),xa=`Matrix`,Sa=[],Ca=or(xa,Sa,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function wa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ta=`DenseMatrix`,Ea=[`Matrix`],Da=or(Ta,Ea,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!Tt(t))throw Error(`Invalid datatype: `+t);if(Et(e))e.type===`DenseMatrix`?(this._data=on(e._data),this._size=on(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&M(e.data)&&M(e.size))this._data=e.data,this._size=e.size,Hn(this._data,this._size),this._datatype=t||e.datatype;else if(M(e))this._data=l(e),this._size=Bn(this._data),Hn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+an(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return Qn(this._data,an)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!M(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new P(e.length,this._size.length);for(var t=0;t<e.length;t++)F(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];F(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!M(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new P(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],F(a,s.length),s=s[a];return a=e[e.length-1],F(a,s.length),s[a]=t,this};function r(e,t){if(!jt(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new P(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)F(o[c],e._size[c]),F(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return F(t,e.length),e[t]}).valueOf():o.map(function(a){F(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Et(n)?(s=n.size(),n=n.valueOf()):s=Bn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!cn(s,i))try{n=s.length===0?rr([n],i):rr(n,i),s=Bn(n)}catch{}if(i.length<e._size.length)throw new P(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=Yn(n,i.length,u,s)}if(!cn(i,s))throw new P(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){F(t),e[t]=n[r[0]]}):s.forEach(function(a,s){F(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Dt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;M(r);)r=r[0];return r}return e._size=t.slice(0),e._data=Un(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=Gn(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=Kn(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:on(this._data),size:on(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=wa(e),i=function n(i,a){return M(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:Qn(a,an);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){M(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(M(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return on(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Mn(this._data,e)},n.prototype.toString=function(){return Mn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(xt(e)&&(e=e.toNumber()),!j(e)||!N(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!M(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(xt(e)&&(e=e.toNumber()),!j(e)||!N(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(xt(r)&&(r=r.toNumber()),!j(r)||!N(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(M(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Et(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=xt(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=Un(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!j(e)||!N(e)||!j(t)||!N(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return F(e,this._size[0]),F(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Et(e)?l(e.valueOf()):M(e)?e.map(l):e}return n},{isClass:!0});function Oa(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Oa(e,t,n)}):t(e)}var ka=`isNumeric`,Aa=[`typed`],ja=or(ka,Aa,e=>{var{typed:t}=e;return t(ka,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Oa(t,e))})}),Ma=`hasNumericValue`,Na=[`typed`,`isNumeric`],Pa=or(Ma,Na,e=>{var{typed:t,isNumeric:n}=e;return t(Ma,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Fa=oa({config:mn}),Ia=ha({}),La=ba({}),Ra=Ca({}),za=Da({Matrix:Ra}),Ba=Cr({BigNumber:Fa,Complex:Ia,DenseMatrix:za,Fraction:La}),Va=ja({typed:Ba}),Ha=Pa({isNumeric:Va,typed:Ba});const Ua=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},Wa=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+_t;if(!Ua(t)&&(0,l.isFutureUnixTimestamp)(t))return vt(t);if(Ua(t))return n+t;{let e=t*ht;return n+e}},Ga=`ratelimitlimit`,Ka=`ratelimitremaining`,qa=`ratelimitreset`,Ja=`ratelimitconcurrencylimit`,Ya=`ratelimitconcurrencyremaining`,Xa=`ratelimitconcurrencyreset`,Za=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Ha(r)?Number(r):null;t[e]=i}return t},Qa=e=>{let t=Za(e);return{rateLimitLimit:t[Ga],rateLimitRemaining:t[Ka],rateLimitReset:Wa(t[qa]),concurrencyLimit:t[Ja],concurrencyRemaining:t[Ya],concurrencyReset:Wa(t[Xa])}},$a=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l.isMissing)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},eo=(e,t=ft,n=dt)=>{let r=Date.now();return(0,l.isFutureUnixTimestamp)(e)||(0,l.isNumber)(e)?to(Number(e),r,t,n):Tt(e)&&e!==``?no(e,r,t,n):n},to=(e,t,n=ft,r=dt)=>{if(e<n)return e;let i=vt(e);if(i>t){let e=Math.floor((i-t)/ht);return e>0&&e<n?e:r}return r},no=(e,t,n=ft,r=dt)=>{if(gt.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/ht);return e>0&&e<n?e:r}return r},ro=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let i=async i=>{let{response:a,config:o}=i,s=o?.signal;if(s?.aborted)return Promise.reject(st(`Request aborted`,o,`ERR_CANCELED`,a));let{status:c,retryAfter:u}=io(a,r,n,t);if(c===429&&(0,l.notMissing)(o)){let n=eo(u);if(o._retryCount>=pt)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${o?.url}. Aborting.`,context:{...r??{},retryAfterHeader:u,retryAfterAsNumber:n}}),Promise.reject(i);let s=o._retryCount??0,c={...o,_retryCount:s+1},d=u?n*ht:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${o?.url}`,context:{...r??{},retryAfterHeader:u,calculatedRetryAfter:d}}),await ct(d,o,a),e?.request(c)}return Promise.reject(i)};return i},io=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=Za(o??{});if((0,l.isMissing)(i)||(0,l.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,l.isMissing)(e),providerIsMissing:(0,l.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,l.notMissing)(u)&&(0,l.notMissing)(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=(0,l.isObject)(s)?(0,h.JSONPath)({path:f,json:s})[0]:s,m=ao(p,r);if(t===a&&m){let e=d??oo(o,i),t=so(e,u);return{status:429,retryAfter:c??t}}}return{status:a,retryAfter:c}},ao=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,oo=(e,t)=>(0,l.notMissing)(t)&&(0,l.notMissing)(e)?(0,h.JSONPath)({path:t,json:e})[0]:null,so=(e,t=`seconds`)=>(0,l.notMissing)(e)?co(e,t):null,co=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/ht}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},lo=`rateLimitErrorInterceptor`,uo=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if((0,l.isMissing)(r)||(0,l.isMissing)(s))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:lo,...s,httpsAgent:void 0,headers:void 0,hasContext:(0,l.notMissing)(r),hasConfig:(0,l.notMissing)(s)},code:ot.InterceptorContextNotPresent}),Promise.reject(a);if((0,l.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lo,...s,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(i)},code:ot.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=s?.requestMetadata??{},m=(0,l.notMissing)(u)&&(0,l.notMissing)(d)?await i.releaseRequest(u,d):!1;if(!m&&(0,l.notMissing)(s?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:lo,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:ot.RateLimiterReleaseRequestFailed}),c?.aborted)return Promise.reject(st(`Request aborted`,s,`ERR_CANCELED`,o));let{status:h,retryAfter:g}=io(o,r,n,t);if(h===429&&(0,l.notMissing)(s)){let n=eo(g);if(s._retryCount>=pt)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${s.url}. Aborting.`,context:{...r??{},...s.requestMetadata??{},retryAfterHeader:g,retryAfterAsNumber:n}}),Promise.reject(a);let i=s?._retryCount??0,c={...s,_retryCount:i+1},u=g?n*ht:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${s.url}`,context:{...r,retryAfterHeader:g,calculatedRetryAfter:u}}),await ct(u,s,o),e?.request(c)}return Promise.reject(a)};return a},fo=`rateLimitResponseInterceptor`,po=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if((0,l.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:fo,...i,httpsAgent:void 0,headers:void 0}});else if((0,l.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:fo,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(n)},code:ot.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,l.notMissing)(t.provider)&&(0,l.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,l.notMissing)(t)){let n=Qa(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:fo,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:fo,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u},code:ot.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(st(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},mo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ho=[{onFulfilled:mo,onRejected:null,options:void 0}],go=[{onFulfilled:null,onRejected:ro},{onFulfilled:null,onRejected:nt}],_o=[{onFulfilled:mo,onRejected:null,options:void 0},{onFulfilled:ut,onRejected:null,options:void 0}],vo=[{onFulfilled:po,onRejected:uo},{onFulfilled:null,onRejected:nt}],yo=1,bo=1e3,xo=0,So=59,Co=.8,wo=500;var To=class extends ge{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=So,i=Co,a=wo){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=xo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=xo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/bo)),u=yo/l,d=Math.max(rt,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,l.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(at.incr,[a,...u],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},Z=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,l.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,l.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let Eo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Do=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?ko(e,n):Oo(e,n),(0,l.isMissing)(n?.service)||(0,l.isMissing)(n?.organizationId)||o===`test`||(0,l.isMissing)(t)||(0,l.isMissing)(e))return a;let c=Z.getIfReady(To)??void 0,u=Z.getIfReady(Ge)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(..._o),m.push(...vo)}let h=$a(n);if((0,l.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,l.notMissing)(a)}}),a;let g=await tt.get(h);if((0,l.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},v=Qe.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await tt.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,l.notMissing)(a)},error:t,code:Eo.HttpTransportInstanceCreateError}),(0,l.notMissing)(a)?a:Ao()}},Oo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Qe.createInstance(n)??Ao()},ko=(e,t)=>{let n={interceptors:{requestConfigs:ho,responseConfigs:go},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Qe.createInstance(n)??Ao()},Ao=()=>{let e=d.default.create({maxBodyLength:1/0});return e};var jo=class{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;name=`HttpClient`;constructor({transportFactory:e=Do,getRedisClient:t=de,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:r}){let i=20;if(!r?.accountSecureId||r.accountSecureId.length<i||!e||!n)return null;let a=t?(0,l.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#getCachedResponse({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#redisClient||!r||r<=0)return null;let a=this.#generateCacheKey({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#redisClient.getData(a);return o?(this.#logger?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#logger?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#cacheResponse({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#redisClient||!r||r<=0)return!1;let o=this.#generateCacheKey({url:e,payload:t,method:n,context:i});return o?(this.#logger?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#redisClient.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:m}){try{(0,l.notMissing)(this.#redisClientConfig)&&(0,l.isMissing)(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let h=this.#buildUrlWithQueryParams(t,r),g=this.#normalizeHeaders(e),_=this.#getSafePayload(u,e),v=await this.#getCachedResponse({url:h,payload:_,method:n,cacheTTL:o,context:s});if(v)return{...v,responseTime:new Date};let y=et.getInstance(),b=(0,l.notMissing)(c)?await y.get(c):null,x=b?.signal,S=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:s,requestConfig:p,httpsAgentConfig:m}),ee=await S.request({headers:g,url:h,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:x}),C={data:ee.data,status:ee.status,body:_,method:n,headers:this.#extractAxiosHeaders(ee.headers),requestUrl:t,responseType:ee?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:h,payload:_,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=(0,g.redactUrl)(t),this.#logger?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#mapErrorToHttpException(r);throw(0,l.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!((0,l.isMissing)(e)||(0,l.isObject)(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?_.default.stringify(e):e}#mapErrorToHttpException(e){if((0,d.isAxiosError)(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if((0,l.isMissing)(t)||Object.keys(t).length===0)return e;let n=_.default.stringify(t);return`${e}?${n}`}};const Mo=(e,t,n)=>new jo({redisClientConfig:e,logger:t,errorMappingFn:n});var No=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Mo}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Po=[`get`,`post`,`put`,`delete`,`patch`],Fo={[k.rPush]:`
|
|
132
132
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
133
133
|
|
|
134
134
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{delay as e,exponentialBackoffInMS as t,generateRequestId as n,getContentHash as r,isFunction as i,isFutureUnixTimestamp as a,isMissing as o,isNumber as s,isObject as c,isString as l,notMissing as u,z as d,zStrictObject as f}from"@stackone/utils";import*as p from"redis";import m,{isAxiosError as h}from"axios";import g from"node:https";import{randomUUID as _}from"crypto";import{clearTimeout as v}from"node:timers";import y from"jsonpath";import{redactUrl as b}from"@stackone/redaction";import x from"qs";import{evaluate as S,safeEvaluate as ee}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),O=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ne.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},k=(e,t,n)=>(n=e==null?{}:C(te(e)),O(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const re=e=>{switch(e.type){case`none`:return{};case`basic`:return ie(e);case`bearer`:return ae(e);case`oauth2`:return ae(e);default:throw Error(`Invalid authentication type`)}},ie=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},ae=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var oe=class{locks;constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const se=1e3,ce=100,le=60,ue=6e4,de=le,fe=ue,pe=ue*10,me=ce,he=10;let ge=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var _e=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new oe,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??fe,this.staleDataThreshold=e?.staleDataThreshold??pe,this.truncateThreshold=e?.truncateThreshold??me,this.truncationPercentage=e?.truncationPercentage??he,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async setData({key:e,value:t,cacheTTL:n=de}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*se,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{(u(this.typeGuard)&&this.typeGuard(t)||o(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/ce;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if(u(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:ge.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if(u(t?.dataStoreSize)&&u(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return u(this.evictionInterval)&&u(this.dataStore)&&u(this.expiryMap)&&u(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const ve=1e3,ye=6e4;let be=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var xe=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new _e(i),this.promiseStore=new _e(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/ve;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return u(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);o(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??ye),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:be.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){u(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):u(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return c(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},Se=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(o(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,o(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const Ce=async(e,t,n)=>{try{let r=await we.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var we=class e{#redisClient;#logger;static async build({getRedisClient:t=p.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=Ee(c??`RedisClient`,l.#logger);return Te(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return l(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:A.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=l(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),u(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:A.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:A.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:A.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:A.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:A.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:A.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:A.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:A.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:A.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);u(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:A.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:A.RedisClientDeleteError,category:e.name}),!1}}};const Te=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},Ee=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let De=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Oe=class extends Se{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!0;async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await Ce(e,i,this.name);if(o(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();u(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){o(this.scripts)||Object.keys(this.scripts).length===0||(this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts))}async loadScripts(e,t){if(u(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);u(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:De.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if(o(r))throw Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),o(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:De.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},ke=class{options={getCacheClient:Ce};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new _e({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),u(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),i=r(t.toString());return await this.subscriptionMap?.setData({key:e,value:i}),n===i?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return u(this.subscriptionClient)&&u(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const Ae=6e4,je=15e3,Me=!1,Ne=6e4,Pe=15e3,Fe=1e4,Ie=1;let Le=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Re=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var ze=class extends Oe{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if(o(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new ke({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:Ne,truncateThreshold:Fe,truncationPercentage:Ie}),await this.subscriptionManager?.initialize(),this.eventClient=new xe({instantiator:this.name,timeoutResolveValue:Me},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?Re.lPush:Re.rPush,[e],[t,Ae.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,je),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:Le.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Re.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Le.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Re.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Le.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return u(this.subscriptionManager)&&u(this.cacheClient)&&u(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Be=5,Ve=12e4,He=1e4,Ue=1,We=60,Ge=90,Ke=`__keyevent@0__:`,qe=`${Ke}set`,Je=`${Ke}expire`,Ye=`${Ke}expired`,Xe=`${Ke}srem`,Ze=`config_check_test_key`,Qe=[qe,Je,Ye],$e=1,et=2e4,tt={mainMaxConcurrency:30};let nt=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),rt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const it={[rt.tryConcurrency]:`
|
|
1
|
+
import{delay as e,exponentialBackoffInMS as t,generateRequestId as n,getContentHash as r,isFunction as i,isFutureUnixTimestamp as a,isMissing as o,isNumber as s,isObject as c,isString as l,notMissing as u,z as d,zStrictObject as f}from"@stackone/utils";import*as p from"redis";import m,{isAxiosError as h}from"axios";import g from"node:https";import{randomUUID as _}from"crypto";import{clearTimeout as v}from"node:timers";import{JSONPath as y}from"jsonpath-plus";import{redactUrl as b}from"@stackone/redaction";import x from"qs";import{evaluate as S,safeEvaluate as ee}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),O=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ne.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},k=(e,t,n)=>(n=e==null?{}:C(te(e)),O(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const re=e=>{switch(e.type){case`none`:return{};case`basic`:return ie(e);case`bearer`:return ae(e);case`oauth2`:return ae(e);default:throw Error(`Invalid authentication type`)}},ie=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},ae=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var oe=class{locks;constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const se=1e3,ce=100,le=60,ue=6e4,de=le,fe=ue,pe=ue*10,me=ce,he=10;let ge=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var _e=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new oe,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??fe,this.staleDataThreshold=e?.staleDataThreshold??pe,this.truncateThreshold=e?.truncateThreshold??me,this.truncationPercentage=e?.truncationPercentage??he,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async setData({key:e,value:t,cacheTTL:n=de}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*se,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{(u(this.typeGuard)&&this.typeGuard(t)||o(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/ce;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if(u(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:ge.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if(u(t?.dataStoreSize)&&u(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return u(this.evictionInterval)&&u(this.dataStore)&&u(this.expiryMap)&&u(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const ve=1e3,ye=6e4;let be=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var xe=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new _e(i),this.promiseStore=new _e(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/ve;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return u(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);o(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??ye),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:be.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){u(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):u(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return c(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},Se=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(o(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,o(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const Ce=async(e,t,n)=>{try{let r=await we.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var we=class e{#redisClient;#logger;static async build({getRedisClient:t=p.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=Ee(c??`RedisClient`,l.#logger);return Te(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return l(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:A.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=l(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),u(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:A.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:A.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:A.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:A.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:A.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:A.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:A.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:A.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:A.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);u(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:A.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:A.RedisClientDeleteError,category:e.name}),!1}}};const Te=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},Ee=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.RedisClientError,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];let De=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Oe=class extends Se{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!0;async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let s=t??await Ce(e,i,this.name);if(o(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();u(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){o(this.scripts)||Object.keys(this.scripts).length===0||(this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts))}async loadScripts(e,t){if(u(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);u(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:De.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if(o(r))throw Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),o(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:De.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},ke=class{options={getCacheClient:Ce};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new _e({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),u(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),i=r(t.toString());return await this.subscriptionMap?.setData({key:e,value:i}),n===i?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return u(this.subscriptionClient)&&u(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const Ae=6e4,je=15e3,Me=!1,Ne=6e4,Pe=15e3,Fe=1e4,Ie=1;let Le=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Re=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var ze=class extends Oe{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if(o(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new ke({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:Ne,truncateThreshold:Fe,truncationPercentage:Ie}),await this.subscriptionManager?.initialize(),this.eventClient=new xe({instantiator:this.name,timeoutResolveValue:Me},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?Re.lPush:Re.rPush,[e],[t,Ae.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,je),await this.eventClient?.deleteEvent(a),await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:Le.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Re.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Le.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Re.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Le.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return u(this.subscriptionManager)&&u(this.cacheClient)&&u(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Be=5,Ve=12e4,He=1e4,Ue=1,We=60,Ge=90,Ke=`__keyevent@0__:`,qe=`${Ke}set`,Je=`${Ke}expire`,Ye=`${Ke}expired`,Xe=`${Ke}srem`,Ze=`config_check_test_key`,Qe=[qe,Je,Ye],$e=1,et=2e4,tt={mainMaxConcurrency:30};let nt=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),rt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const it={[rt.tryConcurrency]:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -128,7 +128,7 @@ var Vr=9e15,Hr=1e9,Ur=`0123456789abcdef`,Wr=`2.302585092994045684017991454684364
|
|
|
128
128
|
* Copyright (c) 2023, Robert Eisele (robert@raw.org)
|
|
129
129
|
* Dual licensed under the MIT or GPL Version 2 licenses.
|
|
130
130
|
**/
|
|
131
|
-
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),Aa=k(ka(),1),ja=`Fraction`,Ma=[],Na=yr(ja,Ma,()=>(Object.defineProperty(Aa.default,`name`,{value:`Fraction`}),Aa.default.prototype.constructor=Aa.default,Aa.default.prototype.type=`Fraction`,Aa.default.prototype.isFraction=!0,Aa.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},Aa.default.fromJSON=function(e){return new Aa.default(e)},Aa.default),{isClass:!0}),Pa=`Matrix`,Fa=[],Ia=yr(Pa,Fa,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function La(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ra=`DenseMatrix`,za=[`Matrix`],Ba=yr(Ra,za,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!zt(t))throw Error(`Invalid datatype: `+t);if(Bt(e))e.type===`DenseMatrix`?(this._data=bn(e._data),this._size=bn(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&M(e.data)&&M(e.size))this._data=e.data,this._size=e.size,tr(this._data,this._size),this._datatype=t||e.datatype;else if(M(e))this._data=l(e),this._size=$n(this._data),tr(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+yn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return dr(this._data,yn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!M(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new P(e.length,this._size.length);for(var t=0;t<e.length;t++)F(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];F(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!M(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new P(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],F(a,s.length),s=s[a];return a=e[e.length-1],F(a,s.length),s[a]=t,this};function r(e,t){if(!Gt(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new P(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)F(o[c],e._size[c]),F(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return F(t,e.length),e[t]}).valueOf():o.map(function(a){F(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Bt(n)?(s=n.size(),n=n.valueOf()):s=$n(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!Sn(s,i))try{n=s.length===0?gr([n],i):gr(n,i),s=$n(n)}catch{}if(i.length<e._size.length)throw new P(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=cr(n,i.length,u,s)}if(!Sn(i,s))throw new P(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){F(t),e[t]=n[r[0]]}):s.forEach(function(a,s){F(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Vt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;M(r);)r=r[0];return r}return e._size=t.slice(0),e._data=nr(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=ir(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=ar(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:bn(this._data),size:bn(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=La(e),i=function n(i,a){return M(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:dr(a,yn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){M(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(M(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return bn(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Gn(this._data,e)},n.prototype.toString=function(){return Gn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(Ft(e)&&(e=e.toNumber()),!j(e)||!N(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!M(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(Ft(e)&&(e=e.toNumber()),!j(e)||!N(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(Ft(r)&&(r=r.toNumber()),!j(r)||!N(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(M(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Bt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=Ft(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=nr(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!j(e)||!N(e)||!j(t)||!N(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return F(e,this._size[0]),F(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Bt(e)?l(e.valueOf()):M(e)?e.map(l):e}return n},{isClass:!0});function Va(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Va(e,t,n)}):t(e)}var Ha=`isNumeric`,Ua=[`typed`],Wa=yr(Ha,Ua,e=>{var{typed:t}=e;return t(Ha,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Va(t,e))})}),Ga=`hasNumericValue`,Ka=[`typed`,`isNumeric`],qa=yr(Ga,Ka,e=>{var{typed:t,isNumeric:n}=e;return t(Ga,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Ja=ya({config:On}),Ya=Oa({}),Xa=Na({}),Za=Ia({}),Qa=Ba({Matrix:Za}),$a=Ir({BigNumber:Ja,Complex:Ya,DenseMatrix:Qa,Fraction:Xa}),eo=Wa({typed:$a}),to=qa({isNumeric:eo,typed:$a});const no=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},ro=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+jt;if(!no(t)&&a(t))return Mt(t);if(no(t))return n+t;{let e=t*kt;return n+e}},io=`ratelimitlimit`,ao=`ratelimitremaining`,oo=`ratelimitreset`,so=`ratelimitconcurrencylimit`,co=`ratelimitconcurrencyremaining`,lo=`ratelimitconcurrencyreset`,uo=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=to(r)?Number(r):null;t[e]=i}return t},fo=e=>{let t=uo(e);return{rateLimitLimit:t[io],rateLimitRemaining:t[ao],rateLimitReset:ro(t[oo]),concurrencyLimit:t[so],concurrencyRemaining:t[co],concurrencyReset:ro(t[lo])}},po=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},mo=(e,t=Et,n=Tt)=>{let r=Date.now();return a(e)||s(e)?ho(Number(e),r,t,n):zt(e)&&e!==``?go(e,r,t,n):n},ho=(e,t,n=Et,r=Tt)=>{if(e<n)return e;let i=Mt(e);if(i>t){let e=Math.floor((i-t)/kt);return e>0&&e<n?e:r}return r},go=(e,t,n=Et,r=Tt)=>{if(At.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/kt);return e>0&&e<n?e:r}return r},_o=({axiosInstance:e,logger:n,requestConfig:r,context:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if(c?.aborted)return Promise.reject(xt(`Request aborted`,s,`ERR_CANCELED`,o));let{status:l,retryAfter:d}=vo(o,i,r,n);if(l===429&&u(s)){let r=mo(d);if(s._retryCount>=Dt)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:d,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,l={...s,_retryCount:c+1},u=d?r*kt:t(l._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:d,calculatedRetryAfter:u}}),await St(u,s,o),e?.request(l)}return Promise.reject(a)};return a},vo=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:l}=e??{},{retryafter:d}=uo(s??{});if(o(i)||o(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:o(e),providerIsMissing:o(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:d??`undefined`}}),{status:a,retryAfter:d};let f=n?.rateLimits?.mappedRateLimitErrors;if(u(f)&&u(l))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:o,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=c(l)?y.query(l,f)[0]:l,m=yo(p,r);if(t===a&&m){let e=u??bo(s,i),t=xo(e,o);return{status:429,retryAfter:d??t}}}return{status:a,retryAfter:d}},yo=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,bo=(e,t)=>u(t)&&u(e)?y.query(e,t)[0]:null,xo=(e,t=`seconds`)=>u(e)?So(e,t):null,So=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/kt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},Co=`rateLimitErrorInterceptor`,wo=({axiosInstance:e,logger:n,requestConfig:r,context:i,concurrencyManager:a})=>{let s=async s=>{let{response:c,config:l}=s,d=l?.signal;if(o(i)||o(l))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:Co,...l,httpsAgent:void 0,headers:void 0,hasContext:u(i),hasConfig:u(l)},code:bt.InterceptorContextNotPresent}),Promise.reject(s);if(o(a))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:Co,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:u(a)},code:bt.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(s);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h}=l?.requestMetadata??{},g=u(f)&&u(p)?await a.releaseRequest(f,p):!1;if(!g&&u(l?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:Co,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:bt.RateLimiterReleaseRequestFailed}),d?.aborted)return Promise.reject(xt(`Request aborted`,l,`ERR_CANCELED`,c));let{status:_,retryAfter:v}=vo(c,i,r,n);if(_===429&&u(l)){let r=mo(v);if(l._retryCount>=Dt)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:v,retryAfterAsNumber:r}}),Promise.reject(s);let a=l?._retryCount??0,o={...l,_retryCount:a+1},u=v?r*kt:t(o._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:v,calculatedRetryAfter:u}}),await St(u,l,c),e?.request(o)}return Promise.reject(s)};return s},To=`rateLimitResponseInterceptor`,Eo=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if(o(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:To,...i,httpsAgent:void 0,headers:void 0}});else if(o(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:To,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:u(n)},code:bt.RateLimitOrConcurrencyManagerNotInitialized}),r;else if(u(t.provider)&&u(t.accountSecureId)){let t=r?.headers;if(u(t)){let n=fo(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:To,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:To,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:bt.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(xt(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},Do=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Oo=[{onFulfilled:Do,onRejected:null,options:void 0}],ko=[{onFulfilled:null,onRejected:_o},{onFulfilled:null,onRejected:gt}],Ao=[{onFulfilled:Do,onRejected:null,options:void 0},{onFulfilled:wt,onRejected:null,options:void 0}],jo=[{onFulfilled:Eo,onRejected:wo},{onFulfilled:null,onRejected:gt}],Mo=1,No=1e3,Po=0,Fo=59,Io=.8,Lo=500;var Ro=class extends Oe{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=Fo,i=Io,a=Lo){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=Po)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=Po)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/No)),u=Mo/l,d=Math.max(_t,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=u(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(yt.incr,[a,...l],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},Z=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(o(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(u(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let zo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Bo=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?Ho(e,n):Vo(e,n),o(n?.service)||o(n?.organizationId)||s===`test`||o(t)||o(e))return a;let l=Z.getIfReady(Ro)??void 0,d=Z.getIfReady(at)??void 0,f=l?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Ao),h.push(...jo)}let g=po(n);if(o(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:u(a)}}),a;let _=await ht.get(g);if(u(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:d,rateLimitManager:l},y=ft.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ht.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:u(a)},error:t,code:zo.HttpTransportInstanceCreateError}),u(a)?a:Uo()}},Vo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ft.createInstance(n)??Uo()},Ho=(e,t)=>{let n={interceptors:{requestConfigs:Oo,responseConfigs:ko},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ft.createInstance(n)??Uo()},Uo=()=>{let e=m.create({maxBodyLength:1/0});return e};var Wo=class{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;name=`HttpClient`;constructor({transportFactory:e=Bo,getRedisClient:t=Ce,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:i}){let a=20;if(!i?.accountSecureId||i.accountSecureId.length<a||!e||!n)return null;let o=t?r(t):``;return`${i.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#getCachedResponse({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#redisClient||!r||r<=0)return null;let a=this.#generateCacheKey({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#redisClient.getData(a);return o?(this.#logger?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#logger?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#cacheResponse({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#redisClient||!r||r<=0)return!1;let o=this.#generateCacheKey({url:e,payload:t,method:n,context:i});return o?(this.#logger?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#redisClient.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{u(this.#redisClientConfig)&&o(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let g=this.#buildUrlWithQueryParams(t,r),_=this.#normalizeHeaders(e),v=this.#getSafePayload(d,e),y=await this.#getCachedResponse({url:g,payload:v,method:n,cacheTTL:s,context:c});if(y)return{...y,responseTime:new Date};let b=mt.getInstance(),x=u(l)?await b.get(l):null,S=x?.signal,ee=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:c,requestConfig:m,httpsAgentConfig:h}),C=await ee.request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:f,httpAgent:p,signal:S}),w={data:C.data,status:C.status,body:v,method:n,headers:this.#extractAxiosHeaders(C.headers),requestUrl:t,responseType:C?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:g,payload:v,method:n,cacheTTL:s,context:c,response:w}),w}catch(e){let r=e;r.url=b(t),this.#logger?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#mapErrorToHttpException(r);throw u(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!(o(e)||c(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?x.stringify(e):e}#mapErrorToHttpException(e){if(h(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if(o(t)||Object.keys(t).length===0)return e;let n=x.stringify(t);return`${e}?${n}`}};const Go=(e,t,n)=>new Wo({redisClientConfig:e,logger:t,errorMappingFn:n});var Ko=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Go}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const qo=[`get`,`post`,`put`,`delete`,`patch`],Jo={[Re.rPush]:`
|
|
131
|
+
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),Aa=k(ka(),1),ja=`Fraction`,Ma=[],Na=yr(ja,Ma,()=>(Object.defineProperty(Aa.default,`name`,{value:`Fraction`}),Aa.default.prototype.constructor=Aa.default,Aa.default.prototype.type=`Fraction`,Aa.default.prototype.isFraction=!0,Aa.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},Aa.default.fromJSON=function(e){return new Aa.default(e)},Aa.default),{isClass:!0}),Pa=`Matrix`,Fa=[],Ia=yr(Pa,Fa,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function La(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ra=`DenseMatrix`,za=[`Matrix`],Ba=yr(Ra,za,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!zt(t))throw Error(`Invalid datatype: `+t);if(Bt(e))e.type===`DenseMatrix`?(this._data=bn(e._data),this._size=bn(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&M(e.data)&&M(e.size))this._data=e.data,this._size=e.size,tr(this._data,this._size),this._datatype=t||e.datatype;else if(M(e))this._data=l(e),this._size=$n(this._data),tr(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+yn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return dr(this._data,yn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!M(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new P(e.length,this._size.length);for(var t=0;t<e.length;t++)F(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];F(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!M(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new P(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],F(a,s.length),s=s[a];return a=e[e.length-1],F(a,s.length),s[a]=t,this};function r(e,t){if(!Gt(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new P(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)F(o[c],e._size[c]),F(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return F(t,e.length),e[t]}).valueOf():o.map(function(a){F(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Bt(n)?(s=n.size(),n=n.valueOf()):s=$n(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!Sn(s,i))try{n=s.length===0?gr([n],i):gr(n,i),s=$n(n)}catch{}if(i.length<e._size.length)throw new P(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=cr(n,i.length,u,s)}if(!Sn(i,s))throw new P(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){F(t),e[t]=n[r[0]]}):s.forEach(function(a,s){F(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Vt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;M(r);)r=r[0];return r}return e._size=t.slice(0),e._data=nr(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=ir(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=ar(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:bn(this._data),size:bn(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=La(e),i=function n(i,a){return M(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:dr(a,yn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){M(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(M(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return bn(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Gn(this._data,e)},n.prototype.toString=function(){return Gn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(Ft(e)&&(e=e.toNumber()),!j(e)||!N(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!M(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(Ft(e)&&(e=e.toNumber()),!j(e)||!N(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(Ft(r)&&(r=r.toNumber()),!j(r)||!N(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(M(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Bt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=Ft(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=nr(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!j(e)||!N(e)||!j(t)||!N(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return F(e,this._size[0]),F(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Bt(e)?l(e.valueOf()):M(e)?e.map(l):e}return n},{isClass:!0});function Va(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Va(e,t,n)}):t(e)}var Ha=`isNumeric`,Ua=[`typed`],Wa=yr(Ha,Ua,e=>{var{typed:t}=e;return t(Ha,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Va(t,e))})}),Ga=`hasNumericValue`,Ka=[`typed`,`isNumeric`],qa=yr(Ga,Ka,e=>{var{typed:t,isNumeric:n}=e;return t(Ga,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Ja=ya({config:On}),Ya=Oa({}),Xa=Na({}),Za=Ia({}),Qa=Ba({Matrix:Za}),$a=Ir({BigNumber:Ja,Complex:Ya,DenseMatrix:Qa,Fraction:Xa}),eo=Wa({typed:$a}),to=qa({isNumeric:eo,typed:$a});const no=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},ro=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+jt;if(!no(t)&&a(t))return Mt(t);if(no(t))return n+t;{let e=t*kt;return n+e}},io=`ratelimitlimit`,ao=`ratelimitremaining`,oo=`ratelimitreset`,so=`ratelimitconcurrencylimit`,co=`ratelimitconcurrencyremaining`,lo=`ratelimitconcurrencyreset`,uo=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=to(r)?Number(r):null;t[e]=i}return t},fo=e=>{let t=uo(e);return{rateLimitLimit:t[io],rateLimitRemaining:t[ao],rateLimitReset:ro(t[oo]),concurrencyLimit:t[so],concurrencyRemaining:t[co],concurrencyReset:ro(t[lo])}},po=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},mo=(e,t=Et,n=Tt)=>{let r=Date.now();return a(e)||s(e)?ho(Number(e),r,t,n):zt(e)&&e!==``?go(e,r,t,n):n},ho=(e,t,n=Et,r=Tt)=>{if(e<n)return e;let i=Mt(e);if(i>t){let e=Math.floor((i-t)/kt);return e>0&&e<n?e:r}return r},go=(e,t,n=Et,r=Tt)=>{if(At.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/kt);return e>0&&e<n?e:r}return r},_o=({axiosInstance:e,logger:n,requestConfig:r,context:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if(c?.aborted)return Promise.reject(xt(`Request aborted`,s,`ERR_CANCELED`,o));let{status:l,retryAfter:d}=vo(o,i,r,n);if(l===429&&u(s)){let r=mo(d);if(s._retryCount>=Dt)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:d,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,l={...s,_retryCount:c+1},u=d?r*kt:t(l._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:d,calculatedRetryAfter:u}}),await St(u,s,o),e?.request(l)}return Promise.reject(a)};return a},vo=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:l}=e??{},{retryafter:d}=uo(s??{});if(o(i)||o(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:o(e),providerIsMissing:o(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:d??`undefined`}}),{status:a,retryAfter:d};let f=n?.rateLimits?.mappedRateLimitErrors;if(u(f)&&u(l))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:o,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=c(l)?y({path:f,json:l})[0]:l,m=yo(p,r);if(t===a&&m){let e=u??bo(s,i),t=xo(e,o);return{status:429,retryAfter:d??t}}}return{status:a,retryAfter:d}},yo=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,bo=(e,t)=>u(t)&&u(e)?y({path:t,json:e})[0]:null,xo=(e,t=`seconds`)=>u(e)?So(e,t):null,So=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/kt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},Co=`rateLimitErrorInterceptor`,wo=({axiosInstance:e,logger:n,requestConfig:r,context:i,concurrencyManager:a})=>{let s=async s=>{let{response:c,config:l}=s,d=l?.signal;if(o(i)||o(l))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:Co,...l,httpsAgent:void 0,headers:void 0,hasContext:u(i),hasConfig:u(l)},code:bt.InterceptorContextNotPresent}),Promise.reject(s);if(o(a))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:Co,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:u(a)},code:bt.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(s);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h}=l?.requestMetadata??{},g=u(f)&&u(p)?await a.releaseRequest(f,p):!1;if(!g&&u(l?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:Co,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:bt.RateLimiterReleaseRequestFailed}),d?.aborted)return Promise.reject(xt(`Request aborted`,l,`ERR_CANCELED`,c));let{status:_,retryAfter:v}=vo(c,i,r,n);if(_===429&&u(l)){let r=mo(v);if(l._retryCount>=Dt)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:v,retryAfterAsNumber:r}}),Promise.reject(s);let a=l?._retryCount??0,o={...l,_retryCount:a+1},u=v?r*kt:t(o._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:v,calculatedRetryAfter:u}}),await St(u,l,c),e?.request(o)}return Promise.reject(s)};return s},To=`rateLimitResponseInterceptor`,Eo=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if(o(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:To,...i,httpsAgent:void 0,headers:void 0}});else if(o(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:To,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:u(n)},code:bt.RateLimitOrConcurrencyManagerNotInitialized}),r;else if(u(t.provider)&&u(t.accountSecureId)){let t=r?.headers;if(u(t)){let n=fo(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:To,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:To,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:bt.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(xt(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},Do=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Oo=[{onFulfilled:Do,onRejected:null,options:void 0}],ko=[{onFulfilled:null,onRejected:_o},{onFulfilled:null,onRejected:gt}],Ao=[{onFulfilled:Do,onRejected:null,options:void 0},{onFulfilled:wt,onRejected:null,options:void 0}],jo=[{onFulfilled:Eo,onRejected:wo},{onFulfilled:null,onRejected:gt}],Mo=1,No=1e3,Po=0,Fo=59,Io=.8,Lo=500;var Ro=class extends Oe{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=Fo,i=Io,a=Lo){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=Po)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=Po)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/No)),u=Mo/l,d=Math.max(_t,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=u(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(yt.incr,[a,...l],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},Z=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(o(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(u(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let zo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Bo=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?Ho(e,n):Vo(e,n),o(n?.service)||o(n?.organizationId)||s===`test`||o(t)||o(e))return a;let l=Z.getIfReady(Ro)??void 0,d=Z.getIfReady(at)??void 0,f=l?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Ao),h.push(...jo)}let g=po(n);if(o(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:u(a)}}),a;let _=await ht.get(g);if(u(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:d,rateLimitManager:l},y=ft.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ht.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:u(a)},error:t,code:zo.HttpTransportInstanceCreateError}),u(a)?a:Uo()}},Vo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ft.createInstance(n)??Uo()},Ho=(e,t)=>{let n={interceptors:{requestConfigs:Oo,responseConfigs:ko},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ft.createInstance(n)??Uo()},Uo=()=>{let e=m.create({maxBodyLength:1/0});return e};var Wo=class{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;name=`HttpClient`;constructor({transportFactory:e=Bo,getRedisClient:t=Ce,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:i}){let a=20;if(!i?.accountSecureId||i.accountSecureId.length<a||!e||!n)return null;let o=t?r(t):``;return`${i.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#getCachedResponse({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#redisClient||!r||r<=0)return null;let a=this.#generateCacheKey({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#redisClient.getData(a);return o?(this.#logger?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#logger?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#cacheResponse({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#redisClient||!r||r<=0)return!1;let o=this.#generateCacheKey({url:e,payload:t,method:n,context:i});return o?(this.#logger?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#redisClient.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{u(this.#redisClientConfig)&&o(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let g=this.#buildUrlWithQueryParams(t,r),_=this.#normalizeHeaders(e),v=this.#getSafePayload(d,e),y=await this.#getCachedResponse({url:g,payload:v,method:n,cacheTTL:s,context:c});if(y)return{...y,responseTime:new Date};let b=mt.getInstance(),x=u(l)?await b.get(l):null,S=x?.signal,ee=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:c,requestConfig:m,httpsAgentConfig:h}),C=await ee.request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:f,httpAgent:p,signal:S}),w={data:C.data,status:C.status,body:v,method:n,headers:this.#extractAxiosHeaders(C.headers),requestUrl:t,responseType:C?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:g,payload:v,method:n,cacheTTL:s,context:c,response:w}),w}catch(e){let r=e;r.url=b(t),this.#logger?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#mapErrorToHttpException(r);throw u(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!(o(e)||c(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?x.stringify(e):e}#mapErrorToHttpException(e){if(h(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if(o(t)||Object.keys(t).length===0)return e;let n=x.stringify(t);return`${e}?${n}`}};const Go=(e,t,n)=>new Wo({redisClientConfig:e,logger:t,errorMappingFn:n});var Ko=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Go}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const qo=[`get`,`post`,`put`,`delete`,`patch`],Jo={[Re.rPush]:`
|
|
132
132
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
133
133
|
|
|
134
134
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackone/transport",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"author": "StackOne",
|
|
42
42
|
"license": "ISC",
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"jsonpath": "^
|
|
44
|
+
"jsonpath-plus": "^10.3.0",
|
|
45
45
|
"@stackone/expressions": "*",
|
|
46
46
|
"@stackone/redaction": "*",
|
|
47
47
|
"@stackone/logger": "*",
|