@stackone/transport 2.44.0 → 2.45.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=/* @__PURE__ */ new Map,this.setRemovalRegistry=/* @__PURE__ */ new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==`__keyevent@0__:expired`)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!==`__keyevent@0__:srem`)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)&&this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(`__keyevent@0__:set`)&&n.includes(`__keyevent@0__:expire`)&&n.includes(`__keyevent@0__:expired`)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=(n,r)=>{let i=setTimeout(()=>{let e=Date.now()-t;r(/* @__PURE__ */ Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4),checkCallback=()=>{clearTimeout(i);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)},subscribeAndTrigger=async()=>{let t=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(ae.map(async n=>this.addTestSubscription(n,t,e,checkCallback)))).every(Boolean))throw Error(`Failed to subscribe to event channels.`);if(!await this.cacheClient?.setData({key:t,value:`test`,cacheTTL:1}))throw Error(`Failed to write the Redis test key.`)};subscribeAndTrigger().catch(e=>{clearTimeout(i),r(e)})};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(`__keyevent@0__:expired`,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(`__keyevent@0__:srem`,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=M*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(M,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 F={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=n?{...e,credentials:n}:e,a=(0,u.safeEvaluate)(r,i)===!0;if((0,o.isMissing)(r)||a){let n=t?.message,r;return r=(0,o.isMissing)(n)?F[t.targetStatus]??`Unknown error`:String((0,u.safeEvaluate)(n,e)??F[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},ce=(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.`}),le=`EgressProxyError`,ue=/* @__PURE__ */ new Map([[407,{status:403,describe:e=>`The egress proxy refused the connection to ${e}`}],[429,{status:503,describe:e=>`The egress proxy was too busy to connect to ${e}`}],[502,{status:502,describe:e=>`The egress proxy could not reach ${e}`}],[504,{status:504,describe:e=>`${e} did not answer the egress proxy in time`}]]);var EgressProxyError=class extends Error{constructor(e,{status:t,proxyStatus:n,proxyReason:r,cause:i}){super(e),this.cause=i,this.name=le,this.status=t,this.proxyStatus=n,this.proxyReason=r}},ConflictingProxyError=class extends Error{constructor(...e){super(...e),this.name=`ConflictingProxyError`}},UntunnelledTransportError=class extends Error{constructor(...e){super(...e),this.name=`UntunnelledTransportError`}},InvalidEgressProxyUrlError=class extends Error{constructor(...e){super(...e),this.name=`InvalidEgressProxyUrlError`}};const isEgressProxyError=e=>e instanceof Error&&e.name===le&&typeof e.status==`number`,egressProxyRefusal=(e,t,n)=>{let r=ue.get(e);return new EgressProxyError(r?.describe(t)??`The egress proxy answered ${e} when connecting to ${t}`,{status:r?.status??502,proxyStatus:e,proxyReason:n})},egressProxyUnavailable=(e,t)=>new EgressProxyError(`Could not reach the egress proxy to connect to ${e}`,{status:503,cause:t}),egressProxyTimedOut=e=>new EgressProxyError(`The egress proxy did not answer when connecting to ${e}`,{status:504}),causeChain=(e,t=/* @__PURE__ */ new Set)=>e instanceof Error&&!t.has(e)?[e,...causeChain(e.cause,/* @__PURE__ */ new Set([...t,e]))]:[],findEgressProxyError=e=>causeChain(e).reverse().find(isEgressProxyError),de=3e4,fe=Symbol(`egressProxyUrl`),authorityOf=(e,t)=>`${(0,p.isIP)(e)===6?`[${e}]`:e}:${t}`,onceOnly=e=>{let t={called:!1};return(n,r)=>{t.called||(t.called=!0,e(n,r))}},upgradeToTls=e=>{try{return m.default.connect(e)}catch(e){return e instanceof Error?e:Error(String(e))}},openTunnel=(e,t,n,r)=>{let i=(0,o.notMissing)(t),a=n.host??`localhost`,s=Number(n.port??(i?443:80)),c=authorityOf(a,s),l=onceOnly(r),u=d.default.request({host:e.hostname.replace(/^\[|\]$/g,``),port:Number(e.port||80),method:`CONNECT`,path:c,headers:{host:c},agent:!1});u.setTimeout(de,()=>{u.destroy(egressProxyTimedOut(c))}),u.once(`connect`,(e,r,o)=>{if(r.setTimeout(0),e.statusCode!==200){r.destroy(),l(egressProxyRefusal(e.statusCode??0,c,e.headers[`x-smokescreen-error`]));return}if(o.length>0&&r.unshift(o),!i){l(null,r);return}let{path:s,...u}=n,d=upgradeToTls({...u,socket:r,secureContext:t,servername:n.servername||((0,p.isIP)(a)?void 0:a)});d instanceof Error?(r.destroy(),l(d)):l(null,d)}),u.once(`error`,e=>{l(isEgressProxyError(e)?e:egressProxyUnavailable(c,e))}),u.end()},tunnelThroughEgressProxy=(e,t)=>{let n=parseEgressProxyUrl(t),r=e instanceof f.default.Agent,i=e;return i[fe]=t,i.createConnection=(e,t)=>{if((0,o.isMissing)(t))throw Error(`A tunnelled connection is only handed over through its callback`);let i=r?e.secureContext??m.default.createSecureContext(e):void 0;openTunnel(n,i,e,t)},i},parseEgressProxyUrl=e=>{let t=URL.canParse(e)?new URL(e):void 0;if((0,o.isMissing)(t)||t.protocol!==`http:`||t.username||t.password)throw new InvalidEgressProxyUrlError(`The egress proxy URL must be an http:// URL with no credentials`);return t},egressProxyOf=e=>e?.[fe],pe=/* @__PURE__ */ new WeakMap,tunnelledCopyOf=(e,t)=>{let n=pe.get(e);if(n&&egressProxyOf(n)===t)return n;let r=e.options,i=tunnelThroughEgressProxy(e instanceof f.default.Agent?new f.default.Agent(r):new d.default.Agent(r),t);return pe.set(e,i),i},me=/Proxy response \((\d{3})\)/,he=/* @__PURE__ */ new Set([`ECONNREFUSED`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOTFOUND`]),I={},loadUndici=()=>(I.loading??=import(`undici`),I.loading),proxyClientFactory=(e,t)=>(n,r)=>{let i=new e.Pool(n,r),a=i.connect.bind(i);return Object.assign(i,{connect:e=>{let n=AbortSignal.timeout(t),r=e.signal instanceof AbortSignal?AbortSignal.any([e.signal,n]):n;return a({...e,signal:r}).catch(t=>{throw n.aborted?egressProxyTimedOut(String(e.path)):t})}})},L=/* @__PURE__ */ new Map,proxyAgentFor=async(e,t)=>{let n=`${e}|${t}`,r=await loadUndici(),i=L.get(n)??new r.ProxyAgent({uri:e,clientFactory:proxyClientFactory(r,t)});return L.set(n,i),i},targetOf=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return`${n}:${r||(t===`https:`?443:80)}`},toEgressProxyError=(e,t)=>{let n=findEgressProxyError(e);if(n)return n;let r=causeChain(e),i=r.map(e=>me.exec(e.message)?.[1]).find(e=>e!==void 0);if(i!==void 0)return egressProxyRefusal(Number(i),targetOf(t));let a=r.find(e=>he.has(e.code??``));return a?egressProxyUnavailable(targetOf(t),a):void 0},createEgressProxyFetch=(e,{connectTimeoutMs:t=de}={})=>(parseEgressProxyUrl(e),async(n,r)=>{let{fetch:i}=await loadUndici();try{return await i(n,{...r,dispatcher:await proxyAgentFor(e,t)})}catch(e){throw toEgressProxyError(e,n)??e}});var R=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 ge=[`client_disconnect`,`timeout`],z=`RequestAbortedError`,_e={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(_e[e]),this.name=z,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===z&&ge.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=/* @__PURE__ */ 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)}},ve=4e3,ye={keepAlive:!0,maxFreeSockets:8,scheduling:`lifo`};var KeepAliveHttpsAgent=class extends f.default.Agent{keepSocketAlive(e){let t=this.options.timeout===void 0;t&&(this.options.timeout=ve);try{return super.keepSocketAlive(e)}finally{t&&delete this.options.timeout}}};const B=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:B,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:B,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:B,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:s,rateLimitManager:c,egressProxyUrl:l}){let throughEgressProxy=e=>(0,o.notMissing)(l)?tunnelThroughEgressProxy(e,l):e,u=throughEgressProxy(n?.keepAlive?new KeepAliveHttpsAgent(n):new f.default.Agent(n)),p=n?.keepAlive?throughEgressProxy(new f.default.Agent({...n,keepAlive:!1,maxSockets:1/0,maxTotalSockets:n.maxTotalSockets??n.maxSockets})):void 0,m=(0,o.notMissing)(l)?throughEgressProxy(new d.default.Agent({keepAlive:!0,scheduling:`lifo`,timeout:ve})):void 0,g=h.default.create({...t,httpsAgent:u,...(0,o.notMissing)(m)&&{httpAgent:m,proxy:!1}});if(p){let sendOnOwnConnectionUnlessGet=e=>e.method===`get`||e.httpsAgent!==u?e:{...e,httpsAgent:p};g.interceptors.request.use(sendOnOwnConnectionUnlessGet)}if(g.close=()=>{let e={accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action};closeAgentWhenIdle(u,{logger:r,logContext:{...e,connections:`instance`}}),p&&closeAgentWhenIdle(p,{logger:r,logContext:{...e,connections:`nonGetRequests`}}),m&&closeAgentWhenIdle(m,{logger:r,logContext:{...e,connections:`egressHttp`}})},e){let t={axiosInstance:g,logger:r,context:i,requestConfig:a,concurrencyManager:s,rateLimitManager:c};this.applyInterceptors(g,e,t)}return g}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}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},be=6048e5;var V=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({staleDataThreshold:be,truncateThreshold:1e4,...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,slidingExpiration:!0,typeGuard:e=>(0,o.notMissing)(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}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 H=V.getInstance(),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},xe={mainRatelimit:25},U=1e3,Se=/^\d+(\.\d+)?$/,Ce=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=/* @__PURE__ */ __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,_.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}r.aborted?(cleanup(),a(c)):s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),G=`checkConcurrencyInterceptor`,we=new LogThrottle(Ce),Te=new LogThrottle(Ce),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:G,...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:G,...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,g.randomUUID)(),{provider:c,accountSecureId:l}=t,u=n?.rateLimits??xe,d=n?.concurrency??oe,f=await i.getDynamicMaxWaitTime(u,d,a.url),p=a._waitDeadlineAt,m=(0,o.isNumber)(p)&&Number.isFinite(p)?p:Date.now()+f*U,remainingBudgetMs=()=>Math.max(m-Date.now(),0),h=`${l}-${c}`,register=async()=>r.registerRequest(h,d,s,a.url,remainingBudgetMs(),a.signal),_=remainingBudgetMs()<=0,v;do{let t=await i.getWaitTime(h,u,a.url);if((0,o.isMissing)(t)){let t=we.consume(h);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:G,provider:c,accountSecureId:l,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){v=await register();break}if(remainingBudgetMs()<=0)break;let r=Math.min(Math.max(n,50),remainingBudgetMs());await W(r,a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f,joinCondition:v?.joinCondition};if(_){let t=Te.consume(h);(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:m}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*U:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return!Number.isNaN(t)&&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*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]=(0,v.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,v.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)/U);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Se.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: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*U:(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 W(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=(0,o.isObject)(s)?(0,y.JSONPath)({path:f,json:s,wrap:!0}):[s],m=Array.isArray(p)?p[0]:void 0,h=testMessage(m,r);if(t===i&&h){let e=d??extractRetryAfter(a,l),t=convertRetryAfter(e,u);return{status:429,retryAfter:c??t}}}return{status:i,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(String(e??``)):typeof e==`string`||Array.isArray(e)?e.includes(t):!1,extractRetryAfter=(e,t)=>{if((0,o.notMissing)(t)&&(0,o.notMissing)(e)){let n=(0,y.JSONPath)({path:t,json:e,wrap:!0}),r=Array.isArray(n)?n[0]:void 0,i=Array.isArray(r)&&r.length===1?r[0]:r;return typeof i==`string`||typeof i==`number`?i:null}return 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)/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: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:K,...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:K,...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:K,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*U:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await W(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},q=`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:q,...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:q,...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:q,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:q,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},Ee=/* @__PURE__ */ new Set([`ECONNRESET`,`EPIPE`]),isResetOnReusedSocket=e=>{let t=e.request;return(0,o.isMissing)(e.response)&&Ee.has(e.code??``)&&(t?._currentRequest??t)?.reusedSocket===!0},De=[d.default.Agent,f.default.Agent,KeepAliveHttpsAgent],isRebuildable=e=>De.includes(e.constructor)&&!Object.prototype.hasOwnProperty.call(e,`createConnection`),unpooledCopy=(e,t)=>{let n=egressProxyOf(e);return(0,o.notMissing)(n)?tunnelThroughEgressProxy(new t({...e?.options,keepAlive:!1}),n):(0,o.isMissing)(e)||isRebuildable(e)?new t({...e?.options,keepAlive:!1}):e},withFreshConnection=e=>({...e,_staleSocketRetried:!0,httpAgent:unpooledCopy(e.httpAgent,d.default.Agent),httpsAgent:unpooledCopy(e.httpsAgent,f.default.Agent)}),withoutQuery=(e=``)=>(0,b.redactUrl)(e.split(`?`)[0]),staleSocketRetryInterceptor=({axiosInstance:e,logger:t,context:n})=>{let staleSocketRetryInterceptor=async r=>{let{config:i}=r;if((0,o.isMissing)(i)||!isResetOnReusedSocket(r))return Promise.reject(r);let a=(i.method??`get`).toUpperCase(),s=a===`GET`&&i._staleSocketRetried!==!0&&i.signal?.aborted!==!0&&(0,o.notMissing)(e);return t?.info({category:`http-transport`,message:`Provider closed a reused connection [${a} ${withoutQuery(i.url)}]: ${r.code}. ${s?`Retrying once on a new connection.`:`Not retried.`}`,context:{...n??{},method:a,errorCode:r.code,retried:s}}),s?e?.request(withFreshConnection(i)):Promise.reject(r)};return staleSocketRetryInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Oe=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ke=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],Ae=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],je=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{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=/* @__PURE__ */ 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 Me=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i,egressProxyUrl:a}={})=>{let s,{NODE_ENV:c}=process.env,l=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(s=l.includes(`RETRY`)?createDefaultRetryInstance(e,n,a):createDefaultInstance(e,n,a),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||c===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return s;let u=SingletonManager.getIfReady(RateLimitManager)??void 0,d=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=u?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(l.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(...Ae),h.push(...je)}let g=generateRequestKey(n),_=(0,o.notMissing)(g)&&(0,o.notMissing)(a)?`${g}|egress:${a}`:g;if((0,o.isMissing)(_))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)(s)}}),s;let v=await H.get(_);if((0,o.notMissing)(v))return v;let y={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:l.includes(`CONCURRENCY`)?{...ye,...i}:i,concurrencyManager:d,rateLimitManager:u,egressProxyUrl:a},b=HttpTransportFactory.createInstance(y);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${_}]`,context:{...n}}),await H.set(_,b,600),b}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(s)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=Me.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);(0,o.notMissing)(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);if((0,o.notMissing)(s))return s;if((0,o.notMissing)(a))throw t;return createAxiosInstance()}},createDefaultInstance=(e,t,n)=>{let r={instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createDefaultRetryInstance=(e,t,n)=>{let r={interceptors:{requestConfigs:Oe,responseConfigs:ke},instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createAxiosInstance=()=>h.default.create({maxBodyLength:1/0}),Ne=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,Ne);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,Ne,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),Pe=/^-?\d+$/,Fe=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&Pe.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!Fe.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},Ie=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return Ie.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=(0,b.redactFields)(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(/* @__PURE__ */ Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>(0,o.isMissing)(e)?void 0:{url:(0,b.redactUrl)(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!(0,h.isAxiosError)(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,(0,o.notMissing)(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof C.Readable&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},Le=/* @__PURE__ */ new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Le.has(e),toFailureCacheKey=e=>`${e}-error`,Re=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Re 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 h.AxiosError(e.message??`Request failed with status code ${e.status}`,h.AxiosError.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[Re]:!0})},egressCacheKeyPrefix=e=>`egress|${(0,x.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}|`,tunnelledRequestConfig=(e,{httpAgent:t,httpsAgent:n},r)=>{let i=e?.defaults,a=(0,o.notMissing)(t)?tunnelledCopyOf(t,r):i?.httpAgent,s=(0,o.notMissing)(n)?tunnelledCopyOf(n,r):i?.httpsAgent;if(egressProxyOf(a)!==r||egressProxyOf(s)!==r)throw new UntunnelledTransportError(`The transport for a client that tunnels through the egress proxy does not tunnel through it`);return{httpAgent:a,httpsAgent:s,proxy:!1,adapter:`http`}};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i,egressProxyUrl:a}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,a&&parseEgressProxyUrl(a),this.egressProxyUrl=a||void 0}#o(e){if(e&&this.egressProxyUrl)throw new ConflictingProxyError(`This client tunnels through the egress proxy, so a request cannot name a proxy of its own`);return this.egressProxyUrl}#s(e,t,n){let r=findEgressProxyError(e);if(!(0,o.isMissing)(r))throw this.#n?.warning({category:this.name,message:`Egress proxy did not carry [${t?.toUpperCase()} ${(0,b.redactUrl)(n)}]: ${r.message}.`,context:{status:r.status,proxyStatus:r.proxyStatus,proxyReason:r.proxyReason}}),r}#c({url:e,payload:t,method:n,context:r,egressProxyUrl:i}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?(0,o.getContentHash)(t):``;return`${i?egressCacheKeyPrefix(i):``}${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a}){if(!this.#a||!r||r<=0)return null;let o=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!o)return null;let s=await this.#a.getDataBatch([toFailureCacheKey(o),o]),c=s?.[0]??s?.[1]??null;return c?(this.#n?.debug({category:this.name,message:`Cache hit for key [${o}].`}),c):(this.#n?.debug({category:this.name,message:`Cache miss for key [${o}].`}),null)}async#u({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,response:o}){if(!this.#a||!r||r<=0)return!1;let s=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});return s?(this.#n?.debug({category:this.name,message:`Caching result for key [${s}].`}),this.#a.setData({key:s,value:o,cacheTTL:r*60})):!1}async#d(e){if(!(0,o.isMissing)(e))try{return(await V.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#f({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#p({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,error:s}){if(!this.#a||(0,o.isMissing)(r)||r<=0||!(0,h.isAxiosError)(s)||!isCacheableFailureStatus(s.response?.status))return!1;let c={data:s.response?.data,status:s.response?.status,headers:this.#h(s.response?.headers??{}),method:n,requestUrl:e,message:s.message,responseTime:/* @__PURE__ */ new Date},l=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!l)return!1;let u=toFailureCacheKey(l);return this.#n?.debug({category:this.name,message:`Caching ${c.status} for key [${u}].`}),this.#a.setData({key:u,value:c,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:h,timeoutMs:g,proxyUrl:_}){let v=await this.#d(u),y=this.#o(_);try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#C(t,r,i),b=this.#m(e),x=this.#b(d,e),S=await this.#l({url:u,payload:x,method:n,cacheTTL:c,context:l,egressProxyUrl:y});if(S){if(isCacheableFailureStatus(S.status))throw rebuildCachedFailure(S,n);return{...S,responseTime:/* @__PURE__ */ new Date}}let C=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:h,egressProxyUrl:y}),w=await C.request({headers:b,url:u,method:n,maxRedirects:a,responseType:s,data:x,...y?tunnelledRequestConfig(C,{httpAgent:p,httpsAgent:f},y):{httpsAgent:f,httpAgent:p},signal:v,...(0,o.notMissing)(g)&&{timeout:g},..._&&{proxy:buildProxyConfig(_)},transformResponse:e=>parseJsonExactly(e,s,this.#n)}),T={data:w.data,status:w.status,body:x,method:n,headers:this.#h(w.headers),requestHeaders:buildSafeRequestHeaders(b),requestUrl:u,responseType:w?.config?.responseType,responseTime:/* @__PURE__ */ new Date};return await this.#u({url:u,payload:x,method:n,cacheTTL:c,context:l,egressProxyUrl:y,response:T}),T}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#x(e);throw(0,o.notMissing)(t)?t:e}this.#s(a,n,t);let s=await toCallerSafeError(a);s.url=(0,b.redactUrl)(t),this.#f({signal:v,error:s,message:`Request error [${n?.toUpperCase()} ${s.url}]: ${s.message}.`}),await this.#p({url:this.#C(t,r,i),payload:this.#b(d,e),method:n,cacheTTL:c,context:l,egressProxyUrl:y,error:s});let u=this.#x(s);throw(0,o.notMissing)(u)?u:s}}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}){let h=await this.#d(c),g=this.#o(m);try{let o=this.#C(t,r,i),c=this.#m(e),_=this.#b(l,e),v=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p,egressProxyUrl:g}),y=await v.request({headers:c,url:o,method:n,maxRedirects:a,responseType:`stream`,data:_,...g?tunnelledRequestConfig(v,{httpAgent:d,httpsAgent:u},g):{httpsAgent:u,httpAgent:d},signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:y.status,headers:this.#h(y.headers),stream:y.data,requestUrl:t}}catch(e){this.#s(e,n,t);let r=await toCallerSafeError(e);r.url=(0,b.redactUrl)(t),this.#f({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#x(r);throw(0,o.notMissing)(i)?i:r}}#m(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#h(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#g(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#_(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#v(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#y(e){return Buffer.isBuffer(e)}#b(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#_(t)||this.#v(e)||this.#y(e)||typeof e==`string`?e:this.#g(t)?S.default.stringify(e):e}#x(e){if((0,h.isAxiosError)(e)&&this.#i)return this.#i(e)}#S(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#C(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.#S(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(S.default.stringify(r,l)),Object.keys(i).length>0&&u.push(S.default.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(S.default.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(s).length>0&&u.push(S.default.stringify(s,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(S.default.stringify(c,l));let d=u.join(`&`);return(0,o.notMissing)(d)?`${e}?${d}`:e}};const buildHttpClientInstance=(e,t,n,r)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n,egressProxyUrl:r});var HttpClientManager=class{static{this.httpClientInstances=/* @__PURE__ */ new Map}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance,egressProxyUrl:i}){let a=i||`direct`,o=this.httpClientInstances.get(a);if(o)return o;let s=r(e,t,n,i||void 0);if(i&&s.egressProxyUrl!==i)throw new UntunnelledTransportError(`The client built for the egress proxy does not tunnel through it`);return this.httpClientInstances.set(a,s),s}static resetInstance(){this.httpClientInstances.clear()}};const ze=[`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=/* @__PURE__ */ new Map,this.setRemovalRegistry=/* @__PURE__ */ new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==`__keyevent@0__:expired`)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!==`__keyevent@0__:srem`)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)&&this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(`__keyevent@0__:set`)&&n.includes(`__keyevent@0__:expire`)&&n.includes(`__keyevent@0__:expired`)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=(n,r)=>{let i=setTimeout(()=>{let e=Date.now()-t;r(/* @__PURE__ */ Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4),checkCallback=()=>{clearTimeout(i);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)},subscribeAndTrigger=async()=>{let t=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(ae.map(async n=>this.addTestSubscription(n,t,e,checkCallback)))).every(Boolean))throw Error(`Failed to subscribe to event channels.`);if(!await this.cacheClient?.setData({key:t,value:`test`,cacheTTL:1}))throw Error(`Failed to write the Redis test key.`)};subscribeAndTrigger().catch(e=>{clearTimeout(i),r(e)})};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(`__keyevent@0__:expired`,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(`__keyevent@0__:srem`,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=M*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(M,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 F={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=n?{...e,credentials:n}:e,a=(0,u.safeEvaluate)(r,i)===!0;if((0,o.isMissing)(r)||a){let n=t?.message,r;return r=(0,o.isMissing)(n)?F[t.targetStatus]??`Unknown error`:String((0,u.safeEvaluate)(n,e)??F[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},ce=(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.`}),le=`EgressProxyError`,ue=/* @__PURE__ */ new Map([[407,{status:403,describe:e=>`The egress proxy refused the connection to ${e}`}],[429,{status:503,describe:e=>`The egress proxy was too busy to connect to ${e}`}],[502,{status:502,describe:e=>`The egress proxy could not reach ${e}`}],[504,{status:504,describe:e=>`${e} did not answer the egress proxy in time`}]]);var EgressProxyError=class extends Error{constructor(e,{status:t,proxyStatus:n,proxyReason:r,cause:i}){super(e),this.cause=i,this.name=le,this.status=t,this.proxyStatus=n,this.proxyReason=r}},ConflictingProxyError=class extends Error{constructor(...e){super(...e),this.name=`ConflictingProxyError`}},UntunnelledTransportError=class extends Error{constructor(...e){super(...e),this.name=`UntunnelledTransportError`}},InvalidEgressProxyUrlError=class extends Error{constructor(...e){super(...e),this.name=`InvalidEgressProxyUrlError`}};const isEgressProxyError=e=>e instanceof Error&&e.name===le&&typeof e.status==`number`,egressProxyRefusal=(e,t,n)=>{let r=ue.get(e);return new EgressProxyError(r?.describe(t)??`The egress proxy answered ${e} when connecting to ${t}`,{status:r?.status??502,proxyStatus:e,proxyReason:n})},egressProxyUnavailable=(e,t)=>new EgressProxyError(`Could not reach the egress proxy to connect to ${e}`,{status:503,cause:t}),egressProxyTimedOut=e=>new EgressProxyError(`The egress proxy did not answer when connecting to ${e}`,{status:504}),causeChain=(e,t=/* @__PURE__ */ new Set)=>e instanceof Error&&!t.has(e)?[e,...causeChain(e.cause,/* @__PURE__ */ new Set([...t,e]))]:[],findEgressProxyError=e=>causeChain(e).reverse().find(isEgressProxyError),de=3e4,fe=Symbol(`egressProxyUrl`),authorityOf=(e,t)=>`${(0,p.isIP)(e)===6?`[${e}]`:e}:${t}`,onceOnly=e=>{let t={called:!1};return(n,r)=>{t.called||(t.called=!0,e(n,r))}},upgradeToTls=e=>{try{return m.default.connect(e)}catch(e){return e instanceof Error?e:Error(String(e))}},openTunnel=(e,t,n,r)=>{let i=(0,o.notMissing)(t),a=n.host??`localhost`,s=Number(n.port??(i?443:80)),c=authorityOf(a,s),l=onceOnly(r),u=d.default.request({host:e.hostname.replace(/^\[|\]$/g,``),port:Number(e.port||80),method:`CONNECT`,path:c,headers:{host:c},agent:!1});u.setTimeout(de,()=>{u.destroy(egressProxyTimedOut(c))}),u.once(`connect`,(e,r,o)=>{if(r.setTimeout(0),e.statusCode!==200){r.destroy(),l(egressProxyRefusal(e.statusCode??0,c,e.headers[`x-smokescreen-error`]));return}if(o.length>0&&r.unshift(o),!i){l(null,r);return}let{path:s,...u}=n,d=upgradeToTls({...u,socket:r,secureContext:t,servername:n.servername||((0,p.isIP)(a)?void 0:a)});d instanceof Error?(r.destroy(),l(d)):l(null,d)}),u.once(`error`,e=>{l(isEgressProxyError(e)?e:egressProxyUnavailable(c,e))}),u.end()},tunnelThroughEgressProxy=(e,t)=>{let n=parseEgressProxyUrl(t),r=e instanceof f.default.Agent,i=e;return i[fe]=t,i.createConnection=(e,t)=>{if((0,o.isMissing)(t))throw Error(`A tunnelled connection is only handed over through its callback`);let i=r?e.secureContext??m.default.createSecureContext(e):void 0;openTunnel(n,i,e,t)},i},parseEgressProxyUrl=e=>{let t=URL.canParse(e)?new URL(e):void 0;if((0,o.isMissing)(t)||t.protocol!==`http:`||t.username||t.password)throw new InvalidEgressProxyUrlError(`The egress proxy URL must be an http:// URL with no credentials`);return t},egressProxyOf=e=>e?.[fe],pe=/* @__PURE__ */ new WeakMap,tunnelledCopyOf=(e,t)=>{let n=pe.get(e);if(n&&egressProxyOf(n)===t)return n;let r=e.options,i=tunnelThroughEgressProxy(e instanceof f.default.Agent?new f.default.Agent(r):new d.default.Agent(r),t);return pe.set(e,i),i},me=/Proxy response \((\d{3})\)/,he=/* @__PURE__ */ new Set([`ECONNREFUSED`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOTFOUND`]),I={},loadUndici=()=>(I.loading??=import(`undici`),I.loading),proxyClientFactory=(e,t)=>(n,r)=>{let i=new e.Pool(n,r),a=i.connect.bind(i);return Object.assign(i,{connect:e=>{let n=AbortSignal.timeout(t),r=e.signal instanceof AbortSignal?AbortSignal.any([e.signal,n]):n;return a({...e,signal:r}).catch(t=>{throw n.aborted?egressProxyTimedOut(String(e.path)):t})}})},L=/* @__PURE__ */ new Map,proxyAgentFor=async(e,t)=>{let n=`${e}|${t}`,r=await loadUndici(),i=L.get(n)??new r.ProxyAgent({uri:e,proxyTunnel:!0,clientFactory:proxyClientFactory(r,t)});return L.set(n,i),i},targetOf=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return`${n}:${r||(t===`https:`?443:80)}`},toEgressProxyError=(e,t)=>{let n=findEgressProxyError(e);if(n)return n;let r=causeChain(e),i=r.map(e=>me.exec(e.message)?.[1]).find(e=>e!==void 0);if(i!==void 0)return egressProxyRefusal(Number(i),targetOf(t));let a=r.find(e=>he.has(e.code??``));return a?egressProxyUnavailable(targetOf(t),a):void 0},createEgressProxyFetch=(e,{connectTimeoutMs:t=de}={})=>(parseEgressProxyUrl(e),async(n,r)=>{let{fetch:i}=await loadUndici();try{return await i(n,{...r,dispatcher:await proxyAgentFor(e,t)})}catch(e){throw toEgressProxyError(e,n)??e}});var R=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 ge=[`client_disconnect`,`timeout`],z=`RequestAbortedError`,_e={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(_e[e]),this.name=z,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===z&&ge.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=/* @__PURE__ */ 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)}},ve=4e3,ye={keepAlive:!0,maxFreeSockets:8,scheduling:`lifo`};var KeepAliveHttpsAgent=class extends f.default.Agent{keepSocketAlive(e){let t=this.options.timeout===void 0;t&&(this.options.timeout=ve);try{return super.keepSocketAlive(e)}finally{t&&delete this.options.timeout}}};const B=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:B,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:B,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:B,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:s,rateLimitManager:c,egressProxyUrl:l}){let throughEgressProxy=e=>(0,o.notMissing)(l)?tunnelThroughEgressProxy(e,l):e,u=throughEgressProxy(n?.keepAlive?new KeepAliveHttpsAgent(n):new f.default.Agent(n)),p=n?.keepAlive?throughEgressProxy(new f.default.Agent({...n,keepAlive:!1,maxSockets:1/0,maxTotalSockets:n.maxTotalSockets??n.maxSockets})):void 0,m=(0,o.notMissing)(l)?throughEgressProxy(new d.default.Agent({keepAlive:!0,scheduling:`lifo`,timeout:ve})):void 0,g=h.default.create({...t,httpsAgent:u,...(0,o.notMissing)(m)&&{httpAgent:m,proxy:!1}});if(p){let sendOnOwnConnectionUnlessGet=e=>e.method===`get`||e.httpsAgent!==u?e:{...e,httpsAgent:p};g.interceptors.request.use(sendOnOwnConnectionUnlessGet)}if(g.close=()=>{let e={accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action};closeAgentWhenIdle(u,{logger:r,logContext:{...e,connections:`instance`}}),p&&closeAgentWhenIdle(p,{logger:r,logContext:{...e,connections:`nonGetRequests`}}),m&&closeAgentWhenIdle(m,{logger:r,logContext:{...e,connections:`egressHttp`}})},e){let t={axiosInstance:g,logger:r,context:i,requestConfig:a,concurrencyManager:s,rateLimitManager:c};this.applyInterceptors(g,e,t)}return g}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}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},be=6048e5;var V=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({staleDataThreshold:be,truncateThreshold:1e4,...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,slidingExpiration:!0,typeGuard:e=>(0,o.notMissing)(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}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 H=V.getInstance(),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},xe={mainRatelimit:25},U=1e3,Se=/^\d+(\.\d+)?$/,Ce=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=/* @__PURE__ */ __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,_.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}r.aborted?(cleanup(),a(c)):s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),G=`checkConcurrencyInterceptor`,we=new LogThrottle(Ce),Te=new LogThrottle(Ce),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:G,...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:G,...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,g.randomUUID)(),{provider:c,accountSecureId:l}=t,u=n?.rateLimits??xe,d=n?.concurrency??oe,f=await i.getDynamicMaxWaitTime(u,d,a.url),p=a._waitDeadlineAt,m=(0,o.isNumber)(p)&&Number.isFinite(p)?p:Date.now()+f*U,remainingBudgetMs=()=>Math.max(m-Date.now(),0),h=`${l}-${c}`,register=async()=>r.registerRequest(h,d,s,a.url,remainingBudgetMs(),a.signal),_=remainingBudgetMs()<=0,v;do{let t=await i.getWaitTime(h,u,a.url);if((0,o.isMissing)(t)){let t=we.consume(h);(0,o.notMissing)(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${c} - Account: ${l}, proceeding without a limit`,context:{interceptor:G,provider:c,accountSecureId:l,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){v=await register();break}if(remainingBudgetMs()<=0)break;let r=Math.min(Math.max(n,50),remainingBudgetMs());await W(r,a)}while(remainingBudgetMs()>0);if((0,o.isMissing)(v)){v=await register();let n={...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f,joinCondition:v?.joinCondition};if(_){let t=Te.consume(h);(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:m}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*U:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return!Number.isNaN(t)&&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*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]=(0,v.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,v.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)/U);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Se.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: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*U:(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 W(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=(0,o.isObject)(s)?(0,y.JSONPath)({path:f,json:s,wrap:!0}):[s],m=Array.isArray(p)?p[0]:void 0,h=testMessage(m,r);if(t===i&&h){let e=d??extractRetryAfter(a,l),t=convertRetryAfter(e,u);return{status:429,retryAfter:c??t}}}return{status:i,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(String(e??``)):typeof e==`string`||Array.isArray(e)?e.includes(t):!1,extractRetryAfter=(e,t)=>{if((0,o.notMissing)(t)&&(0,o.notMissing)(e)){let n=(0,y.JSONPath)({path:t,json:e,wrap:!0}),r=Array.isArray(n)?n[0]:void 0,i=Array.isArray(r)&&r.length===1?r[0]:r;return typeof i==`string`||typeof i==`number`?i:null}return 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)/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: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:K,...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:K,...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:K,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*U:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await W(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},q=`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:q,...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:q,...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:q,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:q,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},Ee=/* @__PURE__ */ new Set([`ECONNRESET`,`EPIPE`]),isResetOnReusedSocket=e=>{let t=e.request;return(0,o.isMissing)(e.response)&&Ee.has(e.code??``)&&(t?._currentRequest??t)?.reusedSocket===!0},De=[d.default.Agent,f.default.Agent,KeepAliveHttpsAgent],isRebuildable=e=>De.includes(e.constructor)&&!Object.prototype.hasOwnProperty.call(e,`createConnection`),unpooledCopy=(e,t)=>{let n=egressProxyOf(e);return(0,o.notMissing)(n)?tunnelThroughEgressProxy(new t({...e?.options,keepAlive:!1}),n):(0,o.isMissing)(e)||isRebuildable(e)?new t({...e?.options,keepAlive:!1}):e},withFreshConnection=e=>({...e,_staleSocketRetried:!0,httpAgent:unpooledCopy(e.httpAgent,d.default.Agent),httpsAgent:unpooledCopy(e.httpsAgent,f.default.Agent)}),withoutQuery=(e=``)=>(0,b.redactUrl)(e.split(`?`)[0]),staleSocketRetryInterceptor=({axiosInstance:e,logger:t,context:n})=>{let staleSocketRetryInterceptor=async r=>{let{config:i}=r;if((0,o.isMissing)(i)||!isResetOnReusedSocket(r))return Promise.reject(r);let a=(i.method??`get`).toUpperCase(),s=a===`GET`&&i._staleSocketRetried!==!0&&i.signal?.aborted!==!0&&(0,o.notMissing)(e);return t?.info({category:`http-transport`,message:`Provider closed a reused connection [${a} ${withoutQuery(i.url)}]: ${r.code}. ${s?`Retrying once on a new connection.`:`Not retried.`}`,context:{...n??{},method:a,errorCode:r.code,retried:s}}),s?e?.request(withFreshConnection(i)):Promise.reject(r)};return staleSocketRetryInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Oe=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ke=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],Ae=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],je=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{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=/* @__PURE__ */ 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 Me=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i,egressProxyUrl:a}={})=>{let s,{NODE_ENV:c}=process.env,l=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(s=l.includes(`RETRY`)?createDefaultRetryInstance(e,n,a):createDefaultInstance(e,n,a),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||c===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return s;let u=SingletonManager.getIfReady(RateLimitManager)??void 0,d=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=u?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(l.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(...Ae),h.push(...je)}let g=generateRequestKey(n),_=(0,o.notMissing)(g)&&(0,o.notMissing)(a)?`${g}|egress:${a}`:g;if((0,o.isMissing)(_))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)(s)}}),s;let v=await H.get(_);if((0,o.notMissing)(v))return v;let y={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:l.includes(`CONCURRENCY`)?{...ye,...i}:i,concurrencyManager:d,rateLimitManager:u,egressProxyUrl:a},b=HttpTransportFactory.createInstance(y);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${_}]`,context:{...n}}),await H.set(_,b,600),b}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(s)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=Me.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);(0,o.notMissing)(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);if((0,o.notMissing)(s))return s;if((0,o.notMissing)(a))throw t;return createAxiosInstance()}},createDefaultInstance=(e,t,n)=>{let r={instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createDefaultRetryInstance=(e,t,n)=>{let r={interceptors:{requestConfigs:Oe,responseConfigs:ke},instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createAxiosInstance=()=>h.default.create({maxBodyLength:1/0}),Ne=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,Ne);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,Ne,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),Pe=/^-?\d+$/,Fe=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&Pe.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!Fe.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},Ie=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return Ie.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=(0,b.redactFields)(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(/* @__PURE__ */ Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>(0,o.isMissing)(e)?void 0:{url:(0,b.redactUrl)(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!(0,h.isAxiosError)(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,(0,o.notMissing)(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof C.Readable&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},Le=/* @__PURE__ */ new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Le.has(e),toFailureCacheKey=e=>`${e}-error`,Re=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Re 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 h.AxiosError(e.message??`Request failed with status code ${e.status}`,h.AxiosError.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[Re]:!0})},egressCacheKeyPrefix=e=>`egress|${(0,x.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}|`,tunnelledRequestConfig=(e,{httpAgent:t,httpsAgent:n},r)=>{let i=e?.defaults,a=(0,o.notMissing)(t)?tunnelledCopyOf(t,r):i?.httpAgent,s=(0,o.notMissing)(n)?tunnelledCopyOf(n,r):i?.httpsAgent;if(egressProxyOf(a)!==r||egressProxyOf(s)!==r)throw new UntunnelledTransportError(`The transport for a client that tunnels through the egress proxy does not tunnel through it`);return{httpAgent:a,httpsAgent:s,proxy:!1,adapter:`http`}};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i,egressProxyUrl:a}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,a&&parseEgressProxyUrl(a),this.egressProxyUrl=a||void 0}#o(e){if(e&&this.egressProxyUrl)throw new ConflictingProxyError(`This client tunnels through the egress proxy, so a request cannot name a proxy of its own`);return this.egressProxyUrl}#s(e,t,n){let r=findEgressProxyError(e);if(!(0,o.isMissing)(r))throw this.#n?.warning({category:this.name,message:`Egress proxy did not carry [${t?.toUpperCase()} ${(0,b.redactUrl)(n)}]: ${r.message}.`,context:{status:r.status,proxyStatus:r.proxyStatus,proxyReason:r.proxyReason}}),r}#c({url:e,payload:t,method:n,context:r,egressProxyUrl:i}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?(0,o.getContentHash)(t):``;return`${i?egressCacheKeyPrefix(i):``}${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a}){if(!this.#a||!r||r<=0)return null;let o=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!o)return null;let s=await this.#a.getDataBatch([toFailureCacheKey(o),o]),c=s?.[0]??s?.[1]??null;return c?(this.#n?.debug({category:this.name,message:`Cache hit for key [${o}].`}),c):(this.#n?.debug({category:this.name,message:`Cache miss for key [${o}].`}),null)}async#u({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,response:o}){if(!this.#a||!r||r<=0)return!1;let s=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});return s?(this.#n?.debug({category:this.name,message:`Caching result for key [${s}].`}),this.#a.setData({key:s,value:o,cacheTTL:r*60})):!1}async#d(e){if(!(0,o.isMissing)(e))try{return(await V.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#f({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#p({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,error:s}){if(!this.#a||(0,o.isMissing)(r)||r<=0||!(0,h.isAxiosError)(s)||!isCacheableFailureStatus(s.response?.status))return!1;let c={data:s.response?.data,status:s.response?.status,headers:this.#h(s.response?.headers??{}),method:n,requestUrl:e,message:s.message,responseTime:/* @__PURE__ */ new Date},l=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!l)return!1;let u=toFailureCacheKey(l);return this.#n?.debug({category:this.name,message:`Caching ${c.status} for key [${u}].`}),this.#a.setData({key:u,value:c,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:h,timeoutMs:g,proxyUrl:_}){let v=await this.#d(u),y=this.#o(_);try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#C(t,r,i),b=this.#m(e),x=this.#b(d,e),S=await this.#l({url:u,payload:x,method:n,cacheTTL:c,context:l,egressProxyUrl:y});if(S){if(isCacheableFailureStatus(S.status))throw rebuildCachedFailure(S,n);return{...S,responseTime:/* @__PURE__ */ new Date}}let C=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:h,egressProxyUrl:y}),w=await C.request({headers:b,url:u,method:n,maxRedirects:a,responseType:s,data:x,...y?tunnelledRequestConfig(C,{httpAgent:p,httpsAgent:f},y):{httpsAgent:f,httpAgent:p},signal:v,...(0,o.notMissing)(g)&&{timeout:g},..._&&{proxy:buildProxyConfig(_)},transformResponse:e=>parseJsonExactly(e,s,this.#n)}),T={data:w.data,status:w.status,body:x,method:n,headers:this.#h(w.headers),requestHeaders:buildSafeRequestHeaders(b),requestUrl:u,responseType:w?.config?.responseType,responseTime:/* @__PURE__ */ new Date};return await this.#u({url:u,payload:x,method:n,cacheTTL:c,context:l,egressProxyUrl:y,response:T}),T}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#x(e);throw(0,o.notMissing)(t)?t:e}this.#s(a,n,t);let s=await toCallerSafeError(a);s.url=(0,b.redactUrl)(t),this.#f({signal:v,error:s,message:`Request error [${n?.toUpperCase()} ${s.url}]: ${s.message}.`}),await this.#p({url:this.#C(t,r,i),payload:this.#b(d,e),method:n,cacheTTL:c,context:l,egressProxyUrl:y,error:s});let u=this.#x(s);throw(0,o.notMissing)(u)?u:s}}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}){let h=await this.#d(c),g=this.#o(m);try{let o=this.#C(t,r,i),c=this.#m(e),_=this.#b(l,e),v=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p,egressProxyUrl:g}),y=await v.request({headers:c,url:o,method:n,maxRedirects:a,responseType:`stream`,data:_,...g?tunnelledRequestConfig(v,{httpAgent:d,httpsAgent:u},g):{httpsAgent:u,httpAgent:d},signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:y.status,headers:this.#h(y.headers),stream:y.data,requestUrl:t}}catch(e){this.#s(e,n,t);let r=await toCallerSafeError(e);r.url=(0,b.redactUrl)(t),this.#f({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#x(r);throw(0,o.notMissing)(i)?i:r}}#m(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#h(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#g(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#_(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#v(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#y(e){return Buffer.isBuffer(e)}#b(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#_(t)||this.#v(e)||this.#y(e)||typeof e==`string`?e:this.#g(t)?S.default.stringify(e):e}#x(e){if((0,h.isAxiosError)(e)&&this.#i)return this.#i(e)}#S(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#C(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.#S(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(S.default.stringify(r,l)),Object.keys(i).length>0&&u.push(S.default.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(S.default.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(s).length>0&&u.push(S.default.stringify(s,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(S.default.stringify(c,l));let d=u.join(`&`);return(0,o.notMissing)(d)?`${e}?${d}`:e}};const buildHttpClientInstance=(e,t,n,r)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n,egressProxyUrl:r});var HttpClientManager=class{static{this.httpClientInstances=/* @__PURE__ */ new Map}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance,egressProxyUrl:i}){let a=i||`direct`,o=this.httpClientInstances.get(a);if(o)return o;let s=r(e,t,n,i||void 0);if(i&&s.egressProxyUrl!==i)throw new UntunnelledTransportError(`The client built for the egress proxy does not tunnel through it`);return this.httpClientInstances.set(a,s),s}static resetInstance(){this.httpClientInstances.clear()}};const ze=[`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
@@ -7,7 +7,7 @@ import * as redis from "redis";
7
7
  import * as tls from "tls";
8
8
  import { Readable } from "node:stream";
9
9
  import { z } from "@stackone/utils";
10
- import { AuthorizationServerMetadata, Client, ClientOptions, FetchLike, OAuthProtectedResourceMetadata, OAuthServerInfo, StreamableHTTPClientTransportOptions, Transport } from "@modelcontextprotocol/client";
10
+ import { AuthorizationServerMetadata as AuthorizationServerMetadata$1, Client, ClientOptions, FetchLike, OAuthProtectedResourceMetadata, OAuthServerInfo, StreamableHTTPClientTransportOptions, Transport } from "@modelcontextprotocol/client";
11
11
  declare abstract class AsyncSingleton<T, O> {
12
12
  private instance;
13
13
  private initPromise;
@@ -909,10 +909,10 @@ type McpOAuthDiscoveryDependencies = {
909
909
  discoverResourceMetadata: (serverUrl: string, fetchFn?: FetchLike) => Promise<OAuthProtectedResourceMetadata>;
910
910
  discoverAuthorizationServerMetadata: (authorizationServerUrl: string, options: {
911
911
  fetchFn?: FetchLike;
912
- }) => Promise<AuthorizationServerMetadata | undefined>;
912
+ }) => Promise<AuthorizationServerMetadata$1 | undefined>;
913
913
  };
914
914
  export declare const isSameSiteIssuer: (expected: string | undefined, received: string | undefined) => boolean;
915
- export declare const discoverSameSiteAuthorizationServerMetadata: (authorizationServerUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<AuthorizationServerMetadata | undefined>;
915
+ export declare const discoverSameSiteAuthorizationServerMetadata: (authorizationServerUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<AuthorizationServerMetadata$1 | undefined>;
916
916
  export declare const discoverMcpOAuthServerInfo: (serverUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<OAuthServerInfo>;
917
917
  type McpServerProbe = {
918
918
  requiresAuthorization: boolean;
@@ -945,7 +945,7 @@ type ResourceMetadata = {
945
945
  resource_documentation?: string;
946
946
  authorization_servers?: string[];
947
947
  };
948
- type AuthorizationServerMetadata$1 = {
948
+ type AuthorizationServerMetadata = {
949
949
  registration_endpoint?: string;
950
950
  client_id_metadata_document_supported?: boolean;
951
951
  token_endpoint?: string;
@@ -957,7 +957,7 @@ type ProbeDependencies = {
957
957
  createClient: (serverUrl: string) => IMcpClient;
958
958
  fetchAuthorizationChallenge: (serverUrl: string) => Promise<AuthorizationChallenge | undefined>;
959
959
  discoverResourceMetadata: (serverUrl: string, resourceMetadataUrl?: string) => Promise<ResourceMetadata>;
960
- discoverAuthorizationServer: (authorizationServerUrl: string) => Promise<AuthorizationServerMetadata$1 | undefined>;
960
+ discoverAuthorizationServer: (authorizationServerUrl: string) => Promise<AuthorizationServerMetadata | undefined>;
961
961
  };
962
962
  export declare const mcpResourceIndicator: (serverUrl: string, advertisedResource?: string) => string;
963
963
  export declare const probeMcpServer: (serverUrl: string, dependencies?: ProbeDependencies) => Promise<McpServerProbe>;
package/dist/index.d.mts CHANGED
@@ -5,7 +5,7 @@ import http, { AgentOptions } from "node:http";
5
5
  import https from "node:https";
6
6
  import { AxiosError, AxiosInstance, AxiosInterceptorManager, AxiosInterceptorOptions, AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios";
7
7
  import { Readable } from "node:stream";
8
- import { AuthorizationServerMetadata, Client, ClientOptions, FetchLike, OAuthProtectedResourceMetadata, OAuthServerInfo, StreamableHTTPClientTransportOptions, Transport } from "@modelcontextprotocol/client";
8
+ import { AuthorizationServerMetadata as AuthorizationServerMetadata$1, Client, ClientOptions, FetchLike, OAuthProtectedResourceMetadata, OAuthServerInfo, StreamableHTTPClientTransportOptions, Transport } from "@modelcontextprotocol/client";
9
9
  import { ILogger } from "@stackone/logger";
10
10
  import * as tls from "tls";
11
11
  declare abstract class AsyncSingleton<T, O> {
@@ -909,10 +909,10 @@ type McpOAuthDiscoveryDependencies = {
909
909
  discoverResourceMetadata: (serverUrl: string, fetchFn?: FetchLike) => Promise<OAuthProtectedResourceMetadata>;
910
910
  discoverAuthorizationServerMetadata: (authorizationServerUrl: string, options: {
911
911
  fetchFn?: FetchLike;
912
- }) => Promise<AuthorizationServerMetadata | undefined>;
912
+ }) => Promise<AuthorizationServerMetadata$1 | undefined>;
913
913
  };
914
914
  export declare const isSameSiteIssuer: (expected: string | undefined, received: string | undefined) => boolean;
915
- export declare const discoverSameSiteAuthorizationServerMetadata: (authorizationServerUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<AuthorizationServerMetadata | undefined>;
915
+ export declare const discoverSameSiteAuthorizationServerMetadata: (authorizationServerUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<AuthorizationServerMetadata$1 | undefined>;
916
916
  export declare const discoverMcpOAuthServerInfo: (serverUrl: string, options?: McpOAuthDiscoveryOptions, dependencies?: McpOAuthDiscoveryDependencies) => Promise<OAuthServerInfo>;
917
917
  type McpServerProbe = {
918
918
  requiresAuthorization: boolean;
@@ -945,7 +945,7 @@ type ResourceMetadata = {
945
945
  resource_documentation?: string;
946
946
  authorization_servers?: string[];
947
947
  };
948
- type AuthorizationServerMetadata$1 = {
948
+ type AuthorizationServerMetadata = {
949
949
  registration_endpoint?: string;
950
950
  client_id_metadata_document_supported?: boolean;
951
951
  token_endpoint?: string;
@@ -957,7 +957,7 @@ type ProbeDependencies = {
957
957
  createClient: (serverUrl: string) => IMcpClient;
958
958
  fetchAuthorizationChallenge: (serverUrl: string) => Promise<AuthorizationChallenge | undefined>;
959
959
  discoverResourceMetadata: (serverUrl: string, resourceMetadataUrl?: string) => Promise<ResourceMetadata>;
960
- discoverAuthorizationServer: (authorizationServerUrl: string) => Promise<AuthorizationServerMetadata$1 | undefined>;
960
+ discoverAuthorizationServer: (authorizationServerUrl: string) => Promise<AuthorizationServerMetadata | undefined>;
961
961
  };
962
962
  export declare const mcpResourceIndicator: (serverUrl: string, advertisedResource?: string) => string;
963
963
  export declare const probeMcpServer: (serverUrl: string, dependencies?: ProbeDependencies) => Promise<McpServerProbe>;
package/dist/index.mjs CHANGED
@@ -94,7 +94,7 @@ import{t as e}from"./rolldown-runtime-BhWHdk3m.mjs";import{delay as t,exponentia
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=/* @__PURE__ */ new Map,this.setRemovalRegistry=/* @__PURE__ */ new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==`__keyevent@0__:expired`)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!==`__keyevent@0__:srem`)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)&&this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(`__keyevent@0__:set`)&&n.includes(`__keyevent@0__:expire`)&&n.includes(`__keyevent@0__:expired`)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=(n,r)=>{let i=setTimeout(()=>{let e=Date.now()-t;r(/* @__PURE__ */ Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4),checkCallback=()=>{clearTimeout(i);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)},subscribeAndTrigger=async()=>{let t=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(Ae.map(async n=>this.addTestSubscription(n,t,e,checkCallback)))).every(Boolean))throw Error(`Failed to subscribe to event channels.`);if(!await this.cacheClient?.setData({key:t,value:`test`,cacheTTL:1}))throw Error(`Failed to write the Redis test key.`)};subscribeAndTrigger().catch(e=>{clearTimeout(i),r(e)})};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(`__keyevent@0__:expired`,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(`__keyevent@0__:srem`,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=I*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(I,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 z={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=n?{...e,credentials:n}:e,a=x(r,i)===!0;if(s(r)||a){let n=t?.message,r;return r=s(n)?z[t.targetStatus]??`Unknown error`:String(x(n,e)??z[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=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.`}),Pe=`EgressProxyError`,Fe=/* @__PURE__ */ new Map([[407,{status:403,describe:e=>`The egress proxy refused the connection to ${e}`}],[429,{status:503,describe:e=>`The egress proxy was too busy to connect to ${e}`}],[502,{status:502,describe:e=>`The egress proxy could not reach ${e}`}],[504,{status:504,describe:e=>`${e} did not answer the egress proxy in time`}]]);var EgressProxyError=class extends Error{constructor(e,{status:t,proxyStatus:n,proxyReason:r,cause:i}){super(e),this.cause=i,this.name=Pe,this.status=t,this.proxyStatus=n,this.proxyReason=r}},ConflictingProxyError=class extends Error{constructor(...e){super(...e),this.name=`ConflictingProxyError`}},UntunnelledTransportError=class extends Error{constructor(...e){super(...e),this.name=`UntunnelledTransportError`}},InvalidEgressProxyUrlError=class extends Error{constructor(...e){super(...e),this.name=`InvalidEgressProxyUrlError`}};const isEgressProxyError=e=>e instanceof Error&&e.name===Pe&&typeof e.status==`number`,egressProxyRefusal=(e,t,n)=>{let r=Fe.get(e);return new EgressProxyError(r?.describe(t)??`The egress proxy answered ${e} when connecting to ${t}`,{status:r?.status??502,proxyStatus:e,proxyReason:n})},egressProxyUnavailable=(e,t)=>new EgressProxyError(`Could not reach the egress proxy to connect to ${e}`,{status:503,cause:t}),egressProxyTimedOut=e=>new EgressProxyError(`The egress proxy did not answer when connecting to ${e}`,{status:504}),causeChain=(e,t=/* @__PURE__ */ new Set)=>e instanceof Error&&!t.has(e)?[e,...causeChain(e.cause,/* @__PURE__ */ new Set([...t,e]))]:[],findEgressProxyError=e=>causeChain(e).reverse().find(isEgressProxyError),Ie=3e4,Le=Symbol(`egressProxyUrl`),authorityOf=(e,t)=>`${w(e)===6?`[${e}]`:e}:${t}`,onceOnly=e=>{let t={called:!1};return(n,r)=>{t.called||(t.called=!0,e(n,r))}},upgradeToTls=e=>{try{return T.connect(e)}catch(e){return e instanceof Error?e:Error(String(e))}},openTunnel=(e,t,n,r)=>{let i=d(t),a=n.host??`localhost`,o=Number(n.port??(i?443:80)),s=authorityOf(a,o),c=onceOnly(r),l=S.request({host:e.hostname.replace(/^\[|\]$/g,``),port:Number(e.port||80),method:`CONNECT`,path:s,headers:{host:s},agent:!1});l.setTimeout(Ie,()=>{l.destroy(egressProxyTimedOut(s))}),l.once(`connect`,(e,r,o)=>{if(r.setTimeout(0),e.statusCode!==200){r.destroy(),c(egressProxyRefusal(e.statusCode??0,s,e.headers[`x-smokescreen-error`]));return}if(o.length>0&&r.unshift(o),!i){c(null,r);return}let{path:l,...u}=n,d=upgradeToTls({...u,socket:r,secureContext:t,servername:n.servername||(w(a)?void 0:a)});d instanceof Error?(r.destroy(),c(d)):c(null,d)}),l.once(`error`,e=>{c(isEgressProxyError(e)?e:egressProxyUnavailable(s,e))}),l.end()},tunnelThroughEgressProxy=(e,t)=>{let n=parseEgressProxyUrl(t),r=e instanceof C.Agent,i=e;return i[Le]=t,i.createConnection=(e,t)=>{if(s(t))throw Error(`A tunnelled connection is only handed over through its callback`);let i=r?e.secureContext??T.createSecureContext(e):void 0;openTunnel(n,i,e,t)},i},parseEgressProxyUrl=e=>{let t=URL.canParse(e)?new URL(e):void 0;if(s(t)||t.protocol!==`http:`||t.username||t.password)throw new InvalidEgressProxyUrlError(`The egress proxy URL must be an http:// URL with no credentials`);return t},egressProxyOf=e=>e?.[Le],Re=/* @__PURE__ */ new WeakMap,tunnelledCopyOf=(e,t)=>{let n=Re.get(e);if(n&&egressProxyOf(n)===t)return n;let r=e.options,i=tunnelThroughEgressProxy(e instanceof C.Agent?new C.Agent(r):new S.Agent(r),t);return Re.set(e,i),i},ze=/Proxy response \((\d{3})\)/,Be=/* @__PURE__ */ new Set([`ECONNREFUSED`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOTFOUND`]),Ve={},loadUndici=()=>(Ve.loading??=import(`undici`),Ve.loading),proxyClientFactory=(e,t)=>(n,r)=>{let i=new e.Pool(n,r),a=i.connect.bind(i);return Object.assign(i,{connect:e=>{let n=AbortSignal.timeout(t),r=e.signal instanceof AbortSignal?AbortSignal.any([e.signal,n]):n;return a({...e,signal:r}).catch(t=>{throw n.aborted?egressProxyTimedOut(String(e.path)):t})}})},He=/* @__PURE__ */ new Map,proxyAgentFor=async(e,t)=>{let n=`${e}|${t}`,r=await loadUndici(),i=He.get(n)??new r.ProxyAgent({uri:e,clientFactory:proxyClientFactory(r,t)});return He.set(n,i),i},targetOf=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return`${n}:${r||(t===`https:`?443:80)}`},toEgressProxyError=(e,t)=>{let n=findEgressProxyError(e);if(n)return n;let r=causeChain(e),i=r.map(e=>ze.exec(e.message)?.[1]).find(e=>e!==void 0);if(i!==void 0)return egressProxyRefusal(Number(i),targetOf(t));let a=r.find(e=>Be.has(e.code??``));return a?egressProxyUnavailable(targetOf(t),a):void 0},createEgressProxyFetch=(e,{connectTimeoutMs:t=Ie}={})=>(parseEgressProxyUrl(e),async(n,r)=>{let{fetch:i}=await loadUndici();try{return await i(n,{...r,dispatcher:await proxyAgentFor(e,t)})}catch(e){throw toEgressProxyError(e,n)??e}});var B=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 Ue=[`client_disconnect`,`timeout`],We=`RequestAbortedError`,Ge={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(Ge[e]),this.name=We,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===We&&Ue.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=/* @__PURE__ */ 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)}},Ke=4e3,qe={keepAlive:!0,maxFreeSockets:8,scheduling:`lifo`};var KeepAliveHttpsAgent=class extends C.Agent{keepSocketAlive(e){let t=this.options.timeout===void 0;t&&(this.options.timeout=Ke);try{return super.keepSocketAlive(e)}finally{t&&delete this.options.timeout}}};const V=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:V,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:V,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:V,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s,egressProxyUrl:c}){let throughEgressProxy=e=>d(c)?tunnelThroughEgressProxy(e,c):e,l=throughEgressProxy(n?.keepAlive?new KeepAliveHttpsAgent(n):new C.Agent(n)),u=n?.keepAlive?throughEgressProxy(new C.Agent({...n,keepAlive:!1,maxSockets:1/0,maxTotalSockets:n.maxTotalSockets??n.maxSockets})):void 0,f=d(c)?throughEgressProxy(new S.Agent({keepAlive:!0,scheduling:`lifo`,timeout:Ke})):void 0,p=E.create({...t,httpsAgent:l,...d(f)&&{httpAgent:f,proxy:!1}});if(u){let sendOnOwnConnectionUnlessGet=e=>e.method===`get`||e.httpsAgent!==l?e:{...e,httpsAgent:u};p.interceptors.request.use(sendOnOwnConnectionUnlessGet)}if(p.close=()=>{let e={accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action};closeAgentWhenIdle(l,{logger:r,logContext:{...e,connections:`instance`}}),u&&closeAgentWhenIdle(u,{logger:r,logContext:{...e,connections:`nonGetRequests`}}),f&&closeAgentWhenIdle(f,{logger:r,logContext:{...e,connections:`egressHttp`}})},e){let t={axiosInstance:p,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(p,e,t)}return p}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}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},Je=6048e5;var 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({staleDataThreshold:Je,truncateThreshold:1e4,...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,slidingExpiration:!0,typeGuard:e=>d(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}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 Ye=H.getInstance(),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},Xe={mainRatelimit:25},U=1e3,Ze=/^\d+(\.\d+)?$/,Qe=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=/* @__PURE__ */ 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&&j(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}r.aborted?(cleanup(),a(c)):s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),G=`checkConcurrencyInterceptor`,$e=new LogThrottle(Qe),et=new LogThrottle(Qe),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=ee(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??Xe,p=n?.concurrency??je,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=$e.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;let r=Math.min(Math.max(n,50),remainingBudgetMs());await W(r,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=et.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)&&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]=te(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):ne(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(Ze.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=l(o)?re({path:f,json:o,wrap:!0}):[o],m=Array.isArray(p)?p[0]:void 0,h=testMessage(m,r);if(t===i&&h){let e=d??extractRetryAfter(a,c),t=convertRetryAfter(e,u);return{status:429,retryAfter:s??t}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(String(e??``)):typeof e==`string`||Array.isArray(e)?e.includes(t):!1,extractRetryAfter=(e,t)=>{if(d(t)&&d(e)){let n=re({path:t,json:e,wrap:!0}),r=Array.isArray(n)?n[0]:void 0,i=Array.isArray(r)&&r.length===1?r[0]:r;return typeof i==`string`||typeof i==`number`?i:null}return 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},tt=/* @__PURE__ */ new Set([`ECONNRESET`,`EPIPE`]),isResetOnReusedSocket=e=>{let t=e.request;return s(e.response)&&tt.has(e.code??``)&&(t?._currentRequest??t)?.reusedSocket===!0},nt=[S.Agent,C.Agent,KeepAliveHttpsAgent],isRebuildable=e=>nt.includes(e.constructor)&&!Object.prototype.hasOwnProperty.call(e,`createConnection`),unpooledCopy=(e,t)=>{let n=egressProxyOf(e);return d(n)?tunnelThroughEgressProxy(new t({...e?.options,keepAlive:!1}),n):s(e)||isRebuildable(e)?new t({...e?.options,keepAlive:!1}):e},withFreshConnection=e=>({...e,_staleSocketRetried:!0,httpAgent:unpooledCopy(e.httpAgent,S.Agent),httpsAgent:unpooledCopy(e.httpsAgent,C.Agent)}),withoutQuery=(e=``)=>M(e.split(`?`)[0]),staleSocketRetryInterceptor=({axiosInstance:e,logger:t,context:n})=>{let staleSocketRetryInterceptor=async r=>{let{config:i}=r;if(s(i)||!isResetOnReusedSocket(r))return Promise.reject(r);let a=(i.method??`get`).toUpperCase(),o=a===`GET`&&i._staleSocketRetried!==!0&&i.signal?.aborted!==!0&&d(e);return t?.info({category:`http-transport`,message:`Provider closed a reused connection [${a} ${withoutQuery(i.url)}]: ${r.code}. ${o?`Retrying once on a new connection.`:`Not retried.`}`,context:{...n??{},method:a,errorCode:r.code,retried:o}}),o?e?.request(withFreshConnection(i)):Promise.reject(r)};return staleSocketRetryInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),rt=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],it=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],at=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ot=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{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=/* @__PURE__ */ 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 st=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i,egressProxyUrl:a}={})=>{let o,{NODE_ENV:c}=process.env,l=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(o=l.includes(`RETRY`)?createDefaultRetryInstance(e,n,a):createDefaultInstance(e,n,a),s(n?.service)||s(n?.organizationId)||c===`test`||s(t)||s(e))return o;let u=SingletonManager.getIfReady(RateLimitManager)??void 0,f=SingletonManager.getIfReady(ConcurrencyManager)??void 0,p=u?.isReady(),m=f?.isRedisConfigured(),h=[],g=[];if(l.includes(`CONCURRENCY`)){if(!m)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!p)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);h.push(...at),g.push(...ot)}let _=generateRequestKey(n),v=d(_)&&d(a)?`${_}|egress:${a}`:_;if(s(v))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(o)}}),o;let y=await Ye.get(v);if(d(y))return y;let b={interceptors:{requestConfigs:h,responseConfigs:g},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:l.includes(`CONCURRENCY`)?{...qe,...i}:i,concurrencyManager:f,rateLimitManager:u,egressProxyUrl:a},x=HttpTransportFactory.createInstance(b);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${v}]`,context:{...n}}),await Ye.set(v,x,600),x}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(o)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=st.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);if(d(o))return o;if(d(a))throw t;return createAxiosInstance()}},createDefaultInstance=(e,t,n)=>{let r={instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createDefaultRetryInstance=(e,t,n)=>{let r={interceptors:{requestConfigs:rt,responseConfigs:it},instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createAxiosInstance=()=>E.create({maxBodyLength:1/0}),ct=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,ct);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,ct,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),lt=/^-?\d+$/,ut=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&lt.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!ut.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},dt=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return dt.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=ie(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(/* @__PURE__ */ Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>s(e)?void 0:{url:M(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!O(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,d(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof se&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},ft=/* @__PURE__ */ new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&ft.has(e),toFailureCacheKey=e=>`${e}-error`,pt=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&pt 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 D(e.message??`Request failed with status code ${e.status}`,D.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[pt]:!0})},egressCacheKeyPrefix=e=>`egress|${ae(`sha256`).update(e).digest(`hex`).slice(0,16)}|`,tunnelledRequestConfig=(e,{httpAgent:t,httpsAgent:n},r)=>{let i=e?.defaults,a=d(t)?tunnelledCopyOf(t,r):i?.httpAgent,o=d(n)?tunnelledCopyOf(n,r):i?.httpsAgent;if(egressProxyOf(a)!==r||egressProxyOf(o)!==r)throw new UntunnelledTransportError(`The transport for a client that tunnels through the egress proxy does not tunnel through it`);return{httpAgent:a,httpsAgent:o,proxy:!1,adapter:`http`}};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i,egressProxyUrl:a}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,a&&parseEgressProxyUrl(a),this.egressProxyUrl=a||void 0}#o(e){if(e&&this.egressProxyUrl)throw new ConflictingProxyError(`This client tunnels through the egress proxy, so a request cannot name a proxy of its own`);return this.egressProxyUrl}#s(e,t,n){let r=findEgressProxyError(e);if(!s(r))throw this.#n?.warning({category:this.name,message:`Egress proxy did not carry [${t?.toUpperCase()} ${M(n)}]: ${r.message}.`,context:{status:r.status,proxyStatus:r.proxyStatus,proxyReason:r.proxyReason}}),r}#c({url:e,payload:t,method:n,context:r,egressProxyUrl:a}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let o=t?i(t):``;return`${a?egressCacheKeyPrefix(a):``}${r.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a}){if(!this.#a||!r||r<=0)return null;let o=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!o)return null;let s=await this.#a.getDataBatch([toFailureCacheKey(o),o]),c=s?.[0]??s?.[1]??null;return c?(this.#n?.debug({category:this.name,message:`Cache hit for key [${o}].`}),c):(this.#n?.debug({category:this.name,message:`Cache miss for key [${o}].`}),null)}async#u({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,response:o}){if(!this.#a||!r||r<=0)return!1;let s=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});return s?(this.#n?.debug({category:this.name,message:`Caching result for key [${s}].`}),this.#a.setData({key:s,value:o,cacheTTL:r*60})):!1}async#d(e){if(!s(e))try{return(await H.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#f({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#p({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,error:o}){if(!this.#a||s(r)||r<=0||!O(o)||!isCacheableFailureStatus(o.response?.status))return!1;let c={data:o.response?.data,status:o.response?.status,headers:this.#h(o.response?.headers??{}),method:n,requestUrl:e,message:o.message,responseTime:/* @__PURE__ */ new Date},l=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!l)return!1;let u=toFailureCacheKey(l);return this.#n?.debug({category:this.name,message:`Caching ${c.status} for key [${u}].`}),this.#a.setData({key:u,value:c,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}){let y=await this.#d(u),b=this.#o(v);try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#C(t,r,i),x=this.#m(e),S=this.#b(f,e),C=await this.#l({url:u,payload:S,method:n,cacheTTL:c,context:l,egressProxyUrl:b});if(C){if(isCacheableFailureStatus(C.status))throw rebuildCachedFailure(C,n);return{...C,responseTime:/* @__PURE__ */ new Date}}let w=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g,egressProxyUrl:b}),T=await w.request({headers:x,url:u,method:n,maxRedirects:a,responseType:o,data:S,...b?tunnelledRequestConfig(w,{httpAgent:m,httpsAgent:p},b):{httpsAgent:p,httpAgent:m},signal:y,...d(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)},transformResponse:e=>parseJsonExactly(e,o,this.#n)}),E={data:T.data,status:T.status,body:S,method:n,headers:this.#h(T.headers),requestHeaders:buildSafeRequestHeaders(x),requestUrl:u,responseType:T?.config?.responseType,responseTime:/* @__PURE__ */ new Date};return await this.#u({url:u,payload:S,method:n,cacheTTL:c,context:l,egressProxyUrl:b,response:E}),E}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#x(e);throw d(t)?t:e}this.#s(a,n,t);let o=await toCallerSafeError(a);o.url=M(t),this.#f({signal:y,error:o,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`}),await this.#p({url:this.#C(t,r,i),payload:this.#b(f,e),method:n,cacheTTL:c,context:l,egressProxyUrl:b,error:o});let s=this.#x(o);throw d(s)?s:o}}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}){let h=await this.#d(s),g=this.#o(m);try{let s=this.#C(t,r,i),d=this.#m(e),_=this.#b(c,e),v=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p,egressProxyUrl:g}),y=await v.request({headers:d,url:s,method:n,maxRedirects:a,responseType:`stream`,data:_,...g?tunnelledRequestConfig(v,{httpAgent:u,httpsAgent:l},g):{httpsAgent:l,httpAgent:u},signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:y.status,headers:this.#h(y.headers),stream:y.data,requestUrl:t}}catch(e){this.#s(e,n,t);let r=await toCallerSafeError(e);r.url=M(t),this.#f({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#x(r);throw d(i)?i:r}}#m(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#h(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#g(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#_(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#v(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#y(e){return Buffer.isBuffer(e)}#b(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#_(t)||this.#v(e)||this.#y(e)||typeof e==`string`?e:this.#g(t)?N.stringify(e):e}#x(e){if(O(e)&&this.#i)return this.#i(e)}#S(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#C(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.#S(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(N.stringify(r,l)),Object.keys(i).length>0&&u.push(N.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(N.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(N.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(N.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n,r)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n,egressProxyUrl:r});var HttpClientManager=class{static{this.httpClientInstances=/* @__PURE__ */ new Map}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance,egressProxyUrl:i}){let a=i||`direct`,o=this.httpClientInstances.get(a);if(o)return o;let s=r(e,t,n,i||void 0);if(i&&s.egressProxyUrl!==i)throw new UntunnelledTransportError(`The client built for the egress proxy does not tunnel through it`);return this.httpClientInstances.set(a,s),s}static resetInstance(){this.httpClientInstances.clear()}};const mt=[`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=/* @__PURE__ */ new Map,this.setRemovalRegistry=/* @__PURE__ */ new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==`__keyevent@0__:expired`)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!==`__keyevent@0__:srem`)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)&&this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(`__keyevent@0__:set`)&&n.includes(`__keyevent@0__:expire`)&&n.includes(`__keyevent@0__:expired`)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=(n,r)=>{let i=setTimeout(()=>{let e=Date.now()-t;r(/* @__PURE__ */ Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4),checkCallback=()=>{clearTimeout(i);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)},subscribeAndTrigger=async()=>{let t=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(Ae.map(async n=>this.addTestSubscription(n,t,e,checkCallback)))).every(Boolean))throw Error(`Failed to subscribe to event channels.`);if(!await this.cacheClient?.setData({key:t,value:`test`,cacheTTL:1}))throw Error(`Failed to write the Redis test key.`)};subscribeAndTrigger().catch(e=>{clearTimeout(i),r(e)})};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(`__keyevent@0__:expired`,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??/* @__PURE__ */ new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(`__keyevent@0__:srem`,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=I*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(I,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 z={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=n?{...e,credentials:n}:e,a=x(r,i)===!0;if(s(r)||a){let n=t?.message,r;return r=s(n)?z[t.targetStatus]??`Unknown error`:String(x(n,e)??z[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=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.`}),Pe=`EgressProxyError`,Fe=/* @__PURE__ */ new Map([[407,{status:403,describe:e=>`The egress proxy refused the connection to ${e}`}],[429,{status:503,describe:e=>`The egress proxy was too busy to connect to ${e}`}],[502,{status:502,describe:e=>`The egress proxy could not reach ${e}`}],[504,{status:504,describe:e=>`${e} did not answer the egress proxy in time`}]]);var EgressProxyError=class extends Error{constructor(e,{status:t,proxyStatus:n,proxyReason:r,cause:i}){super(e),this.cause=i,this.name=Pe,this.status=t,this.proxyStatus=n,this.proxyReason=r}},ConflictingProxyError=class extends Error{constructor(...e){super(...e),this.name=`ConflictingProxyError`}},UntunnelledTransportError=class extends Error{constructor(...e){super(...e),this.name=`UntunnelledTransportError`}},InvalidEgressProxyUrlError=class extends Error{constructor(...e){super(...e),this.name=`InvalidEgressProxyUrlError`}};const isEgressProxyError=e=>e instanceof Error&&e.name===Pe&&typeof e.status==`number`,egressProxyRefusal=(e,t,n)=>{let r=Fe.get(e);return new EgressProxyError(r?.describe(t)??`The egress proxy answered ${e} when connecting to ${t}`,{status:r?.status??502,proxyStatus:e,proxyReason:n})},egressProxyUnavailable=(e,t)=>new EgressProxyError(`Could not reach the egress proxy to connect to ${e}`,{status:503,cause:t}),egressProxyTimedOut=e=>new EgressProxyError(`The egress proxy did not answer when connecting to ${e}`,{status:504}),causeChain=(e,t=/* @__PURE__ */ new Set)=>e instanceof Error&&!t.has(e)?[e,...causeChain(e.cause,/* @__PURE__ */ new Set([...t,e]))]:[],findEgressProxyError=e=>causeChain(e).reverse().find(isEgressProxyError),Ie=3e4,Le=Symbol(`egressProxyUrl`),authorityOf=(e,t)=>`${w(e)===6?`[${e}]`:e}:${t}`,onceOnly=e=>{let t={called:!1};return(n,r)=>{t.called||(t.called=!0,e(n,r))}},upgradeToTls=e=>{try{return T.connect(e)}catch(e){return e instanceof Error?e:Error(String(e))}},openTunnel=(e,t,n,r)=>{let i=d(t),a=n.host??`localhost`,o=Number(n.port??(i?443:80)),s=authorityOf(a,o),c=onceOnly(r),l=S.request({host:e.hostname.replace(/^\[|\]$/g,``),port:Number(e.port||80),method:`CONNECT`,path:s,headers:{host:s},agent:!1});l.setTimeout(Ie,()=>{l.destroy(egressProxyTimedOut(s))}),l.once(`connect`,(e,r,o)=>{if(r.setTimeout(0),e.statusCode!==200){r.destroy(),c(egressProxyRefusal(e.statusCode??0,s,e.headers[`x-smokescreen-error`]));return}if(o.length>0&&r.unshift(o),!i){c(null,r);return}let{path:l,...u}=n,d=upgradeToTls({...u,socket:r,secureContext:t,servername:n.servername||(w(a)?void 0:a)});d instanceof Error?(r.destroy(),c(d)):c(null,d)}),l.once(`error`,e=>{c(isEgressProxyError(e)?e:egressProxyUnavailable(s,e))}),l.end()},tunnelThroughEgressProxy=(e,t)=>{let n=parseEgressProxyUrl(t),r=e instanceof C.Agent,i=e;return i[Le]=t,i.createConnection=(e,t)=>{if(s(t))throw Error(`A tunnelled connection is only handed over through its callback`);let i=r?e.secureContext??T.createSecureContext(e):void 0;openTunnel(n,i,e,t)},i},parseEgressProxyUrl=e=>{let t=URL.canParse(e)?new URL(e):void 0;if(s(t)||t.protocol!==`http:`||t.username||t.password)throw new InvalidEgressProxyUrlError(`The egress proxy URL must be an http:// URL with no credentials`);return t},egressProxyOf=e=>e?.[Le],Re=/* @__PURE__ */ new WeakMap,tunnelledCopyOf=(e,t)=>{let n=Re.get(e);if(n&&egressProxyOf(n)===t)return n;let r=e.options,i=tunnelThroughEgressProxy(e instanceof C.Agent?new C.Agent(r):new S.Agent(r),t);return Re.set(e,i),i},ze=/Proxy response \((\d{3})\)/,Be=/* @__PURE__ */ new Set([`ECONNREFUSED`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOTFOUND`]),Ve={},loadUndici=()=>(Ve.loading??=import(`undici`),Ve.loading),proxyClientFactory=(e,t)=>(n,r)=>{let i=new e.Pool(n,r),a=i.connect.bind(i);return Object.assign(i,{connect:e=>{let n=AbortSignal.timeout(t),r=e.signal instanceof AbortSignal?AbortSignal.any([e.signal,n]):n;return a({...e,signal:r}).catch(t=>{throw n.aborted?egressProxyTimedOut(String(e.path)):t})}})},He=/* @__PURE__ */ new Map,proxyAgentFor=async(e,t)=>{let n=`${e}|${t}`,r=await loadUndici(),i=He.get(n)??new r.ProxyAgent({uri:e,proxyTunnel:!0,clientFactory:proxyClientFactory(r,t)});return He.set(n,i),i},targetOf=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return`${n}:${r||(t===`https:`?443:80)}`},toEgressProxyError=(e,t)=>{let n=findEgressProxyError(e);if(n)return n;let r=causeChain(e),i=r.map(e=>ze.exec(e.message)?.[1]).find(e=>e!==void 0);if(i!==void 0)return egressProxyRefusal(Number(i),targetOf(t));let a=r.find(e=>Be.has(e.code??``));return a?egressProxyUnavailable(targetOf(t),a):void 0},createEgressProxyFetch=(e,{connectTimeoutMs:t=Ie}={})=>(parseEgressProxyUrl(e),async(n,r)=>{let{fetch:i}=await loadUndici();try{return await i(n,{...r,dispatcher:await proxyAgentFor(e,t)})}catch(e){throw toEgressProxyError(e,n)??e}});var B=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 Ue=[`client_disconnect`,`timeout`],We=`RequestAbortedError`,Ge={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(Ge[e]),this.name=We,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===We&&Ue.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=/* @__PURE__ */ 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)}},Ke=4e3,qe={keepAlive:!0,maxFreeSockets:8,scheduling:`lifo`};var KeepAliveHttpsAgent=class extends C.Agent{keepSocketAlive(e){let t=this.options.timeout===void 0;t&&(this.options.timeout=Ke);try{return super.keepSocketAlive(e)}finally{t&&delete this.options.timeout}}};const V=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:V,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:V,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:V,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s,egressProxyUrl:c}){let throughEgressProxy=e=>d(c)?tunnelThroughEgressProxy(e,c):e,l=throughEgressProxy(n?.keepAlive?new KeepAliveHttpsAgent(n):new C.Agent(n)),u=n?.keepAlive?throughEgressProxy(new C.Agent({...n,keepAlive:!1,maxSockets:1/0,maxTotalSockets:n.maxTotalSockets??n.maxSockets})):void 0,f=d(c)?throughEgressProxy(new S.Agent({keepAlive:!0,scheduling:`lifo`,timeout:Ke})):void 0,p=E.create({...t,httpsAgent:l,...d(f)&&{httpAgent:f,proxy:!1}});if(u){let sendOnOwnConnectionUnlessGet=e=>e.method===`get`||e.httpsAgent!==l?e:{...e,httpsAgent:u};p.interceptors.request.use(sendOnOwnConnectionUnlessGet)}if(p.close=()=>{let e={accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action};closeAgentWhenIdle(l,{logger:r,logContext:{...e,connections:`instance`}}),u&&closeAgentWhenIdle(u,{logger:r,logContext:{...e,connections:`nonGetRequests`}}),f&&closeAgentWhenIdle(f,{logger:r,logContext:{...e,connections:`egressHttp`}})},e){let t={axiosInstance:p,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(p,e,t)}return p}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}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},Je=6048e5;var 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({staleDataThreshold:Je,truncateThreshold:1e4,...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,slidingExpiration:!0,typeGuard:e=>d(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}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 Ye=H.getInstance(),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},Xe={mainRatelimit:25},U=1e3,Ze=/^\d+(\.\d+)?$/,Qe=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=/* @__PURE__ */ 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&&j(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}r.aborted?(cleanup(),a(c)):s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),G=`checkConcurrencyInterceptor`,$e=new LogThrottle(Qe),et=new LogThrottle(Qe),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=ee(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??Xe,p=n?.concurrency??je,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=$e.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;let r=Math.min(Math.max(n,50),remainingBudgetMs());await W(r,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=et.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)&&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]=te(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):ne(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(Ze.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=l(o)?re({path:f,json:o,wrap:!0}):[o],m=Array.isArray(p)?p[0]:void 0,h=testMessage(m,r);if(t===i&&h){let e=d??extractRetryAfter(a,c),t=convertRetryAfter(e,u);return{status:429,retryAfter:s??t}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(String(e??``)):typeof e==`string`||Array.isArray(e)?e.includes(t):!1,extractRetryAfter=(e,t)=>{if(d(t)&&d(e)){let n=re({path:t,json:e,wrap:!0}),r=Array.isArray(n)?n[0]:void 0,i=Array.isArray(r)&&r.length===1?r[0]:r;return typeof i==`string`||typeof i==`number`?i:null}return 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},tt=/* @__PURE__ */ new Set([`ECONNRESET`,`EPIPE`]),isResetOnReusedSocket=e=>{let t=e.request;return s(e.response)&&tt.has(e.code??``)&&(t?._currentRequest??t)?.reusedSocket===!0},nt=[S.Agent,C.Agent,KeepAliveHttpsAgent],isRebuildable=e=>nt.includes(e.constructor)&&!Object.prototype.hasOwnProperty.call(e,`createConnection`),unpooledCopy=(e,t)=>{let n=egressProxyOf(e);return d(n)?tunnelThroughEgressProxy(new t({...e?.options,keepAlive:!1}),n):s(e)||isRebuildable(e)?new t({...e?.options,keepAlive:!1}):e},withFreshConnection=e=>({...e,_staleSocketRetried:!0,httpAgent:unpooledCopy(e.httpAgent,S.Agent),httpsAgent:unpooledCopy(e.httpsAgent,C.Agent)}),withoutQuery=(e=``)=>M(e.split(`?`)[0]),staleSocketRetryInterceptor=({axiosInstance:e,logger:t,context:n})=>{let staleSocketRetryInterceptor=async r=>{let{config:i}=r;if(s(i)||!isResetOnReusedSocket(r))return Promise.reject(r);let a=(i.method??`get`).toUpperCase(),o=a===`GET`&&i._staleSocketRetried!==!0&&i.signal?.aborted!==!0&&d(e);return t?.info({category:`http-transport`,message:`Provider closed a reused connection [${a} ${withoutQuery(i.url)}]: ${r.code}. ${o?`Retrying once on a new connection.`:`Not retried.`}`,context:{...n??{},method:a,errorCode:r.code,retried:o}}),o?e?.request(withFreshConnection(i)):Promise.reject(r)};return staleSocketRetryInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),rt=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],it=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],at=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ot=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{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=/* @__PURE__ */ 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 st=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i,egressProxyUrl:a}={})=>{let o,{NODE_ENV:c}=process.env,l=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(o=l.includes(`RETRY`)?createDefaultRetryInstance(e,n,a):createDefaultInstance(e,n,a),s(n?.service)||s(n?.organizationId)||c===`test`||s(t)||s(e))return o;let u=SingletonManager.getIfReady(RateLimitManager)??void 0,f=SingletonManager.getIfReady(ConcurrencyManager)??void 0,p=u?.isReady(),m=f?.isRedisConfigured(),h=[],g=[];if(l.includes(`CONCURRENCY`)){if(!m)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!p)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);h.push(...at),g.push(...ot)}let _=generateRequestKey(n),v=d(_)&&d(a)?`${_}|egress:${a}`:_;if(s(v))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(o)}}),o;let y=await Ye.get(v);if(d(y))return y;let b={interceptors:{requestConfigs:h,responseConfigs:g},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:l.includes(`CONCURRENCY`)?{...qe,...i}:i,concurrencyManager:f,rateLimitManager:u,egressProxyUrl:a},x=HttpTransportFactory.createInstance(b);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${v}]`,context:{...n}}),await Ye.set(v,x,600),x}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(o)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=st.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);if(d(o))return o;if(d(a))throw t;return createAxiosInstance()}},createDefaultInstance=(e,t,n)=>{let r={instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createDefaultRetryInstance=(e,t,n)=>{let r={interceptors:{requestConfigs:rt,responseConfigs:it},instanceConfig:{maxBodyLength:1/0},logger:e,context:t,egressProxyUrl:n};return HttpTransportFactory.createInstance(r)??createAxiosInstance()},createAxiosInstance=()=>E.create({maxBodyLength:1/0}),ct=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,ct);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,ct,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),lt=/^-?\d+$/,ut=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&lt.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!ut.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},dt=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return dt.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=ie(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(/* @__PURE__ */ Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>s(e)?void 0:{url:M(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!O(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,d(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof se&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},ft=/* @__PURE__ */ new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&ft.has(e),toFailureCacheKey=e=>`${e}-error`,pt=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&pt 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 D(e.message??`Request failed with status code ${e.status}`,D.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[pt]:!0})},egressCacheKeyPrefix=e=>`egress|${ae(`sha256`).update(e).digest(`hex`).slice(0,16)}|`,tunnelledRequestConfig=(e,{httpAgent:t,httpsAgent:n},r)=>{let i=e?.defaults,a=d(t)?tunnelledCopyOf(t,r):i?.httpAgent,o=d(n)?tunnelledCopyOf(n,r):i?.httpsAgent;if(egressProxyOf(a)!==r||egressProxyOf(o)!==r)throw new UntunnelledTransportError(`The transport for a client that tunnels through the egress proxy does not tunnel through it`);return{httpAgent:a,httpsAgent:o,proxy:!1,adapter:`http`}};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i,egressProxyUrl:a}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,a&&parseEgressProxyUrl(a),this.egressProxyUrl=a||void 0}#o(e){if(e&&this.egressProxyUrl)throw new ConflictingProxyError(`This client tunnels through the egress proxy, so a request cannot name a proxy of its own`);return this.egressProxyUrl}#s(e,t,n){let r=findEgressProxyError(e);if(!s(r))throw this.#n?.warning({category:this.name,message:`Egress proxy did not carry [${t?.toUpperCase()} ${M(n)}]: ${r.message}.`,context:{status:r.status,proxyStatus:r.proxyStatus,proxyReason:r.proxyReason}}),r}#c({url:e,payload:t,method:n,context:r,egressProxyUrl:a}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let o=t?i(t):``;return`${a?egressCacheKeyPrefix(a):``}${r.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#l({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a}){if(!this.#a||!r||r<=0)return null;let o=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!o)return null;let s=await this.#a.getDataBatch([toFailureCacheKey(o),o]),c=s?.[0]??s?.[1]??null;return c?(this.#n?.debug({category:this.name,message:`Cache hit for key [${o}].`}),c):(this.#n?.debug({category:this.name,message:`Cache miss for key [${o}].`}),null)}async#u({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,response:o}){if(!this.#a||!r||r<=0)return!1;let s=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});return s?(this.#n?.debug({category:this.name,message:`Caching result for key [${s}].`}),this.#a.setData({key:s,value:o,cacheTTL:r*60})):!1}async#d(e){if(!s(e))try{return(await H.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#f({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#p({url:e,payload:t,method:n,cacheTTL:r,context:i,egressProxyUrl:a,error:o}){if(!this.#a||s(r)||r<=0||!O(o)||!isCacheableFailureStatus(o.response?.status))return!1;let c={data:o.response?.data,status:o.response?.status,headers:this.#h(o.response?.headers??{}),method:n,requestUrl:e,message:o.message,responseTime:/* @__PURE__ */ new Date},l=this.#c({url:e,payload:t,method:n,context:i,egressProxyUrl:a});if(!l)return!1;let u=toFailureCacheKey(l);return this.#n?.debug({category:this.name,message:`Caching ${c.status} for key [${u}].`}),this.#a.setData({key:u,value:c,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}){let y=await this.#d(u),b=this.#o(v);try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#C(t,r,i),x=this.#m(e),S=this.#b(f,e),C=await this.#l({url:u,payload:S,method:n,cacheTTL:c,context:l,egressProxyUrl:b});if(C){if(isCacheableFailureStatus(C.status))throw rebuildCachedFailure(C,n);return{...C,responseTime:/* @__PURE__ */ new Date}}let w=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g,egressProxyUrl:b}),T=await w.request({headers:x,url:u,method:n,maxRedirects:a,responseType:o,data:S,...b?tunnelledRequestConfig(w,{httpAgent:m,httpsAgent:p},b):{httpsAgent:p,httpAgent:m},signal:y,...d(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)},transformResponse:e=>parseJsonExactly(e,o,this.#n)}),E={data:T.data,status:T.status,body:S,method:n,headers:this.#h(T.headers),requestHeaders:buildSafeRequestHeaders(x),requestUrl:u,responseType:T?.config?.responseType,responseTime:/* @__PURE__ */ new Date};return await this.#u({url:u,payload:S,method:n,cacheTTL:c,context:l,egressProxyUrl:b,response:E}),E}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#x(e);throw d(t)?t:e}this.#s(a,n,t);let o=await toCallerSafeError(a);o.url=M(t),this.#f({signal:y,error:o,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`}),await this.#p({url:this.#C(t,r,i),payload:this.#b(f,e),method:n,cacheTTL:c,context:l,egressProxyUrl:b,error:o});let s=this.#x(o);throw d(s)?s:o}}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}){let h=await this.#d(s),g=this.#o(m);try{let s=this.#C(t,r,i),d=this.#m(e),_=this.#b(c,e),v=await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p,egressProxyUrl:g}),y=await v.request({headers:d,url:s,method:n,maxRedirects:a,responseType:`stream`,data:_,...g?tunnelledRequestConfig(v,{httpAgent:u,httpsAgent:l},g):{httpsAgent:l,httpAgent:u},signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:y.status,headers:this.#h(y.headers),stream:y.data,requestUrl:t}}catch(e){this.#s(e,n,t);let r=await toCallerSafeError(e);r.url=M(t),this.#f({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#x(r);throw d(i)?i:r}}#m(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#h(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#g(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#_(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#v(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#y(e){return Buffer.isBuffer(e)}#b(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#_(t)||this.#v(e)||this.#y(e)||typeof e==`string`?e:this.#g(t)?N.stringify(e):e}#x(e){if(O(e)&&this.#i)return this.#i(e)}#S(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#C(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.#S(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(N.stringify(r,l)),Object.keys(i).length>0&&u.push(N.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(N.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(N.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(N.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n,r)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n,egressProxyUrl:r});var HttpClientManager=class{static{this.httpClientInstances=/* @__PURE__ */ new Map}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance,egressProxyUrl:i}){let a=i||`direct`,o=this.httpClientInstances.get(a);if(o)return o;let s=r(e,t,n,i||void 0);if(i&&s.egressProxyUrl!==i)throw new UntunnelledTransportError(`The client built for the egress proxy does not tunnel through it`);return this.httpClientInstances.set(a,s),s}static resetInstance(){this.httpClientInstances.clear()}};const mt=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
98
98
  `).replace(/\r\n/g,`
99
99
  `).replace(/\r/g,`
100
100
  `).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.44.0",
3
+ "version": "2.45.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -27,14 +27,14 @@
27
27
  "@stackone/logger": "*",
28
28
  "@stackone/redaction": "*",
29
29
  "@stackone/utils": "*",
30
- "axios": "1.21.0",
31
- "fast-xml-parser": "5.12.0",
30
+ "axios": "1.21.1",
31
+ "fast-xml-parser": "5.12.1",
32
32
  "jsonpath-plus": "11.3.0",
33
33
  "mathjs": "15.2.0",
34
34
  "qs": "6.17.1",
35
35
  "redis": "6.3.1",
36
- "tldts": "7.4.19",
37
- "undici": "7.30.2"
36
+ "tldts": "7.5.4",
37
+ "undici": "8.12.4"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@redis/client": "6.3.1"