@stackone/transport 2.33.1 → 2.33.2

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.cjs CHANGED
@@ -94,7 +94,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
94
94
 
95
95
  redis.call('publish', nextItemKey, nextItem)
96
96
  end
97
- `};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==k)return;let n=this.leaseRegistry.get(e);if(!(0,o.isMissing)(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==A)return;let n=this.setRemovalRegistry.get(e);if(!(0,o.isMissing)(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(D)&&n.includes(O)&&n.includes(k)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(j.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(k,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(A,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=C*5,a){let s=`concurrency:${e}`,c=`queue:${e}`,l=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,u=(0,o.notMissing)(l)?`${s}-${l}`:s,{mainMaxConcurrency:d,subPools:f}=t,p=[{key:s,maxConcurrency:d},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${s}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,u),this.subscribeToSetRemoval(u,c)]),v={requestId:n,targetConcurrencyKey:u,leaseSubscription:g,setRemovalSubscription:_,queueKey:c,acquired:!1},y=!1,b=!1;try{let e=await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]);if((0,o.notMissing)(e)&&e[0])return y=!0,{...v,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let t=(0,o.notMissing)(e)?e[1]:``,r=0,s=i,l=[],isAborted=()=>a?.aborted===!0;for(;s>0&&r<5&&!isAborted();){let e=r>1,t=Math.min(C,s),i=Date.now();b=!0;let f=await this.queueManager?.joinAndWaitTurn(c,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]),!1,t,a);s-=Math.max(Date.now()-i,0);let p=(0,o.notMissing)(f)?f[0]:!1,g=(0,o.notMissing)(f)?f[1]:``;if((0,o.notMissing)(g)&&g!==``&&l.push(g),r++,p)return y=!0,r>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${r} attempts.`,context:{...v,registerAttempts:r,joinCondition:`attempts`,failureMessages:l}}),{...v,joinCondition:`attempts`,acquired:!0};let _=(0,o.exponentialBackoffInMS)(r,100);if(s-=_,s<=0||isAborted())break;await(0,o.delay)(_)}if(r===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...v,registerAttempts:r,joinCondition:e,maxWaitMs:i,optimisticFailureReason:t}}),{...v,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${r} attempts.`,context:{...v,registerAttempts:r,joinCondition:`failed`,failureMessages:l,optimisticFailureReason:t},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}finally{if(!y&&(this.leaseRegistry.delete(buildLeaseKey(u,n)),b))try{await this.queueManager?.remove(c,n)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...v,queueKey:c},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if((0,o.isString)(t)&&(0,o.isString)(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const M={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?M[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??M[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ne=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var N=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},P=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const F=P.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},re={mainRatelimit:25},I=1e3,ie=/^\d+(\.\d+)?$/,L=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},R=`checkConcurrencyInterceptor`,ae=new LogThrottle(L),oe=new LogThrottle(L),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:R,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:R,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let s=(0,d.randomUUID)(),{provider:c,accountSecureId:l}=t,u=n?.rateLimits??re,f=n?.concurrency??ee,p=await i.getDynamicMaxWaitTime(u,f,a.url),m=a._waitDeadlineAt,h=(0,o.isNumber)(m)&&Number.isFinite(m)?m:Date.now()+p*I,remainingBudgetMs=()=>Math.max(h-Date.now(),0),g=`${l}-${c}`,register=async()=>r.registerRequest(g,f,s,a.url,remainingBudgetMs(),a.signal),_=remainingBudgetMs()<=0,v;do{let t=await i.getWaitTime(g,u,a.url);if((0,o.isMissing)(t)){let t=ae.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:R,provider:c,accountSecureId:l,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){v=await register();break}if(remainingBudgetMs()<=0)break;await abortableDelay(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:R,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:p,joinCondition:v?.joinCondition};if(_){let t=oe.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${c} - Account: ${l}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${c} - Account: ${l}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:v,_waitDeadlineAt:h}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*I:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(ie.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):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)/I);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*I:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(a??{}),l=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(l)&&(0,o.notMissing)(s))for(let e of l){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:l,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage((0,o.isObject)(s)?(0,m.JSONPath)({path:f,json:s})[0]:s,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,l),u);return{status:429,retryAfter:c??e}}}return{status:i,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;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`)},z=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p,acquired:m}=c?.requestMetadata??{},h=m!==!1&&(0,o.notMissing)(u)&&(0,o.notMissing)(d);if(!(h&&await i.releaseRequest(u,d))&&h&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:z,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,r,n,t);if(g===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(_);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=_?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},B=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:B,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u,acquired:d}=i?.requestMetadata??{},f=d!==!1&&(0,o.notMissing)(s)&&(0,o.notMissing)(c);if(!(f&&await n.releaseRequest(s,c))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:B,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){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<=0)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<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}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,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.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,o.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,o.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?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.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}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const V=new LogThrottle(6e4),getTransportInstance=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`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...le),m.push(...ue)}let h=generateRequestKey(n);if((0,o.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,o.notMissing)(a)}}),a;let g=await F.get(h);if((0,o.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:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await F.set(h,v),v}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=V.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);(0,o.notMissing)(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}const H=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&H.has(e),toFailureCacheKey=e=>`${e}-error`,U=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&U in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new l.AxiosError(e.message??`Request failed with status code ${e.status}`,l.AxiosError.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[U]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||(0,o.isMissing)(r)||r<=0||!(0,l.isAxiosError)(a)||!isCacheableFailureStatus(a.response?.status))return!1;let s={data:a.response?.data,status:a.response?.status,headers:this.#d(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let u=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${s.status} for key [${u}].`}),this.#a.setData({key:u,value:s,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:s,cacheTTL:c,context:l,traceId:u,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:g}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#y(t,r,i),_=this.#u(e),v=this.#g(d,e),y=await this.#s({url:h,payload:v,method:n,cacheTTL:c,context:l});if(y){if(isCacheableFailureStatus(y.status))throw rebuildCachedFailure(y,n);return{...y,responseTime:new Date}}let b=P.getInstance(),x=((0,o.notMissing)(u)?await b.get(u):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:g})).request({headers:_,url:h,method:n,maxRedirects:a,responseType:s,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#d(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:h,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:v,method:n,cacheTTL:c,context:l,response:C}),C}catch(a){if(isReplayedFailure(a)){let e=this.#_(a);throw(0,o.notMissing)(e)?e:a}let s=a;s.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${s.url}]: ${s.message}.`,error:s}),await this.#l({url:this.#y(t,r,i),payload:this.#g(d,e),method:n,cacheTTL:c,context:l,error:a});let u=this.#_(s);throw(0,o.notMissing)(u)?u:a}}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})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:s,traceId:c,payload:l,httpsAgent:u,httpAgent:d,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#y(t,r,i),h=this.#u(e),g=this.#g(l,e),_=P.getInstance(),v=((0,o.notMissing)(c)?await _.get(c):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:u,httpAgent:d,signal:v});return{status:y.status,headers:this.#d(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#_(r);throw(0,o.notMissing)(i)?i:e}}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#d(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#f(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#p(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#m(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#h(e){return Buffer.isBuffer(e)}#g(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#p(t)||this.#m(e)||this.#h(e)?e:this.#f(t)?g.default.stringify(e):e}#_(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#v(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#y(e,t,n){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let r={},i={},a={},s={},c={};for(let[e,n]of Object.entries(t))if(this.#v(n)){let t=n.arrayFormat,o=n.value;t===`repeat`?i[e]=Array.isArray(o)?o:[o]:t===`brackets`?a[e]=Array.isArray(o)?o:[o]:t===`comma`?s[e]=Array.isArray(o)?o:[o]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(o)?o:[o]):r[e]=o}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(g.default.stringify(r,l)),Object.keys(i).length>0&&u.push(g.default.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(g.default.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(s).length>0&&u.push(g.default.stringify(s,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(g.default.stringify(c,l));let d=u.join(`&`);return(0,o.notMissing)(d)?`${e}?${d}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
97
+ `};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==k)return;let n=this.leaseRegistry.get(e);if(!(0,o.isMissing)(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==A)return;let n=this.setRemovalRegistry.get(e);if(!(0,o.isMissing)(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(D)&&n.includes(O)&&n.includes(k)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(j.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(k,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(A,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=C*5,a){let s=`concurrency:${e}`,c=`queue:${e}`,l=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,u=(0,o.notMissing)(l)?`${s}-${l}`:s,{mainMaxConcurrency:d,subPools:f}=t,p=[{key:s,maxConcurrency:d},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${s}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,u),this.subscribeToSetRemoval(u,c)]),v={requestId:n,targetConcurrencyKey:u,leaseSubscription:g,setRemovalSubscription:_,queueKey:c,acquired:!1},y=!1,b=!1;try{let e=await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]);if((0,o.notMissing)(e)&&e[0])return y=!0,{...v,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let t=(0,o.notMissing)(e)?e[1]:``,r=0,s=i,l=[],isAborted=()=>a?.aborted===!0;for(;s>0&&r<5&&!isAborted();){let e=r>1,t=Math.min(C,s),i=Date.now();b=!0;let f=await this.queueManager?.joinAndWaitTurn(c,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]),!1,t,a);s-=Math.max(Date.now()-i,0);let p=(0,o.notMissing)(f)?f[0]:!1,g=(0,o.notMissing)(f)?f[1]:``;if((0,o.notMissing)(g)&&g!==``&&l.push(g),r++,p)return y=!0,r>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${r} attempts.`,context:{...v,registerAttempts:r,joinCondition:`attempts`,failureMessages:l}}),{...v,joinCondition:`attempts`,acquired:!0};let _=(0,o.exponentialBackoffInMS)(r,100);if(s-=_,s<=0||isAborted())break;await(0,o.delay)(_)}if(r===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...v,registerAttempts:r,joinCondition:e,maxWaitMs:i,optimisticFailureReason:t}}),{...v,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${r} attempts.`,context:{...v,registerAttempts:r,joinCondition:`failed`,failureMessages:l,optimisticFailureReason:t},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}finally{if(!y&&(this.leaseRegistry.delete(buildLeaseKey(u,n)),b))try{await this.queueManager?.remove(c,n)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...v,queueKey:c},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if((0,o.isString)(t)&&(0,o.isString)(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const M={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?M[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??M[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ne=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var N=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet,n=0)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(n>=64)return`[Max Depth Exceeded]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let r=e.map(e=>safeSerialize(e,t,n+1));return t.delete(e),r}let r=e,i={};t.add(r);for(let[e,a]of Object.entries(r))i[e]=safeSerialize(a,t,n+1);return t.delete(r),i},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},P=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const F=P.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},re={mainRatelimit:25},I=1e3,ie=/^\d+(\.\d+)?$/,L=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},R=`checkConcurrencyInterceptor`,ae=new LogThrottle(L),oe=new LogThrottle(L),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:R,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:R,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let s=(0,d.randomUUID)(),{provider:c,accountSecureId:l}=t,u=n?.rateLimits??re,f=n?.concurrency??ee,p=await i.getDynamicMaxWaitTime(u,f,a.url),m=a._waitDeadlineAt,h=(0,o.isNumber)(m)&&Number.isFinite(m)?m:Date.now()+p*I,remainingBudgetMs=()=>Math.max(h-Date.now(),0),g=`${l}-${c}`,register=async()=>r.registerRequest(g,f,s,a.url,remainingBudgetMs(),a.signal),_=remainingBudgetMs()<=0,v;do{let t=await i.getWaitTime(g,u,a.url);if((0,o.isMissing)(t)){let t=ae.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:R,provider:c,accountSecureId:l,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){v=await register();break}if(remainingBudgetMs()<=0)break;await abortableDelay(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:R,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:p,joinCondition:v?.joinCondition};if(_){let t=oe.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${c} - Account: ${l}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${c} - Account: ${l}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:v,_waitDeadlineAt:h}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*I:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(ie.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):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)/I);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*I:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(a??{}),l=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(l)&&(0,o.notMissing)(s))for(let e of l){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:l,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage((0,o.isObject)(s)?(0,m.JSONPath)({path:f,json:s})[0]:s,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,l),u);return{status:429,retryAfter:c??e}}}return{status:i,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;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`)},z=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p,acquired:m}=c?.requestMetadata??{},h=m!==!1&&(0,o.notMissing)(u)&&(0,o.notMissing)(d);if(!(h&&await i.releaseRequest(u,d))&&h&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:z,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,r,n,t);if(g===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(_);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=_?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},B=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:B,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u,acquired:d}=i?.requestMetadata??{},f=d!==!1&&(0,o.notMissing)(s)&&(0,o.notMissing)(c);if(!(f&&await n.releaseRequest(s,c))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:B,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){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<=0)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<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}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,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.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,o.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,o.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?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.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}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const V=new LogThrottle(6e4),getTransportInstance=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`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...le),m.push(...ue)}let h=generateRequestKey(n);if((0,o.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,o.notMissing)(a)}}),a;let g=await F.get(h);if((0,o.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:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await F.set(h,v),v}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=V.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);(0,o.notMissing)(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}const H=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&H.has(e),toFailureCacheKey=e=>`${e}-error`,U=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&U in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new l.AxiosError(e.message??`Request failed with status code ${e.status}`,l.AxiosError.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[U]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||(0,o.isMissing)(r)||r<=0||!(0,l.isAxiosError)(a)||!isCacheableFailureStatus(a.response?.status))return!1;let s={data:a.response?.data,status:a.response?.status,headers:this.#d(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let u=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${s.status} for key [${u}].`}),this.#a.setData({key:u,value:s,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:s,cacheTTL:c,context:l,traceId:u,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:g}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#y(t,r,i),_=this.#u(e),v=this.#g(d,e),y=await this.#s({url:h,payload:v,method:n,cacheTTL:c,context:l});if(y){if(isCacheableFailureStatus(y.status))throw rebuildCachedFailure(y,n);return{...y,responseTime:new Date}}let b=P.getInstance(),x=((0,o.notMissing)(u)?await b.get(u):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:g})).request({headers:_,url:h,method:n,maxRedirects:a,responseType:s,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#d(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:h,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:v,method:n,cacheTTL:c,context:l,response:C}),C}catch(a){if(isReplayedFailure(a)){let e=this.#_(a);throw(0,o.notMissing)(e)?e:a}let s=a;s.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${s.url}]: ${s.message}.`,error:s}),await this.#l({url:this.#y(t,r,i),payload:this.#g(d,e),method:n,cacheTTL:c,context:l,error:a});let u=this.#_(s);throw(0,o.notMissing)(u)?u:a}}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})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:s,traceId:c,payload:l,httpsAgent:u,httpAgent:d,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#y(t,r,i),h=this.#u(e),g=this.#g(l,e),_=P.getInstance(),v=((0,o.notMissing)(c)?await _.get(c):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:u,httpAgent:d,signal:v});return{status:y.status,headers:this.#d(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#_(r);throw(0,o.notMissing)(i)?i:e}}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#d(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#f(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#p(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#m(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#h(e){return Buffer.isBuffer(e)}#g(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#p(t)||this.#m(e)||this.#h(e)?e:this.#f(t)?g.default.stringify(e):e}#_(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#v(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#y(e,t,n){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let r={},i={},a={},s={},c={};for(let[e,n]of Object.entries(t))if(this.#v(n)){let t=n.arrayFormat,o=n.value;t===`repeat`?i[e]=Array.isArray(o)?o:[o]:t===`brackets`?a[e]=Array.isArray(o)?o:[o]:t===`comma`?s[e]=Array.isArray(o)?o:[o]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(o)?o:[o]):r[e]=o}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(g.default.stringify(r,l)),Object.keys(i).length>0&&u.push(g.default.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(g.default.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(s).length>0&&u.push(g.default.stringify(s,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(g.default.stringify(c,l));let d=u.join(`&`);return(0,o.notMissing)(d)?`${e}?${d}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
98
98
  `).replace(/\r\n/g,`
99
99
  `).replace(/\r/g,`
100
100
  `).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
package/dist/index.mjs CHANGED
@@ -94,7 +94,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInM
94
94
 
95
95
  redis.call('publish', nextItemKey, nextItem)
96
96
  end
97
- `};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==R)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==z)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(se)&&n.includes(ce)&&n.includes(R)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(le.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(R,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(z,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=F*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=d(e)?e[1]:``,a=0,c=o,u=[],isAborted=()=>s?.aborted===!0;for(;c>0&&a<5&&!isAborted();){let e=a>1,r=Math.min(F,c),o=Date.now();S=!0;let m=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,r,s);c-=Math.max(Date.now()-o,0);let h=d(m)?m[0]:!1,v=d(m)?m[1]:``;if(d(v)&&v!==``&&u.push(v),a++,h)return x=!0,a>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`attempts`,failureMessages:u}}),{...b,joinCondition:`attempts`,acquired:!0};let y=n(a,100);if(c-=y,c<=0||isAborted())break;await t(y)}if(a===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...b,registerAttempts:a,joinCondition:e,maxWaitMs:o,optimisticFailureReason:r}}),{...b,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`failed`,failureMessages:u,optimisticFailureReason:r},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const B={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=v(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?B[t.targetStatus]??`Unknown error`:String(v(n,e)??B[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},fe=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var V=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new S.Agent(n),l=y.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},H=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const U=H.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},pe={mainRatelimit:25},W=1e3,me=/^\d+(\.\d+)?$/,he=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&ee(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},G=`checkConcurrencyInterceptor`,ge=new LogThrottle(he),_e=new LogThrottle(he),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=T(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??pe,p=n?.concurrency??ue,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*W,remainingBudgetMs=()=>Math.max(g-Date.now(),0),_=`${u}-${l}`,register=async()=>r.registerRequest(_,p,o,a.url,remainingBudgetMs(),a.signal),v=remainingBudgetMs()<=0,y;do{let t=await i.getWaitTime(_,f,a.url);if(s(t)){let t=ge.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${l} - Account: ${u}, proceeding without a limit`,context:{interceptor:G,provider:l,accountSecureId:u,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){y=await register();break}if(remainingBudgetMs()<=0)break;await abortableDelay(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if(s(y)){y=await register();let n={...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:m,joinCondition:y?.joinCondition};if(v){let t=_e.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${l} - Account: ${u}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${l} - Account: ${u}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:y,_waitDeadlineAt:g}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*W:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*W},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=E(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):te(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/W);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(me.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):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)/W);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*W:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:o}=e??{},{retryafter:s}=superNormalizeHeaders(a??{}),c=n?.rateLimits?.mappedRateLimitErrors;if(d(c)&&d(o))for(let e of c){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:c,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage(l(o)?D({path:f,json:o})[0]:o,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,c),u);return{status:429,retryAfter:s??e}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?D({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/W;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`)},K=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:K,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*W:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},q=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:q,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:q,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ve=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ye=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],be=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],xe=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){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<=0)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<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}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=d(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),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.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(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(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?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.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}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const Se=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...be),h.push(...xe)}let g=generateRequestKey(n);if(s(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:d(a)}}),a;let _=await U.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await U.set(g,y),y}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=Se.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:ve,responseConfigs:ye},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=ne(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}const Ce=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Ce.has(e),toFailureCacheKey=e=>`${e}-error`,we=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&we in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new b(e.message??`Request failed with status code ${e.status}`,b.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[we]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||s(r)||r<=0||!x(a)||!isCacheableFailureStatus(a.response?.status))return!1;let o={data:a.response?.data,status:a.response?.status,headers:this.#d(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let l=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${o.status} for key [${l}].`}),this.#a.setData({key:l,value:o,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:c,context:l,traceId:u,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let _=this.#y(t,r,i),v=this.#u(e),y=this.#g(f,e),b=await this.#s({url:_,payload:y,method:n,cacheTTL:c,context:l});if(b){if(isCacheableFailureStatus(b.status))throw rebuildCachedFailure(b,n);return{...b,responseTime:new Date}}let x=H.getInstance(),S=(d(u)?await x.get(u):null)?.signal,C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:v,url:_,method:n,maxRedirects:a,responseType:o,data:y,httpsAgent:p,httpAgent:m,signal:S}),w={data:C.data,status:C.status,body:y,method:n,headers:this.#d(C.headers),requestHeaders:buildSafeRequestHeaders(v),requestUrl:_,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:_,payload:y,method:n,cacheTTL:c,context:l,response:w}),w}catch(a){if(isReplayedFailure(a)){let e=this.#_(a);throw d(e)?e:a}let o=a;o.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`,error:o}),await this.#l({url:this.#y(t,r,i),payload:this.#g(f,e),method:n,cacheTTL:c,context:l,error:a});let s=this.#_(o);throw d(s)?s:a}}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})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:o,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#y(t,r,i),h=this.#u(e),g=this.#g(c,e),_=H.getInstance(),v=(d(s)?await _.get(s):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:l,httpAgent:u,signal:v});return{status:y.status,headers:this.#d(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#_(r);throw d(i)?i:e}}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#d(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#f(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#p(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#m(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#h(e){return Buffer.isBuffer(e)}#g(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#p(t)||this.#m(e)||this.#h(e)?e:this.#f(t)?k.stringify(e):e}#_(e){if(x(e)&&this.#i)return this.#i(e)}#v(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#y(e,t,n){if(s(t)||Object.keys(t).length===0)return e;let r={},i={},a={},o={},c={};for(let[e,n]of Object.entries(t))if(this.#v(n)){let t=n.arrayFormat,s=n.value;t===`repeat`?i[e]=Array.isArray(s)?s:[s]:t===`brackets`?a[e]=Array.isArray(s)?s:[s]:t===`comma`?o[e]=Array.isArray(s)?s:[s]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(s)?s:[s]):r[e]=s}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(k.stringify(r,l)),Object.keys(i).length>0&&u.push(k.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(k.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(k.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(k.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Te=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
97
+ `};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==R)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==z)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(se)&&n.includes(ce)&&n.includes(R)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(le.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(R,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(z,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=F*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=d(e)?e[1]:``,a=0,c=o,u=[],isAborted=()=>s?.aborted===!0;for(;c>0&&a<5&&!isAborted();){let e=a>1,r=Math.min(F,c),o=Date.now();S=!0;let m=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,r,s);c-=Math.max(Date.now()-o,0);let h=d(m)?m[0]:!1,v=d(m)?m[1]:``;if(d(v)&&v!==``&&u.push(v),a++,h)return x=!0,a>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`attempts`,failureMessages:u}}),{...b,joinCondition:`attempts`,acquired:!0};let y=n(a,100);if(c-=y,c<=0||isAborted())break;await t(y)}if(a===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...b,registerAttempts:a,joinCondition:e,maxWaitMs:o,optimisticFailureReason:r}}),{...b,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`failed`,failureMessages:u,optimisticFailureReason:r},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const B={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=v(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?B[t.targetStatus]??`Unknown error`:String(v(n,e)??B[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},fe=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var V=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet,n=0)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(n>=64)return`[Max Depth Exceeded]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let r=e.map(e=>safeSerialize(e,t,n+1));return t.delete(e),r}let r=e,i={};t.add(r);for(let[e,a]of Object.entries(r))i[e]=safeSerialize(a,t,n+1);return t.delete(r),i},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new S.Agent(n),l=y.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},H=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const U=H.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},pe={mainRatelimit:25},W=1e3,me=/^\d+(\.\d+)?$/,he=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&ee(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},G=`checkConcurrencyInterceptor`,ge=new LogThrottle(he),_e=new LogThrottle(he),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=T(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??pe,p=n?.concurrency??ue,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*W,remainingBudgetMs=()=>Math.max(g-Date.now(),0),_=`${u}-${l}`,register=async()=>r.registerRequest(_,p,o,a.url,remainingBudgetMs(),a.signal),v=remainingBudgetMs()<=0,y;do{let t=await i.getWaitTime(_,f,a.url);if(s(t)){let t=ge.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${l} - Account: ${u}, proceeding without a limit`,context:{interceptor:G,provider:l,accountSecureId:u,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){y=await register();break}if(remainingBudgetMs()<=0)break;await abortableDelay(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if(s(y)){y=await register();let n={...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:m,joinCondition:y?.joinCondition};if(v){let t=_e.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${l} - Account: ${u}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${l} - Account: ${u}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:y,_waitDeadlineAt:g}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*W:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*W},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=E(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):te(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/W);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(me.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):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)/W);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*W:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:o}=e??{},{retryafter:s}=superNormalizeHeaders(a??{}),c=n?.rateLimits?.mappedRateLimitErrors;if(d(c)&&d(o))for(let e of c){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:c,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage(l(o)?D({path:f,json:o})[0]:o,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,c),u);return{status:429,retryAfter:s??e}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?D({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/W;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`)},K=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:K,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*W:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},q=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:q,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:q,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ve=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ye=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],be=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],xe=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){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<=0)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<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}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=d(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),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.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(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(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?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.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}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const Se=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...be),h.push(...xe)}let g=generateRequestKey(n);if(s(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:d(a)}}),a;let _=await U.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await U.set(g,y),y}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=Se.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:ve,responseConfigs:ye},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=ne(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}const Ce=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Ce.has(e),toFailureCacheKey=e=>`${e}-error`,we=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&we in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new b(e.message??`Request failed with status code ${e.status}`,b.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[we]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||s(r)||r<=0||!x(a)||!isCacheableFailureStatus(a.response?.status))return!1;let o={data:a.response?.data,status:a.response?.status,headers:this.#d(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let l=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${o.status} for key [${l}].`}),this.#a.setData({key:l,value:o,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:c,context:l,traceId:u,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let _=this.#y(t,r,i),v=this.#u(e),y=this.#g(f,e),b=await this.#s({url:_,payload:y,method:n,cacheTTL:c,context:l});if(b){if(isCacheableFailureStatus(b.status))throw rebuildCachedFailure(b,n);return{...b,responseTime:new Date}}let x=H.getInstance(),S=(d(u)?await x.get(u):null)?.signal,C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:v,url:_,method:n,maxRedirects:a,responseType:o,data:y,httpsAgent:p,httpAgent:m,signal:S}),w={data:C.data,status:C.status,body:y,method:n,headers:this.#d(C.headers),requestHeaders:buildSafeRequestHeaders(v),requestUrl:_,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:_,payload:y,method:n,cacheTTL:c,context:l,response:w}),w}catch(a){if(isReplayedFailure(a)){let e=this.#_(a);throw d(e)?e:a}let o=a;o.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`,error:o}),await this.#l({url:this.#y(t,r,i),payload:this.#g(f,e),method:n,cacheTTL:c,context:l,error:a});let s=this.#_(o);throw d(s)?s:a}}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})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:o,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#y(t,r,i),h=this.#u(e),g=this.#g(c,e),_=H.getInstance(),v=(d(s)?await _.get(s):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:l,httpAgent:u,signal:v});return{status:y.status,headers:this.#d(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#_(r);throw d(i)?i:e}}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#d(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#f(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#p(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#m(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#h(e){return Buffer.isBuffer(e)}#g(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#p(t)||this.#m(e)||this.#h(e)?e:this.#f(t)?k.stringify(e):e}#_(e){if(x(e)&&this.#i)return this.#i(e)}#v(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#y(e,t,n){if(s(t)||Object.keys(t).length===0)return e;let r={},i={},a={},o={},c={};for(let[e,n]of Object.entries(t))if(this.#v(n)){let t=n.arrayFormat,s=n.value;t===`repeat`?i[e]=Array.isArray(s)?s:[s]:t===`brackets`?a[e]=Array.isArray(s)?s:[s]:t===`comma`?o[e]=Array.isArray(s)?s:[s]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(s)?s:[s]):r[e]=s}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(k.stringify(r,l)),Object.keys(i).length>0&&u.push(k.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(k.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(k.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(k.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Te=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
98
98
  `).replace(/\r\n/g,`
99
99
  `).replace(/\r/g,`
100
100
  `).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.33.1",
3
+ "version": "2.33.2",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",