@stackone/transport 2.36.2 → 2.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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!==j)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!==M)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(k)&&n.includes(A)&&n.includes(j)&&(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(ee.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(j,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(M,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=T*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(T,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 P={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)?P[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??P[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().meta({description:`Provider HTTP status code to match.`}),targetStatus:o.z.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:o.z.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});var F=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}},I=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 L=I.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},R={mainRatelimit:25},z=1e3,re=/^\d+(\.\d+)?$/,B=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},V=__name((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))},`abortableDelay`),H=`checkConcurrencyInterceptor`,ie=new LogThrottle(B),ae=new LogThrottle(B),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:H,...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:H,...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??R,f=n?.concurrency??N,p=await i.getDynamicMaxWaitTime(u,f,a.url),m=a._waitDeadlineAt,h=(0,o.isNumber)(m)&&Number.isFinite(m)?m:Date.now()+p*z,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=ie.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:H,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 V(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:H,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:p,joinCondition:v?.joinCondition};if(_){let t=ae.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*z: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*z},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)/z);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(re.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)/z);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*z:(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 V(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)/z;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`)},U=`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))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:U,...c,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(c))return Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:U,...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:U,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*z:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await V(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},W=`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:W,...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:W,...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:W,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:W,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),oe=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],se=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ce=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],le=[{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 ue=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(...ce),m.push(...le)}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 L.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 L.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=ue.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:oe,responseConfigs:se},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 de=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&de.has(e),toFailureCacheKey=e=>`${e}-error`,G=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&G 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,{[G]:!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,timeoutMs:_}){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),v=this.#u(e),y=this.#g(d,e),b=await this.#s({url:h,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=I.getInstance(),S=((0,o.notMissing)(u)?await x.get(u):null)?.signal,C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:g})).request({headers:v,url:h,method:n,maxRedirects:a,responseType:s,data:y,httpsAgent:f,httpAgent:p,signal:S,...(0,o.notMissing)(_)&&{timeout:_}}),w={data:C.data,status:C.status,body:y,method:n,headers:this.#d(C.headers),requestHeaders:buildSafeRequestHeaders(v),requestUrl:h,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:y,method:n,cacheTTL:c,context:l,response:w}),w}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),_=I.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)||typeof e==`string`?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 fe=[`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!==j)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!==M)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(k)&&n.includes(A)&&n.includes(j)&&(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(ee.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(j,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(M,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=T*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(T,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 P={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)?P[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??P[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().meta({description:`Provider HTTP status code to match.`}),targetStatus:o.z.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:o.z.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:o.z.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});var F=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}},I=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 L=I.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},R={mainRatelimit:25},z=1e3,re=/^\d+(\.\d+)?$/,B=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},V=__name((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))},`abortableDelay`),H=`checkConcurrencyInterceptor`,ie=new LogThrottle(B),ae=new LogThrottle(B),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:H,...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:H,...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??R,f=n?.concurrency??N,p=await i.getDynamicMaxWaitTime(u,f,a.url),m=a._waitDeadlineAt,h=(0,o.isNumber)(m)&&Number.isFinite(m)?m:Date.now()+p*z,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=ie.consume(g);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:H,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 V(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:H,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:p,joinCondition:v?.joinCondition};if(_){let t=ae.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*z: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*z},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)/z);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(re.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)/z);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*z:(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 V(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)/z;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`)},U=`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))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:U,...c,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(c))return Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:U,...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:U,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*z:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await V(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},W=`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:W,...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:W,...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:W,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:W,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),oe=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],se=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ce=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],le=[{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 ue=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(...ce),m.push(...le)}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 L.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 L.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=ue.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:oe,responseConfigs:se},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 buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},de=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&de.has(e),toFailureCacheKey=e=>`${e}-error`,G=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&G 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,{[G]:!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,timeoutMs:_,proxyUrl:v}){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),y=this.#u(e),b=this.#g(d,e),x=await this.#s({url:h,payload:b,method:n,cacheTTL:c,context:l});if(x){if(isCacheableFailureStatus(x.status))throw rebuildCachedFailure(x,n);return{...x,responseTime:new Date}}let S=I.getInstance(),C=((0,o.notMissing)(u)?await S.get(u):null)?.signal,w=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:g})).request({headers:y,url:h,method:n,maxRedirects:a,responseType:s,data:b,httpsAgent:f,httpAgent:p,signal:C,...(0,o.notMissing)(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)}}),T={data:w.data,status:w.status,body:b,method:n,headers:this.#d(w.headers),requestHeaders:buildSafeRequestHeaders(y),requestUrl:h,responseType:w?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:b,method:n,cacheTTL:c,context:l,response:T}),T}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,proxyUrl:c}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c})}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,proxyUrl:m}){try{let h=this.#y(t,r,i),g=this.#u(e),_=this.#g(l,e),v=I.getInstance(),y=((0,o.notMissing)(c)?await v.get(c):null)?.signal,b=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p})).request({headers:g,url:h,method:n,maxRedirects:a,responseType:`stream`,data:_,httpsAgent:u,httpAgent:d,signal:y,...m&&{proxy:buildProxyConfig(m)}});return{status:b.status,headers:this.#d(b.headers),stream:b.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)||typeof e==`string`?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 fe=[`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.d.cts CHANGED
@@ -447,7 +447,8 @@ interface IHttpClient {
447
447
  httpAgent,
448
448
  requestConfig,
449
449
  httpsAgentConfig,
450
- timeoutMs
450
+ timeoutMs,
451
+ proxyUrl
451
452
  }: {
452
453
  headers?: HttpHeaders;
453
454
  url: string;
@@ -464,6 +465,7 @@ interface IHttpClient {
464
465
  requestConfig?: RequestConfig;
465
466
  httpsAgentConfig?: https.AgentOptions;
466
467
  timeoutMs?: number;
468
+ proxyUrl?: string;
467
469
  }): Promise<HttpResponse<T>>;
468
470
  get<T>({
469
471
  headers,
@@ -472,7 +474,8 @@ interface IHttpClient {
472
474
  maxRedirects,
473
475
  cacheTTL,
474
476
  context,
475
- requestConfig
477
+ requestConfig,
478
+ proxyUrl
476
479
  }: {
477
480
  headers?: HttpHeaders;
478
481
  url: string;
@@ -481,6 +484,7 @@ interface IHttpClient {
481
484
  cacheTTL?: number;
482
485
  context?: RequestContext;
483
486
  requestConfig?: RequestConfig;
487
+ proxyUrl?: string;
484
488
  }): Promise<HttpResponse<T>>;
485
489
  post<P, T>({
486
490
  headers,
@@ -489,7 +493,8 @@ interface IHttpClient {
489
493
  cacheTTL,
490
494
  context,
491
495
  payload,
492
- requestConfig
496
+ requestConfig,
497
+ proxyUrl
493
498
  }: {
494
499
  headers?: HttpHeaders;
495
500
  url: string;
@@ -498,6 +503,7 @@ interface IHttpClient {
498
503
  context?: RequestContext;
499
504
  payload?: P;
500
505
  requestConfig?: RequestConfig;
506
+ proxyUrl?: string;
501
507
  }): Promise<HttpResponse<T>>;
502
508
  requestStream({
503
509
  headers,
@@ -512,7 +518,8 @@ interface IHttpClient {
512
518
  httpsAgent,
513
519
  httpAgent,
514
520
  requestConfig,
515
- httpsAgentConfig
521
+ httpsAgentConfig,
522
+ proxyUrl
516
523
  }: {
517
524
  headers?: HttpHeaders;
518
525
  url: string;
@@ -527,6 +534,7 @@ interface IHttpClient {
527
534
  httpAgent?: http.Agent;
528
535
  requestConfig?: RequestConfig;
529
536
  httpsAgentConfig?: https.AgentOptions;
537
+ proxyUrl?: string;
530
538
  }): Promise<StreamHttpResponse>;
531
539
  }
532
540
  interface OperationSetting {
@@ -774,7 +782,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
774
782
  httpAgent,
775
783
  requestConfig,
776
784
  httpsAgentConfig,
777
- timeoutMs
785
+ timeoutMs,
786
+ proxyUrl
778
787
  }: {
779
788
  headers?: HttpHeaders;
780
789
  url: string;
@@ -792,6 +801,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
792
801
  requestConfig?: RequestConfig;
793
802
  httpsAgentConfig?: https.AgentOptions;
794
803
  timeoutMs?: number;
804
+ proxyUrl?: string;
795
805
  }): Promise<HttpResponse<T>>;
796
806
  get<T>({
797
807
  headers,
@@ -801,7 +811,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
801
811
  cacheTTL,
802
812
  context,
803
813
  traceId,
804
- requestConfig
814
+ requestConfig,
815
+ proxyUrl
805
816
  }: {
806
817
  headers?: HttpHeaders;
807
818
  url: string;
@@ -811,6 +822,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
811
822
  context?: RequestContext;
812
823
  traceId?: string;
813
824
  requestConfig?: RequestConfig;
825
+ proxyUrl?: string;
814
826
  }): Promise<HttpResponse<T>>;
815
827
  post<P, T>({
816
828
  headers,
@@ -820,7 +832,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
820
832
  context,
821
833
  traceId,
822
834
  payload,
823
- requestConfig
835
+ requestConfig,
836
+ proxyUrl
824
837
  }: {
825
838
  headers?: HttpHeaders;
826
839
  url: string;
@@ -830,6 +843,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
830
843
  traceId?: string;
831
844
  payload?: P;
832
845
  requestConfig?: RequestConfig;
846
+ proxyUrl?: string;
833
847
  }): Promise<HttpResponse<T>>;
834
848
  requestStream({
835
849
  headers,
@@ -844,7 +858,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
844
858
  httpsAgent,
845
859
  httpAgent,
846
860
  requestConfig,
847
- httpsAgentConfig
861
+ httpsAgentConfig,
862
+ proxyUrl
848
863
  }: {
849
864
  headers?: HttpHeaders;
850
865
  url: string;
@@ -859,6 +874,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
859
874
  httpAgent?: http.Agent;
860
875
  requestConfig?: RequestConfig;
861
876
  httpsAgentConfig?: https.AgentOptions;
877
+ proxyUrl?: string;
862
878
  }): Promise<StreamHttpResponse>;
863
879
  }
864
880
  //#endregion
package/dist/index.d.mts CHANGED
@@ -446,7 +446,8 @@ interface IHttpClient {
446
446
  httpAgent,
447
447
  requestConfig,
448
448
  httpsAgentConfig,
449
- timeoutMs
449
+ timeoutMs,
450
+ proxyUrl
450
451
  }: {
451
452
  headers?: HttpHeaders;
452
453
  url: string;
@@ -463,6 +464,7 @@ interface IHttpClient {
463
464
  requestConfig?: RequestConfig;
464
465
  httpsAgentConfig?: https.AgentOptions;
465
466
  timeoutMs?: number;
467
+ proxyUrl?: string;
466
468
  }): Promise<HttpResponse<T>>;
467
469
  get<T>({
468
470
  headers,
@@ -471,7 +473,8 @@ interface IHttpClient {
471
473
  maxRedirects,
472
474
  cacheTTL,
473
475
  context,
474
- requestConfig
476
+ requestConfig,
477
+ proxyUrl
475
478
  }: {
476
479
  headers?: HttpHeaders;
477
480
  url: string;
@@ -480,6 +483,7 @@ interface IHttpClient {
480
483
  cacheTTL?: number;
481
484
  context?: RequestContext;
482
485
  requestConfig?: RequestConfig;
486
+ proxyUrl?: string;
483
487
  }): Promise<HttpResponse<T>>;
484
488
  post<P, T>({
485
489
  headers,
@@ -488,7 +492,8 @@ interface IHttpClient {
488
492
  cacheTTL,
489
493
  context,
490
494
  payload,
491
- requestConfig
495
+ requestConfig,
496
+ proxyUrl
492
497
  }: {
493
498
  headers?: HttpHeaders;
494
499
  url: string;
@@ -497,6 +502,7 @@ interface IHttpClient {
497
502
  context?: RequestContext;
498
503
  payload?: P;
499
504
  requestConfig?: RequestConfig;
505
+ proxyUrl?: string;
500
506
  }): Promise<HttpResponse<T>>;
501
507
  requestStream({
502
508
  headers,
@@ -511,7 +517,8 @@ interface IHttpClient {
511
517
  httpsAgent,
512
518
  httpAgent,
513
519
  requestConfig,
514
- httpsAgentConfig
520
+ httpsAgentConfig,
521
+ proxyUrl
515
522
  }: {
516
523
  headers?: HttpHeaders;
517
524
  url: string;
@@ -526,6 +533,7 @@ interface IHttpClient {
526
533
  httpAgent?: http.Agent;
527
534
  requestConfig?: RequestConfig;
528
535
  httpsAgentConfig?: https.AgentOptions;
536
+ proxyUrl?: string;
529
537
  }): Promise<StreamHttpResponse>;
530
538
  }
531
539
  interface OperationSetting {
@@ -773,7 +781,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
773
781
  httpAgent,
774
782
  requestConfig,
775
783
  httpsAgentConfig,
776
- timeoutMs
784
+ timeoutMs,
785
+ proxyUrl
777
786
  }: {
778
787
  headers?: HttpHeaders;
779
788
  url: string;
@@ -791,6 +800,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
791
800
  requestConfig?: RequestConfig;
792
801
  httpsAgentConfig?: https.AgentOptions;
793
802
  timeoutMs?: number;
803
+ proxyUrl?: string;
794
804
  }): Promise<HttpResponse<T>>;
795
805
  get<T>({
796
806
  headers,
@@ -800,7 +810,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
800
810
  cacheTTL,
801
811
  context,
802
812
  traceId,
803
- requestConfig
813
+ requestConfig,
814
+ proxyUrl
804
815
  }: {
805
816
  headers?: HttpHeaders;
806
817
  url: string;
@@ -810,6 +821,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
810
821
  context?: RequestContext;
811
822
  traceId?: string;
812
823
  requestConfig?: RequestConfig;
824
+ proxyUrl?: string;
813
825
  }): Promise<HttpResponse<T>>;
814
826
  post<P, T>({
815
827
  headers,
@@ -819,7 +831,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
819
831
  context,
820
832
  traceId,
821
833
  payload,
822
- requestConfig
834
+ requestConfig,
835
+ proxyUrl
823
836
  }: {
824
837
  headers?: HttpHeaders;
825
838
  url: string;
@@ -829,6 +842,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
829
842
  traceId?: string;
830
843
  payload?: P;
831
844
  requestConfig?: RequestConfig;
845
+ proxyUrl?: string;
832
846
  }): Promise<HttpResponse<T>>;
833
847
  requestStream({
834
848
  headers,
@@ -843,7 +857,8 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
843
857
  httpsAgent,
844
858
  httpAgent,
845
859
  requestConfig,
846
- httpsAgentConfig
860
+ httpsAgentConfig,
861
+ proxyUrl
847
862
  }: {
848
863
  headers?: HttpHeaders;
849
864
  url: string;
@@ -858,6 +873,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
858
873
  httpAgent?: http.Agent;
859
874
  requestConfig?: RequestConfig;
860
875
  httpsAgentConfig?: https.AgentOptions;
876
+ proxyUrl?: string;
861
877
  }): Promise<StreamHttpResponse>;
862
878
  }
863
879
  //#endregion
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{AxiosError as b,isAxiosError as x}from"axios";import S from"node:https";import{createHash as C,createHmac as w,randomUUID as T}from"crypto";import{clearTimeout as ee}from"node:timers";import{hasNumericValue as E,isString as te}from"mathjs";import{JSONPath as D}from"jsonpath-plus";import{redactFields as ne,redactUrl as O}from"@stackone/redaction";import k from"qs";import{Client as re,SdkHttpError as ie,StreamableHTTPClientTransport as ae,UnauthorizedError as oe,discoverAuthorizationServerMetadata as se,discoverOAuthProtectedResourceMetadata as ce,extractWWWAuthenticateParams as le}from"@modelcontextprotocol/client";import{randomUUID as ue}from"node:crypto";import{XMLBuilder as de,XMLParser as fe,XMLValidator as A}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const j=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if(s(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*j,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*j:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*j;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*j),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return s(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if(s(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.defaultExecutorMethodDispose=async(e,t)=>{d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const pe=1e4,me=6e4,he=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&he.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await ge.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var ge=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:s=pe,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c,h,p.#t)?p:(p.#t?.error({message:`Redis client did not connect within its ${c}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return d(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>d(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#a())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#a())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#a())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#a())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#a())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#i(e,t,n){if(!this.#a())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#a())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#a())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#a()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#a(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#a())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#a())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#a())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,u(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#r(n)}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#a())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,this.#r(t)]))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#a())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t,n,r)=>{let i=Promise.resolve(e.connect());i.catch(()=>void 0);let a=i.then(()=>!0),o=0,s=0;for(;o<t;){let e=Math.min(1e3,t-o),i=Date.now(),c,l=new Promise(t=>{c=setTimeout(()=>t(!1),e)}),u;try{u=await Promise.race([a,l])}finally{clearTimeout(c)}if(u)return!0;o+=e;let d=Date.now()-i-e;d<=250||(s+=d,r?.debug({message:`Redis connect budget did not advance for ${d}ms because the runtime was suspended; only executed time is charged against the ${t}ms budget`,category:n,context:{budgetMs:t,sliceMs:e,overrunMs:d,suspendedMs:s,chargedMs:o}}))}return!1},teardownUnusableClient=async e=>{e.removeAllListeners(),e.on(`error`,()=>void 0);try{await e.disconnect()}catch{}},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(pe))=>{let r=new LogThrottle(me);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(me)}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),null}let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const M=15e3,_e=15e3,N=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:N,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:_e,truncateThreshold:N,truncationPercentage:1},{instantiator:this.name,evictionFrequency:_e,truncateThreshold:N,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=M,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const P=`__keyevent@0__:`,F=`${P}set`,I=`${P}expire`,L=`${P}expired`,R=`${P}srem`,ve=[F,I,L],z={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,ye={tryConcurrency:`
1
+ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{AxiosError as b,isAxiosError as x}from"axios";import S from"node:https";import{createHash as C,createHmac as w,randomUUID as T}from"crypto";import{clearTimeout as E}from"node:timers";import{hasNumericValue as D,isString as ee}from"mathjs";import{JSONPath as O}from"jsonpath-plus";import{redactFields as te,redactUrl as k}from"@stackone/redaction";import A from"qs";import{Client as ne,SdkHttpError as re,StreamableHTTPClientTransport as ie,UnauthorizedError as ae,discoverAuthorizationServerMetadata as oe,discoverOAuthProtectedResourceMetadata as se,extractWWWAuthenticateParams as ce}from"@modelcontextprotocol/client";import{randomUUID as le}from"node:crypto";import{XMLBuilder as ue,XMLParser as de,XMLValidator as j}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const M=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if(s(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*M,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*M:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*M;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*M),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return s(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if(s(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.defaultExecutorMethodDispose=async(e,t)=>{d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const fe=1e4,pe=6e4,me=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&me.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await he.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var he=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:s=fe,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c,h,p.#t)?p:(p.#t?.error({message:`Redis client did not connect within its ${c}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return d(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>d(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#a())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#a())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#a())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#a())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#a())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#i(e,t,n){if(!this.#a())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#a())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#a())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#a()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#a(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#a())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#a())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#a())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,u(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#r(n)}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#a())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,this.#r(t)]))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#a())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t,n,r)=>{let i=Promise.resolve(e.connect());i.catch(()=>void 0);let a=i.then(()=>!0),o=0,s=0;for(;o<t;){let e=Math.min(1e3,t-o),i=Date.now(),c,l=new Promise(t=>{c=setTimeout(()=>t(!1),e)}),u;try{u=await Promise.race([a,l])}finally{clearTimeout(c)}if(u)return!0;o+=e;let d=Date.now()-i-e;d<=250||(s+=d,r?.debug({message:`Redis connect budget did not advance for ${d}ms because the runtime was suspended; only executed time is charged against the ${t}ms budget`,category:n,context:{budgetMs:t,sliceMs:e,overrunMs:d,suspendedMs:s,chargedMs:o}}))}return!1},teardownUnusableClient=async e=>{e.removeAllListeners(),e.on(`error`,()=>void 0);try{await e.disconnect()}catch{}},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(fe))=>{let r=new LogThrottle(pe);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(pe)}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),null}let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const N=15e3,ge=15e3,P=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:P,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ge,truncateThreshold:P,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ge,truncateThreshold:P,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=N,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const F=`__keyevent@0__:`,I=`${F}set`,L=`${F}expire`,R=`${F}expired`,z=`${F}srem`,_e=[I,L,R],ve={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,ye={tryConcurrency:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
@@ -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!==L)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!==R)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(F)&&n.includes(I)&&n.includes(L)&&(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(ve.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(L,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(R,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=M*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(M,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},be=p({receivedStatus:f.number().meta({description:`Provider HTTP status code to match.`}),targetStatus:f.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:f.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:f.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});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 xe=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},Se={mainRatelimit:25},U=1e3,Ce=/^\d+(\.\d+)?$/,we=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},W=e((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))},`abortableDelay`),G=`checkConcurrencyInterceptor`,Te=new LogThrottle(we),Ee=new LogThrottle(we),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??Se,p=n?.concurrency??z,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*U,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=Te.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 W(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=Ee.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*U: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*U},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)/U);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Ce.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)/U);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*U:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await W(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)/U;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))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(l))return 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*U:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await W(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),De=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],Oe=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ke=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],Ae=[{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 je=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(...ke),h.push(...Ae)}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 xe.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 xe.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=je.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:De,responseConfigs:Oe},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 Me=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Me.has(e),toFailureCacheKey=e=>`${e}-error`,Ne=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Ne 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,{[Ne]:!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,timeoutMs:_}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let v=this.#y(t,r,i),y=this.#u(e),b=this.#g(f,e),x=await this.#s({url:v,payload:b,method:n,cacheTTL:c,context:l});if(x){if(isCacheableFailureStatus(x.status))throw rebuildCachedFailure(x,n);return{...x,responseTime:new Date}}let S=H.getInstance(),C=(d(u)?await S.get(u):null)?.signal,w=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:y,url:v,method:n,maxRedirects:a,responseType:o,data:b,httpsAgent:p,httpAgent:m,signal:C,...d(_)&&{timeout:_}}),T={data:w.data,status:w.status,body:b,method:n,headers:this.#d(w.headers),requestHeaders:buildSafeRequestHeaders(y),requestUrl:v,responseType:w?.config?.responseType,responseTime:new Date};return await this.#c({url:v,payload:b,method:n,cacheTTL:c,context:l,response:T}),T}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)||typeof e==`string`?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 Pe=[`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(I)&&n.includes(L)&&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(_e.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=N*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(N,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},be=p({receivedStatus:f.number().meta({description:`Provider HTTP status code to match.`}),targetStatus:f.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:f.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:f.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});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 xe=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},Se={mainRatelimit:25},U=1e3,Ce=/^\d+(\.\d+)?$/,we=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},W=e((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&&E(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))},`abortableDelay`),G=`checkConcurrencyInterceptor`,Te=new LogThrottle(we),Ee=new LogThrottle(we),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??Se,p=n?.concurrency??ve,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*U,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=Te.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 W(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=Ee.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*U: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*U},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]=D(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):ee(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)/U);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Ce.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)/U);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*U:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await W(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)?O({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)?O({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)/U;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))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(l))return 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*U:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await W(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),De=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],Oe=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ke=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],Ae=[{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 je=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(...ke),h.push(...Ae)}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 xe.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 xe.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=je.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:De,responseConfigs:Oe},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=te(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 buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},Me=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Me.has(e),toFailureCacheKey=e=>`${e}-error`,Ne=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Ne 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,{[Ne]:!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,timeoutMs:_,proxyUrl:v}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let y=this.#y(t,r,i),b=this.#u(e),x=this.#g(f,e),S=await this.#s({url:y,payload:x,method:n,cacheTTL:c,context:l});if(S){if(isCacheableFailureStatus(S.status))throw rebuildCachedFailure(S,n);return{...S,responseTime:new Date}}let C=H.getInstance(),w=(d(u)?await C.get(u):null)?.signal,T=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:b,url:y,method:n,maxRedirects:a,responseType:o,data:x,httpsAgent:p,httpAgent:m,signal:w,...d(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)}}),E={data:T.data,status:T.status,body:x,method:n,headers:this.#d(T.headers),requestHeaders:buildSafeRequestHeaders(b),requestUrl:y,responseType:T?.config?.responseType,responseTime:new Date};return await this.#c({url:y,payload:x,method:n,cacheTTL:c,context:l,response:E}),E}catch(a){if(isReplayedFailure(a)){let e=this.#_(a);throw d(e)?e:a}let o=a;o.url=k(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,proxyUrl:c}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c})}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,proxyUrl:m}){try{let h=this.#y(t,r,i),g=this.#u(e),_=this.#g(c,e),v=H.getInstance(),y=(d(s)?await v.get(s):null)?.signal,b=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:g,url:h,method:n,maxRedirects:a,responseType:`stream`,data:_,httpsAgent:l,httpAgent:u,signal:y,...m&&{proxy:buildProxyConfig(m)}});return{status:b.status,headers:this.#d(b.headers),stream:b.data,requestUrl:t}}catch(e){let r=e;r.url=k(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)||typeof e==`string`?e:this.#f(t)?A.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(A.stringify(r,l)),Object.keys(i).length>0&&u.push(A.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(A.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(A.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(A.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 Pe=[`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
@@ -202,8 +202,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
202
202
  -- open with a warning, so returning nil here would report the ordinary un-throttled path as
203
203
  -- an outage. nil is reserved for the client genuinely being unavailable.
204
204
  return 0
205
- `};let J=null,Y=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],o=await acquireSharedCacheClient(a,t,n);if(s(o))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:o,scripts:Fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:Ie,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:ye,logger:n,additionalArgs:e}),d=[{name:`ConcurrencyManager`,ready:u.isReady()},{name:`QueueManager`,ready:c.isReady()},{name:`RateLimitManager`,ready:l.isReady()}],f=d.filter(e=>!e.ready);if(f.length>0){let e=f.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:d.map(e=>e.name)}}),{concurrencyManager:u,queueManager:c,rateLimitManager:l}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),closeAndResetManagers(n),await releaseSharedCacheClient(n),e}},acquireSharedCacheClient=async(e,t,n)=>{if(d(J))return J;Y??=e(t,n,`TransportSystem`);try{return J=await Y??null,J}finally{Y=null}},releaseSharedCacheClient=async e=>{let t=J;if(J=null,Y=null,!s(t))try{await t.close?.()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing the shared transport Redis client`,code:`TRANSPORT_CLIENT_CLOSE_ERROR`,error:t})}},closeAndResetManagers=e=>{let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);for(let[i,a]of[[`ConcurrencyManager`,t],[`QueueManager`,n],[`RateLimitManager`,r]])try{a?.close()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing ${i}`,code:`TRANSPORT_MANAGER_CLOSE_ERROR`,error:t})}SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager)},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`}),closeAndResetManagers(e),releaseSharedCacheClient(e),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},abortReason=e=>e.reason??new DOMException(`The operation was aborted`,`AbortError`),abortableDelay=(e,t)=>t?.aborted?Promise.reject(abortReason(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e),onAbort=()=>{clearTimeout(i),r(abortReason(t))};t?.addEventListener(`abort`,onAbort,{once:!0})}),Le=e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=Le,{maxRetries:t=5,delay:r=abortableDelay}={})=>{let fetchWithRetry=async(i,a,o)=>{let s=await e(i,a);if(s.status!==429||o>=t)return s;let c=s.headers.get(`retry-after`),l=o+1,u=c?getRetryAfterWaitTime(c)*U:n(l);return await s.body?.cancel().catch(()=>void 0),await r(u,a?.signal),fetchWithRetry(i,a,l)};return(e,t)=>fetchWithRetry(e,t,0)},defaultBaseFetch=(e,t)=>fetch(e,t),createThrottledFetch=(e=defaultBaseFetch,{requestConfig:t,context:n,getManagers:r=getTransportManagers,delay:i=abortableDelay}={})=>async(a,o)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if(s(c)||s(l)||s(u))return e(a,o);let{rateLimitManager:f,concurrencyManager:p}=c,m=t?.rateLimits??Se,h=t?.concurrency??z,g=`${u}-${l}`,_=a.toString(),v=f.getDynamicMaxWaitTime(m,h,_),y=Date.now()+v*U,remainingBudgetMs=()=>Math.max(y-Date.now(),0),registerRequest=()=>p.registerRequest(g,h,ue(),_,remainingBudgetMs(),o?.signal??void 0),acquireSlot=async()=>{let e=await f.getWaitTime(g,m,_)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),o?.signal),acquireSlot())},b=await acquireSlot();try{return await e(a,o)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=b??{};n!==!1&&d(e)&&d(t)&&await p.releaseRequest(e,t).catch(()=>void 0)}},Re={name:`stackone-connect`,version:`1.0.0`},ze={mode:`auto`},Be={createClient:(e,t)=>new re(e,t),createTransport:(e,t)=>new ae(e,t)};var McpClient=class{constructor(e,t=Be){this.config=e,this.sdk=t}async callTool({name:e,arguments:t}){let{content:n,structuredContent:r,isError:i}=await(await this.getConnectedClient()).callTool({name:e,arguments:t??{}},this.buildRequestOptions());return{content:n??[],structuredContent:r,isError:i===!0}}async listTools(e){let t=await(await this.getConnectedClient()).listTools(e?.cursor?{cursor:e.cursor}:void 0,this.buildRequestOptions());return{tools:t.tools,nextCursor:t.nextCursor}}async getServerInfo(){let e=await this.getConnectedClient(),t=e.getServerVersion();return{name:t?.name,title:t?.title,version:t?.version,description:t?.description,websiteUrl:t?.websiteUrl,instructions:e.getInstructions(),iconUrl:this.resolveIconUrl(t?.icons)}}resolveIconUrl(e){if(!e?.length)return;let t=e.find(e=>e.theme!==`dark`)??e[0];try{return new URL(t.src,this.config.serverUrl).toString()}catch{return}}async close(){let e=this.connectedClient;this.connectedClient=void 0,e&&await(await e.catch(()=>void 0))?.close()}getConnectedClient(){return this.connectedClient??=this.connect(),this.connectedClient.catch(e=>{throw this.connectedClient=void 0,e})}async connect(){let{serverUrl:e,headers:t,clientInfo:n,requestConfig:r,context:i}=this.config,a=this.sdk.createClient(n??Re,{versionNegotiation:ze}),o=this.sdk.createTransport(new URL(e),{requestInit:t?{headers:t}:void 0,fetch:createRetryingFetch(createThrottledFetch(void 0,{requestConfig:r,context:i}))});return await a.connect(o,this.buildRequestOptions()),a}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const fetchAuthorizationChallenge=async e=>{let t=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`ping`})});if(await t.body?.cancel().catch(()=>void 0),t.status!==401)return;let{resourceMetadataUrl:n,scope:r}=le(t);return{resourceMetadataUrl:n?.toString(),scope:r}},Ve={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>ce(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>se(e)},isAuthorizationFailure=e=>e instanceof oe||e instanceof ie&&e.status===401,probeProtectedServer=async(e,t)=>{let n=await t.fetchAuthorizationChallenge(e).catch(()=>void 0),r=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!r&&!n?.resourceMetadataUrl)return{requiresAuthorization:!0};let i=r?.authorization_servers,a=i?.[0]?await t.discoverAuthorizationServer(i[0]).catch(()=>void 0):void 0,o=r?.resource_name||r?.resource_documentation?{name:r.resource_name,documentationUrl:r.resource_documentation}:void 0;return{requiresAuthorization:!0,oauth:{scopes:r?.scopes_supported??n?.scope?.split(` `)??a?.scopes_supported,authorizationServers:i,dynamicRegistration:d(a)?d(a.registration_endpoint):void 0,resourceMetadataUrl:n?.resourceMetadataUrl},...o?{resource:o}:{}}},probeMcpServer=async(e,t=Ve)=>{let n=t.createClient(e);try{return await n.listTools(),{requiresAuthorization:!1,server:await n.getServerInfo().catch(()=>void 0)}}catch(n){if(!isAuthorizationFailure(n))throw n;return probeProtectedServer(e,t)}finally{await n.close().catch(()=>void 0)}},He=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),X=e(e=>Array.isArray(e)?e:[e],`toStringArray`),isNullish=e=>e==null,toQueryValue=e=>Array.isArray(e)?e.filter(e=>!isNullish(e)).map(String):String(e),hasValue=e=>e.in===`body`||!isNullish(e.value),mergeQueryValues=(e,t,n)=>{let r=X(t);if(He(e))return{value:[...X(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...X(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.filter(hasValue).reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.inline)e.body=t.value;else if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),Ue=[`query`,`body`,`headers`],We=[`repeat`,`brackets`,`comma`,`stringify`],Ge={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},Ke=new de(Ge),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return Ke.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199,qe=[`arraybuffer`,`blob`,`document`,`text`];let Je;const getXmlParser=()=>(Je??=new fe({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Je);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f,context:p,cacheTTL:m,timeoutMs:h}){let g,_=o;if(isXmlContentType(r))if(typeof o==`string`)_=o;else if(Array.isArray(o))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else o!=null&&(_=serializeBodyToXml(o));try{g=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:_,requestConfig:l,httpsAgent:u,responseType:f,context:p,cacheTTL:m,timeoutMs:h})}catch(e){if(s(e?.response))throw e;g=e.response}if(typeof g.data==`string`&&/\S/.test(g.data)&&g.headers&&isXmlContentType(g.headers)&&(!f||!qe.includes(f))){let e=A.validate(g.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);g={...g,data:getXmlParser().parse(g.data)}}let v=translateCustomError(g,c,d);if(isFailedStatusCode(v?.status))throw new V(v,v.message);return v}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,credentials:u,context:d,cacheTTL:f}){let p;if(p=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?Z.build(l.envelope):await buildEnvelope(o,l),A.validate(p,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let m,h={"Content-Type":`application/xml`,...r};l?.soapAction&&(h.SOAPAction=l.soapAction);try{m=await e?.request({method:n,url:t,headers:h,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:p,requestConfig:l,context:d,cacheTTL:f})}catch(e){if(s(e?.response))throw e;m=e.response}let g=Ye.parse(m.data),_=g.Envelope||g,v=_.Body||_,y=v.Fault;if(y)throw new V({...m,status:500,data:y,message:y.faultstring??y.faultcode??`SOAP Fault`},y.faultstring??`SOAP Fault occurred`);m.data=v;let b=translateCustomError(m,c,u);if(isFailedStatusCode(b?.status))throw new V(b,b.message);return b}};const Z=new de(Ge),Ye=new fe({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Z.build(t.envelope);if(A.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Z.build(n);if(A.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>w(`sha256`,e).update(t).digest(),hash=e=>C(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Q=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Xe=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return Q(decodeURIComponent(e))}catch{return Q(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=Xe(e,n);return i===0?Xe(t,r):i});let h=m.map(([e,t])=>`${Q(e)}=${Q(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=C(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let b=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),x=g.length>0&&!b,S;x&&(S=_.toString(`base64`),y[`x-amz-checksum-sha256`]=S);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),ee=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),E=T.join(`;`),te=[e.method.toUpperCase(),p,h,ee,E,v].join(`
206
- `),D=`${d}/${l}/${s}/aws4_request`,ne=[`AWS4-HMAC-SHA256`,u,D,hash(te)].join(`
207
- `),O={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${D}, SignedHeaders=${E}, Signature=${w(`sha256`,getSigningKey(i,d,l,s)).update(ne).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(O[`x-amz-security-token`]=a),S!==void 0&&(O[`x-amz-checksum-sha256`]=S),O},Ze=[`sha256`,`sha512`],isValidAlgorithm=e=>Ze.includes(e),hashPayload=e=>C(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,d=new Date().toISOString(),f=new URL(e.url),p=[];for(let[e,t]of f.searchParams.entries())p.push([e,t]);p.push(...flattenQueryParams(e.query)),p.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let m=p.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),h=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),g=[d,e.method.toUpperCase(),f.pathname,m,h].join(`
205
+ `};let J=null,Y=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],o=await acquireSharedCacheClient(a,t,n);if(s(o))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:o,scripts:Fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:Ie,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:ye,logger:n,additionalArgs:e}),d=[{name:`ConcurrencyManager`,ready:u.isReady()},{name:`QueueManager`,ready:c.isReady()},{name:`RateLimitManager`,ready:l.isReady()}],f=d.filter(e=>!e.ready);if(f.length>0){let e=f.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:d.map(e=>e.name)}}),{concurrencyManager:u,queueManager:c,rateLimitManager:l}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),closeAndResetManagers(n),await releaseSharedCacheClient(n),e}},acquireSharedCacheClient=async(e,t,n)=>{if(d(J))return J;Y??=e(t,n,`TransportSystem`);try{return J=await Y??null,J}finally{Y=null}},releaseSharedCacheClient=async e=>{let t=J;if(J=null,Y=null,!s(t))try{await t.close?.()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing the shared transport Redis client`,code:`TRANSPORT_CLIENT_CLOSE_ERROR`,error:t})}},closeAndResetManagers=e=>{let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);for(let[i,a]of[[`ConcurrencyManager`,t],[`QueueManager`,n],[`RateLimitManager`,r]])try{a?.close()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing ${i}`,code:`TRANSPORT_MANAGER_CLOSE_ERROR`,error:t})}SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager)},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`}),closeAndResetManagers(e),releaseSharedCacheClient(e),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},abortReason=e=>e.reason??new DOMException(`The operation was aborted`,`AbortError`),abortableDelay=(e,t)=>t?.aborted?Promise.reject(abortReason(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e),onAbort=()=>{clearTimeout(i),r(abortReason(t))};t?.addEventListener(`abort`,onAbort,{once:!0})}),Le=e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=Le,{maxRetries:t=5,delay:r=abortableDelay}={})=>{let fetchWithRetry=async(i,a,o)=>{let s=await e(i,a);if(s.status!==429||o>=t)return s;let c=s.headers.get(`retry-after`),l=o+1,u=c?getRetryAfterWaitTime(c)*U:n(l);return await s.body?.cancel().catch(()=>void 0),await r(u,a?.signal),fetchWithRetry(i,a,l)};return(e,t)=>fetchWithRetry(e,t,0)},defaultBaseFetch=(e,t)=>fetch(e,t),createThrottledFetch=(e=defaultBaseFetch,{requestConfig:t,context:n,getManagers:r=getTransportManagers,delay:i=abortableDelay}={})=>async(a,o)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if(s(c)||s(l)||s(u))return e(a,o);let{rateLimitManager:f,concurrencyManager:p}=c,m=t?.rateLimits??Se,h=t?.concurrency??ve,g=`${u}-${l}`,_=a.toString(),v=f.getDynamicMaxWaitTime(m,h,_),y=Date.now()+v*U,remainingBudgetMs=()=>Math.max(y-Date.now(),0),registerRequest=()=>p.registerRequest(g,h,le(),_,remainingBudgetMs(),o?.signal??void 0),acquireSlot=async()=>{let e=await f.getWaitTime(g,m,_)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),o?.signal),acquireSlot())},b=await acquireSlot();try{return await e(a,o)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=b??{};n!==!1&&d(e)&&d(t)&&await p.releaseRequest(e,t).catch(()=>void 0)}},Re={name:`stackone-connect`,version:`1.0.0`},ze={mode:`auto`},Be={createClient:(e,t)=>new ne(e,t),createTransport:(e,t)=>new ie(e,t)};var McpClient=class{constructor(e,t=Be){this.config=e,this.sdk=t}async callTool({name:e,arguments:t}){let{content:n,structuredContent:r,isError:i}=await(await this.getConnectedClient()).callTool({name:e,arguments:t??{}},this.buildRequestOptions());return{content:n??[],structuredContent:r,isError:i===!0}}async listTools(e){let t=await(await this.getConnectedClient()).listTools(e?.cursor?{cursor:e.cursor}:void 0,this.buildRequestOptions());return{tools:t.tools,nextCursor:t.nextCursor}}async getServerInfo(){let e=await this.getConnectedClient(),t=e.getServerVersion();return{name:t?.name,title:t?.title,version:t?.version,description:t?.description,websiteUrl:t?.websiteUrl,instructions:e.getInstructions(),iconUrl:this.resolveIconUrl(t?.icons)}}resolveIconUrl(e){if(!e?.length)return;let t=e.find(e=>e.theme!==`dark`)??e[0];try{return new URL(t.src,this.config.serverUrl).toString()}catch{return}}async close(){let e=this.connectedClient;this.connectedClient=void 0,e&&await(await e.catch(()=>void 0))?.close()}getConnectedClient(){return this.connectedClient??=this.connect(),this.connectedClient.catch(e=>{throw this.connectedClient=void 0,e})}async connect(){let{serverUrl:e,headers:t,clientInfo:n,requestConfig:r,context:i}=this.config,a=this.sdk.createClient(n??Re,{versionNegotiation:ze}),o=this.sdk.createTransport(new URL(e),{requestInit:t?{headers:t}:void 0,fetch:createRetryingFetch(createThrottledFetch(void 0,{requestConfig:r,context:i}))});return await a.connect(o,this.buildRequestOptions()),a}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const fetchAuthorizationChallenge=async e=>{let t=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`ping`})});if(await t.body?.cancel().catch(()=>void 0),t.status!==401)return;let{resourceMetadataUrl:n,scope:r}=ce(t);return{resourceMetadataUrl:n?.toString(),scope:r}},Ve={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>se(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>oe(e)},isAuthorizationFailure=e=>e instanceof ae||e instanceof re&&e.status===401,probeProtectedServer=async(e,t)=>{let n=await t.fetchAuthorizationChallenge(e).catch(()=>void 0),r=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!r&&!n?.resourceMetadataUrl)return{requiresAuthorization:!0};let i=r?.authorization_servers,a=i?.[0]?await t.discoverAuthorizationServer(i[0]).catch(()=>void 0):void 0,o=r?.resource_name||r?.resource_documentation?{name:r.resource_name,documentationUrl:r.resource_documentation}:void 0;return{requiresAuthorization:!0,oauth:{scopes:r?.scopes_supported??n?.scope?.split(` `)??a?.scopes_supported,authorizationServers:i,dynamicRegistration:d(a)?d(a.registration_endpoint):void 0,resourceMetadataUrl:n?.resourceMetadataUrl},...o?{resource:o}:{}}},probeMcpServer=async(e,t=Ve)=>{let n=t.createClient(e);try{return await n.listTools(),{requiresAuthorization:!1,server:await n.getServerInfo().catch(()=>void 0)}}catch(n){if(!isAuthorizationFailure(n))throw n;return probeProtectedServer(e,t)}finally{await n.close().catch(()=>void 0)}},He=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),X=e(e=>Array.isArray(e)?e:[e],`toStringArray`),isNullish=e=>e==null,toQueryValue=e=>Array.isArray(e)?e.filter(e=>!isNullish(e)).map(String):String(e),hasValue=e=>e.in===`body`||!isNullish(e.value),mergeQueryValues=(e,t,n)=>{let r=X(t);if(He(e))return{value:[...X(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...X(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.filter(hasValue).reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.inline)e.body=t.value;else if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),Ue=[`query`,`body`,`headers`],We=[`repeat`,`brackets`,`comma`,`stringify`],Ge={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},Ke=new ue(Ge),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return Ke.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?A.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199,qe=[`arraybuffer`,`blob`,`document`,`text`];let Je;const getXmlParser=()=>(Je??=new de({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Je);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f,context:p,cacheTTL:m,timeoutMs:h}){let g,_=o;if(isXmlContentType(r))if(typeof o==`string`)_=o;else if(Array.isArray(o))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else o!=null&&(_=serializeBodyToXml(o));try{g=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:_,requestConfig:l,httpsAgent:u,responseType:f,context:p,cacheTTL:m,timeoutMs:h})}catch(e){if(s(e?.response))throw e;g=e.response}if(typeof g.data==`string`&&/\S/.test(g.data)&&g.headers&&isXmlContentType(g.headers)&&(!f||!qe.includes(f))){let e=j.validate(g.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);g={...g,data:getXmlParser().parse(g.data)}}let v=translateCustomError(g,c,d);if(isFailedStatusCode(v?.status))throw new V(v,v.message);return v}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,credentials:u,context:d,cacheTTL:f}){let p;if(p=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?Z.build(l.envelope):await buildEnvelope(o,l),j.validate(p,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let m,h={"Content-Type":`application/xml`,...r};l?.soapAction&&(h.SOAPAction=l.soapAction);try{m=await e?.request({method:n,url:t,headers:h,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:p,requestConfig:l,context:d,cacheTTL:f})}catch(e){if(s(e?.response))throw e;m=e.response}let g=Ye.parse(m.data),_=g.Envelope||g,v=_.Body||_,y=v.Fault;if(y)throw new V({...m,status:500,data:y,message:y.faultstring??y.faultcode??`SOAP Fault`},y.faultstring??`SOAP Fault occurred`);m.data=v;let b=translateCustomError(m,c,u);if(isFailedStatusCode(b?.status))throw new V(b,b.message);return b}};const Z=new ue(Ge),Ye=new de({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Z.build(t.envelope);if(j.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Z.build(n);if(j.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>w(`sha256`,e).update(t).digest(),hash=e=>C(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Q=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Xe=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return Q(decodeURIComponent(e))}catch{return Q(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=Xe(e,n);return i===0?Xe(t,r):i});let h=m.map(([e,t])=>`${Q(e)}=${Q(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=C(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let b=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),x=g.length>0&&!b,S;x&&(S=_.toString(`base64`),y[`x-amz-checksum-sha256`]=S);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),E=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),D=T.join(`;`),ee=[e.method.toUpperCase(),p,h,E,D,v].join(`
206
+ `),O=`${d}/${l}/${s}/aws4_request`,te=[`AWS4-HMAC-SHA256`,u,O,hash(ee)].join(`
207
+ `),k={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${D}, Signature=${w(`sha256`,getSigningKey(i,d,l,s)).update(te).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(k[`x-amz-security-token`]=a),S!==void 0&&(k[`x-amz-checksum-sha256`]=S),k},Ze=[`sha256`,`sha512`],isValidAlgorithm=e=>Ze.includes(e),hashPayload=e=>C(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,d=new Date().toISOString(),f=new URL(e.url),p=[];for(let[e,t]of f.searchParams.entries())p.push([e,t]);p.push(...flattenQueryParams(e.query)),p.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let m=p.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),h=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),g=[d,e.method.toUpperCase(),f.pathname,m,h].join(`
208
208
  `),_=w(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},Qe=[`sha1`,`sha256`,`sha512`],formatRfc2822Date=e=>e.toUTCString().replace(`GMT`,`-0000`),extractBodyParams=e=>{let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=Array.isArray(r)?r:[r];for(let r of e)t.push([n,String(r)])}return t};function requiresExtendedSigning(e){let{algorithm:t,dateFormat:n,includeHost:r,includeBodyHash:i,outputFormat:a,username:o}=e;return!!(n===`rfc2822`||r===!0||i===!1||a===`basic`||o||t===`sha1`)}function signWithExtendedOptions(e,t,n){let{algorithm:r,headerName:i,prefix:a,dateFormat:o=`iso8601`,includeHost:s=!1,includeBodyHash:c=!0,outputFormat:l=`header`,username:u}=n;if(r&&!Qe.includes(r))throw Error(`Unsupported HMAC algorithm "${r}". Use "sha1", "sha256", or "sha512".`);if(l===`basic`&&!u)throw Error(`HMAC signing with outputFormat "basic" requires username`);if(u&&/[:\r\n]/.test(u))throw Error(`HMAC signing username cannot contain ":", "\\r", or "\\n"`);let d=r??`sha256`,f=new URL(e.url),p=new Date,m=o===`rfc2822`?formatRfc2822Date(p):p.toISOString(),h=[...f.searchParams.entries(),...flattenQueryParams(e.query)];!c&&e.body&&typeof e.body==`object`&&!Array.isArray(e.body)&&(e.headers?.[`content-type`]??e.headers?.[`Content-Type`]??``).toLowerCase().includes(`application/x-www-form-urlencoded`)&&h.push(...extractBodyParams(e.body)),h.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let g=h.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),_=[m,e.method.toUpperCase()];s&&_.push(f.hostname.toLowerCase()),_.push(f.pathname,g),c&&_.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let v=w(d,t).update(_.join(`
209
- `)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy);export{be as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,B as HttpErrorMessages,Pe as HttpMethods,V as HttpResponseError,HttpTransportFactory,H as InstanceManager,LockManager,McpClient,MemoryStore,We as QueryArrayFormats,QueueManager,RateLimitManager,ge as RedisClient,RequestClientFactory,Ue as RequestParameterLocations,ScriptManager,SubscriptionManager,TransportManagersUnavailableError,buildHttpClientInstance,buildHttpsAgent,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getSigningStrategy,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,probeMcpServer,registerSigningStrategy,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
209
+ `)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy);export{be as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,B as HttpErrorMessages,Pe as HttpMethods,V as HttpResponseError,HttpTransportFactory,H as InstanceManager,LockManager,McpClient,MemoryStore,We as QueryArrayFormats,QueueManager,RateLimitManager,he as RedisClient,RequestClientFactory,Ue as RequestParameterLocations,ScriptManager,SubscriptionManager,TransportManagersUnavailableError,buildHttpClientInstance,buildHttpsAgent,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getSigningStrategy,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,probeMcpServer,registerSigningStrategy,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.36.2",
3
+ "version": "2.37.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",