axios-retryer
Version:
TypeScript-first Axios retry library with concurrency limits, request priority, token refresh, response caching, and circuit breaker plugins.
1 lines • 71.6 kB
JavaScript
"use strict";var e=require("axios");const t="GET",r=new Set(["retryAttempt","requestRetries","requestMode","requestId","correlationId","isRetrying","priority","timestamp","backoffType","retryableStatuses","extra","isRetryRefreshRequest","manualReplayAttempt","retryAfterMs","silentlyCancelled","cachingOptions"]);function s(e){return r.has(e)&&"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}function i(e){const t={};if(Object.defineProperty(t,"toJSON",{value:()=>{},enumerable:!1,writable:!1,configurable:!1}),e)for(const r of Object.keys(e))s(r)&&(t[r]=e[r]);return t}function n(e){const t=e;return t.__axiosRetryer?"function"!=typeof t.__axiosRetryer.toJSON&&(t.__axiosRetryer=i(t.__axiosRetryer)):t.__axiosRetryer=i(),t.__axiosRetryer}function o(e){if(e)return e.__axiosRetryer}function a(e,t,r){const s=n(e);return void 0===r?delete s[t]:s[t]=r,s}function c(e,t){const r=n(e);for(const e of Object.keys(t)){if(!s(e))continue;const i=t[e];void 0===i?delete r[e]:r[e]=i}return r}class u extends Error{constructor(){super("URL is required for cache key generation"),this.name="InvalidCacheKeyError"}}class l extends Error{constructor(e,t){super(e),this.name=new.target.name,this.code=t,Object.setPrototypeOf(this,new.target.prototype)}}class h extends l{constructor(e,t,r){super(e,"EINVALID_CONFIG"),this.optionName=t,this.optionValue=r}}class d{constructor(){this.storage=new Map}get(e){return this.storage.get(e)}set(e,t){this.storage.set(e,t)}delete(e){this.storage.delete(e)}clear(){this.storage.clear()}entries(){return Array.from(this.storage,([e,t])=>({key:e,value:t}))}}function p(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return`fp_${(t>>>0).toString(16).padStart(8,"0")}`}function f([e,t],[r,s]){return e.localeCompare(r)||t.localeCompare(s)}function g(e){const t=e.indexOf("#"),r=-1===t?e:e.slice(0,t),s=r.indexOf("?");if(-1===s)return r;const i=r.slice(0,s),n=r.slice(s+1);if(!n)return i;const o=Array.from(new URLSearchParams(n).entries()).sort(f);return 0===o.length?i:`${i}?${o.map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&")}`}function m(e,t=!1){if(void 0!==e){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Date)return e.toISOString();if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return Array.from(e.entries()).sort(f);if(e instanceof Map)return Array.from(e.entries()).map(([e,r])=>[String(e),m(r,t)]).sort(([e],[t])=>e.localeCompare(t));if(e instanceof Set)return Array.from(e.values()).map(e=>m(e,t));if(Array.isArray(e))return e.map(e=>m(e,t));if("object"==typeof e){const r="function"==typeof e.toJSON?e.toJSON():e;if(r!==e)return m(r,t);const s={};return Object.entries(r).map(([e,r])=>[t?e.toLowerCase():e,m(r,t)]).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,t])=>{s[e]=t}),s}return String(e)}}function y(e,t=!1){if(null==e)return"";if("string"==typeof e){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.stringify(m(JSON.parse(r),t))}catch(e){}return e}return"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(m(e,t))}function v(e){return[e.method,e.normalizedUrl,e.normalizedParams,e.normalizedData,e.normalizedHeaders].join("|")}function R(e){return e instanceof RegExp?{type:"regexp",fingerprint:p(String(e))}:"string"==typeof e?{type:"exact",fingerprint:p(e)}:{type:"exact"in e?"exact":"prefix",fingerprint:p("exact"in e?e.exact:e.prefix)}}const w=new Set(["authorization","proxy-authorization","cookie","x-auth-token","x-api-key"]);function S(e){if(!e.headers)return!1;const t=e.headers;for(const e of Object.keys(t))if(w.has(e.toLowerCase()))return!0;return!1}function C(e){return!!e&&"function"==typeof e.then}function x(e){return e instanceof Error?{errorName:e.name}:{}}function k(e){var t;return null!==(t=e.lastAccessedAt)&&void 0!==t?t:e.timestamp}function E(e){return[...e].sort((e,t)=>k(e.value)-k(t.value)||e.key.localeCompare(t.key))}function T(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return new URLSearchParams(e.toString());if("undefined"!=typeof ArrayBuffer){if(e instanceof ArrayBuffer)return e.slice(0);if(ArrayBuffer.isView(e))return function(e){const t="undefined"!=typeof globalThis?globalThis.Buffer:void 0;return(null==t?void 0:t.isBuffer(e))?t.from(e):e instanceof DataView?new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)):"function"==typeof e.slice?e.slice():new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}(e)}if("undefined"!=typeof Blob&&e instanceof Blob)return e.slice(0,e.size,e.type);const r=t.get(e);if(void 0!==r)return r;if(Array.isArray(e)){const r=[];return t.set(e,r),e.forEach((e,s)=>{r[s]=T(e,t)}),r}if(e instanceof Map){const r=new Map;return t.set(e,r),e.forEach((e,s)=>{r.set(T(s,t),T(e,t))}),r}if(e instanceof Set){const r=new Set;return t.set(e,r),e.forEach(e=>{r.add(T(e,t))}),r}let s=e;if(function(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toJSON}(e))try{s=e.toJSON()}catch{}if(s!==e)return T(s,t);const i=Object.getPrototypeOf(e),n=Object.create(null===i?null:i);return t.set(e,n),Reflect.ownKeys(e).forEach(r=>{const s=Object.getOwnPropertyDescriptor(e,r);(null==s?void 0:s.enumerable)&&(n[r]=T(e[r],t))}),n}function b(e){if("function"==typeof structuredClone)try{return structuredClone(e)}catch(e){}return T(e)}function A(e,t){const r=b(e.headers);if(t.length>0){const e=new Set(t.map(e=>e.toLowerCase()));for(const t of Object.keys(r))e.has(t.toLowerCase())&&delete r[t]}return{config:{},data:b(e.data),headers:r,status:e.status,statusText:e.statusText}}function q(e,t){return{config:t,data:b(e.data),headers:b(e.headers),status:e.status,statusText:e.statusText}}class _{constructor(e){this.options=e,this.timer=null,this.consecutiveFailures=0}start(){this.timer||this.options.intervalMs<=0||(this.timer=setInterval(()=>this.runOnce(),this.options.intervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}get consecutiveFailureCount(){return this.consecutiveFailures}runOnce(){let e;const t=new Promise((t,r)=>{e=setTimeout(()=>r(new Error(`Cache cleanup exceeded ${this.options.timeoutMs} ms timeout`)),this.options.timeoutMs)});Promise.race([this.options.runCleanup(),t]).then(()=>{this.consecutiveFailures=0}).catch(e=>{var t,r;this.consecutiveFailures+=1,null===(t=this.options.getLogger())||void 0===t||t.warn("[CachingPlugin] Failed to run cache cleanup",{...x(e),consecutiveFailures:this.consecutiveFailures}),this.consecutiveFailures>=this.options.disableAfterFailures&&(null===(r=this.options.getLogger())||void 0===r||r.error("[CachingPlugin] Disabling cleanup after repeated failures",{consecutiveFailures:this.consecutiveFailures}),this.stop())}).finally(()=>{void 0!==e&&clearTimeout(e)})}}class M{constructor(e){this.options=e,this.inflightRequests=new Map,this.inflightLeaders=new Map,this.inflightFollowers=new Map,this.servedFromCache=new Set,this.trackingIdFallback=new WeakMap}getOrAssignTrackingId(e){var t,r;const s=null===(t=o(e))||void 0===t?void 0:t.requestId;if(s)return s;let i=this.trackingIdFallback.get(e);return i||(i=`ct_${Math.random().toString(36).slice(2)}`,this.trackingIdFallback.set(e,i),null===(r=this.options.getLogger())||void 0===r||r.warn("[CachingPlugin] Request lacks requestId; falling back to WeakMap-keyed tracking id. Register CachingPlugin AFTER any plugin that mutates the request config.")),i}peekInflight(e){return this.inflightRequests.get(e)}registerLeader(e,t){const r=function(){let e,t;const r=new Promise((r,s)=>{e=r,t=s});return r.catch(()=>{}),{promise:r,resolve:e,reject:t}}();return this.inflightRequests.set(t,r),this.inflightLeaders.set(this.getOrAssignTrackingId(e),t),r}registerFollower(e,t){this.inflightFollowers.set(this.getOrAssignTrackingId(e),t)}consumeFollower(e){if(!e)return!1;const t=this.getOrAssignTrackingId(e);return!!this.inflightFollowers.has(t)&&(this.inflightFollowers.delete(t),!0)}clearFollower(e){this.inflightFollowers.delete(this.getOrAssignTrackingId(e))}markServedFromCache(e){this.servedFromCache.add(this.getOrAssignTrackingId(e))}consumeServedFromCache(e){if(!e)return!1;const t=this.getOrAssignTrackingId(e);return!!this.servedFromCache.has(t)&&(this.servedFromCache.delete(t),!0)}resolve(e,t){if(!e)return;const r=this.getOrAssignTrackingId(e),s=this.inflightLeaders.get(r);if(!s)return;const i=this.inflightRequests.get(s);i&&(i.resolve(t),this.inflightRequests.delete(s)),this.inflightLeaders.delete(r)}reject(e,t){const r=this.getOrAssignTrackingId(e),s=this.inflightLeaders.get(r);if(!s)return;const i=this.inflightRequests.get(s);i&&(i.reject(t),this.inflightRequests.delete(s)),this.inflightLeaders.delete(r)}clearInflightOnly(){this.inflightRequests.clear()}clearAll(){this.inflightRequests.clear(),this.inflightLeaders.clear(),this.inflightFollowers.clear(),this.servedFromCache.clear()}}class I{constructor(e){this.name="CachingPlugin",this.version="1.0.0",this.interceptorIdReq=null,this.interceptorIdRes=null,this.cache=new Map,this.options=function(e){var r,s;return{sensitiveResponseHeaders:["set-cookie"],compareHeaders:!1,timeToRevalidate:0,cacheMethods:[t],cleanupInterval:0,maxAge:0,maxItems:1e3,maxEntrySize:0,cacheOnlyRetriedRequests:!1,storage:null!==(r=null==e?void 0:e.storage)&&void 0!==r?r:new d,dedupeConcurrentRequests:!0,cacheKeyBuilder:null!==(s=null==e?void 0:e.cacheKeyBuilder)&&void 0!==s?s:v,skipWhenAuthPresent:!0,varyHeaders:[],...e}}(e),this.storage=this.options.storage,function(e){if(!Number.isInteger(e.cleanupInterval)||e.cleanupInterval<0)throw new h("cleanupInterval must be a non-negative integer","cleanupInterval",e.cleanupInterval);if(!Number.isInteger(e.maxAge)||e.maxAge<0)throw new h("maxAge must be a non-negative integer","maxAge",e.maxAge);if(!Number.isInteger(e.maxItems)||e.maxItems<0)throw new h("maxItems must be a non-negative integer","maxItems",e.maxItems);if(!Number.isInteger(e.maxEntrySize)||e.maxEntrySize<0)throw new h("maxEntrySize must be a non-negative integer","maxEntrySize",e.maxEntrySize);if(!Number.isInteger(e.timeToRevalidate)||e.timeToRevalidate<0)throw new h("timeToRevalidate must be a non-negative integer","timeToRevalidate",e.timeToRevalidate)}(this.options);const r=()=>{var e,t;return null!==(t=null===(e=this.context)||void 0===e?void 0:e.getLogger())&&void 0!==t?t:null};this.inflight=new M({getLogger:r}),this.cleanup=new _({intervalMs:this.options.cleanupInterval,timeoutMs:I.CACHE_CLEANUP_TIMEOUT_MS,disableAfterFailures:I.CACHE_CLEANUP_DISABLE_AFTER,runCleanup:()=>this.runCacheCleanup(),getLogger:r})}initialize(e){this.context=e;const t=e.axiosInstance;this.interceptorIdReq=t.interceptors.request.use(e=>this.handleRequest(e),e=>Promise.reject(e)),this.interceptorIdRes=t.interceptors.response.use(e=>this.handleResponseSuccess(e),e=>this.handleResponseError(e)),this.options.cleanupInterval>0&&this.cleanup.start()}onBeforeDestroyed(){null!==this.interceptorIdReq&&this.context.axiosInstance.interceptors.request.eject(this.interceptorIdReq),null!==this.interceptorIdRes&&this.context.axiosInstance.interceptors.response.eject(this.interceptorIdRes),this.cleanup.stop(),this.inflight.clearAll()}getCacheKeyFingerprint(e){return p(e)}async handleRequest(e){var r,s,i,o,a,c,u;const l=n(e),h=this.getRequestCachingOptions(e),d=(e.method||t).toUpperCase();if(h&&(l.cachingOptions=h),!1===(null==h?void 0:h.cache))return null===(r=this.context.getLogger())||void 0===r||r.debug("[CachingPlugin] Skipping cache for request (explicitly disabled)"),e;if(this.options.skipWhenAuthPresent&&S(e))return null===(s=this.context.getLogger())||void 0===s||s.debug("[CachingPlugin] Skipping cache for authenticated request"),e;if(!0!==(null==h?void 0:h.cache)&&!this.options.cacheMethods.includes(d))return e;if(this.options.cacheOnlyRetriedRequests&&!l.isRetrying)return e;const p=this.buildCacheKey(e),f=this.getCacheKeyFingerprint(p);let g=this.cache.get(p);if(!g)try{g=await this.storage.get(p)}catch(t){return null===(i=this.context.getLogger())||void 0===i||i.warn("[CachingPlugin] Failed to read cache entry",{cacheKeyFingerprint:f,...x(t)}),e}if(g){const t=Date.now(),r=t-g.timestamp,s=null!==(o=g.ttr)&&void 0!==o?o:this.options.timeToRevalidate;if(0===s||r<s){const s=this.touchCacheEntry(p,g,t);return await this.persistCacheTouchIfNeeded(p,s,f),null===(a=this.context.getLogger())||void 0===a||a.debug("[CachingPlugin] Cache hit",{cacheKeyFingerprint:f,ageMs:r}),this.context.triggerAndEmit("onCacheHit",{keyFingerprint:f,config:e,ageMs:r}),this.inflight.markServedFromCache(e),{...e,adapter:()=>Promise.resolve(q(s.response,e))}}null===(c=this.context.getLogger())||void 0===c||c.debug("[CachingPlugin] Cache stale",{cacheKeyFingerprint:f,ageMs:r}),this.context.triggerAndEmit("onCacheMiss",{keyFingerprint:f,config:e,reason:"stale"}),await this.deleteCacheEntry(p)}else this.context.triggerAndEmit("onCacheMiss",{keyFingerprint:f,config:e,reason:"empty"});if(!this.options.dedupeConcurrentRequests)return e;const m=this.inflight.peekInflight(p);return m?(this.inflight.registerFollower(e,p),null===(u=this.context.getLogger())||void 0===u||u.debug("[CachingPlugin] Piggybacking on in-flight request",{cacheKeyFingerprint:f}),{...e,adapter:async()=>q(await m.promise,e)}):(this.inflight.registerLeader(e,p),e)}async handleResponseSuccess(e){var r,s,i,n,a,c;const u=e.config?o(e.config):void 0;if(this.inflight.consumeFollower(e.config))return e;if(this.inflight.consumeServedFromCache(e.config))return e;const l=this.getRequestCachingOptions(e.config);if(!1===(null==l?void 0:l.cache))return this.inflight.resolve(e.config,e),e;if(this.options.skipWhenAuthPresent&&S(e.config))return this.inflight.resolve(e.config,e),e;if(!0!==(null==l?void 0:l.cache)){const s=((null===(r=e.config)||void 0===r?void 0:r.method)||t).toUpperCase();if(!this.options.cacheMethods.includes(s))return this.inflight.resolve(e.config,e),e;if(this.options.cacheOnlyRetriedRequests&&e.config&&!(null==u?void 0:u.isRetrying))return this.inflight.resolve(e.config,e),e}if(e.status>=200&&e.status<300){const t=this.buildCacheKey(e.config),r=this.getCacheKeyFingerprint(t),o=null==l?void 0:l.ttr;if(this.options.maxEntrySize>0)try{const t=null!==(i=null===(s=JSON.stringify(e.data))||void 0===s?void 0:s.length)&&void 0!==i?i:0;if(t>this.options.maxEntrySize)return null===(n=this.context.getLogger())||void 0===n||n.debug("[CachingPlugin] Skipping oversized response",{cacheKeyFingerprint:r,estimatedSize:t,maxEntrySize:this.options.maxEntrySize}),this.inflight.resolve(e.config,e),e}catch{return this.inflight.resolve(e.config,e),e}try{null===(a=this.context.getLogger())||void 0===a||a.debug("[CachingPlugin] Caching response",{cacheKeyFingerprint:r,...o?{ttrMs:o}:{}}),await this.upsertCacheEntry(t,{response:A(e,this.options.sensitiveResponseHeaders),timestamp:Date.now(),ttr:o,lastAccessedAt:Date.now()})}catch(e){null===(c=this.context.getLogger())||void 0===c||c.warn("[CachingPlugin] Failed to cache response",{cacheKeyFingerprint:r,...x(e)})}finally{this.inflight.resolve(e.config,e)}}else this.inflight.resolve(e.config,e);return e}handleResponseError(e){return e.config&&(this.inflight.reject(e.config,e),this.inflight.clearFollower(e.config)),Promise.reject(e)}buildCacheKey(e){if(!e.url)throw new u;return this.options.cacheKeyBuilder(this.buildCacheKeyContext(e))}async runCacheCleanup(){var e;const t=await this.readCacheEntriesForScan();this.syncLocalCache(t);const r=Date.now(),s=new Set;if(this.options.maxAge>0&&t.forEach(({key:e,value:t})=>{r-t.timestamp>this.options.maxAge&&s.add(e)}),this.options.maxItems>0&&t.length>this.options.maxItems){const e=t.length-this.options.maxItems,r=E(t);for(let t=0;t<r.length&&s.size<e;t++)s.add(r[t].key)}s.size>0&&(await Promise.all(Array.from(s,e=>this.deleteCacheEntry(e))),null===(e=this.context.getLogger())||void 0===e||e.debug(`[CachingPlugin] Cleaned up ${s.size} cached items`))}clearCache(){var e;const t=this.cache.size;this.cache.clear(),this.inflight.clearInflightOnly(),null===(e=this.context.getLogger())||void 0===e||e.debug("[CachingPlugin] Cache cleared."),this.context.triggerAndEmit("onCacheInvalidated",{count:t,matcher:"all"});const r=this.storage.clear();if(C(r))return r.then(()=>{})}invalidateCache(e){const t=this.storage.entries();return C(t)?Promise.resolve(t).then(t=>this.invalidateCacheEntries(e,t)):this.invalidateCacheEntries(e,t)}getCacheStats(){const e=Date.now(),t=Array.from(this.cache.values());if(0===t.length)return{size:0,oldestItemAge:0,newestItemAge:0,averageAge:0};const r=t.map(t=>e-t.timestamp);return{size:this.cache.size,oldestItemAge:Math.max(...r),newestItemAge:Math.min(...r),averageAge:r.reduce((e,t)=>e+t,0)/r.length}}async upsertCacheEntry(e,t){var r;await this.enforceMaxItemsBeforeUpsert(e);const s=this.touchCacheEntry(e,t,null!==(r=t.lastAccessedAt)&&void 0!==r?r:t.timestamp);await this.storage.set(e,s)}touchCacheEntry(e,t,r=Date.now()){const s=t.lastAccessedAt===r?t:{...t,lastAccessedAt:r};return this.cache.delete(e),this.cache.set(e,s),s}deleteCacheEntry(e){this.cache.delete(e);const t=this.storage.delete(e);if(C(t))return t.then(()=>{})}getRequestCachingOptions(e){var t,r;return null!==(t=e.__cachingOptions)&&void 0!==t?t:null===(r=o(e))||void 0===r?void 0:r.cachingOptions}async readCacheEntriesForScan(){return Array.from(await this.storage.entries())}syncLocalCache(e){this.cache.clear(),E(e).forEach(({key:e,value:t})=>{this.cache.set(e,t)})}async enforceMaxItemsBeforeUpsert(e){if(0===this.options.maxItems)return;if(this.cache.size>0){if(this.cache.has(e))return;if(this.cache.size<this.options.maxItems)return;const t=this.cache.size-this.options.maxItems+1,r=E(Array.from(this.cache,([e,t])=>({key:e,value:t})));return void await Promise.all(r.slice(0,t).map(({key:e})=>this.deleteCacheEntry(e)))}const t=await this.readCacheEntriesForScan();if(this.syncLocalCache(t),t.some(t=>t.key===e))return;const r=t.length-this.options.maxItems+1;if(r<=0)return;const s=E(t).slice(0,r).map(e=>e.key);await Promise.all(s.map(e=>this.deleteCacheEntry(e)))}async persistCacheTouchIfNeeded(e,t,r){var s;if(0!==this.options.maxItems)try{await this.storage.set(e,t)}catch(e){null===(s=this.context.getLogger())||void 0===s||s.warn("[CachingPlugin] Failed to persist cache access metadata",{cacheKeyFingerprint:r,...x(e)})}}invalidateCacheEntries(e,t){this.syncLocalCache(t);const r=t.filter(({key:t})=>function(e,t){return t instanceof RegExp?t.test(e):"string"==typeof t?e===t:"exact"in t?e===t.exact:e.startsWith(t.prefix)}(t,e)).map(({key:e})=>e);if(0===r.length)return 0;const s=r.map(e=>this.deleteCacheEntry(e)),i=()=>{var t;return null===(t=this.context.getLogger())||void 0===t||t.debug("[CachingPlugin] Invalidated cache entries",{count:r.length,matcher:R(e)}),this.context.triggerAndEmit("onCacheInvalidated",{count:r.length,matcher:"custom"}),r.length};return s.some(e=>C(e))?Promise.all(s.map(e=>Promise.resolve(e))).then(()=>i()):i()}buildCacheKeyContext(e){return function(e,r){var s;let i;if(r.compareHeaders&&e.headers)i=y(e.headers,!0);else if(r.varyHeaders.length>0&&e.headers){const t=e.headers,s=new Set(r.varyHeaders.map(e=>e.toLowerCase())),n=[];for(const e of Object.keys(t))s.has(e.toLowerCase())&&n.push([e.toLowerCase(),String(t[e])]);n.sort(f),i=n.length>0?JSON.stringify(n):""}else i="";return{config:e,method:(e.method||t).toUpperCase(),normalizedUrl:g(null!==(s=e.url)&&void 0!==s?s:""),normalizedParams:y(e.params),normalizedData:y(e.data),normalizedHeaders:i}}(e,this.options)}}I.CACHE_CLEANUP_TIMEOUT_MS=3e4,I.CACHE_CLEANUP_DISABLE_AFTER=5;const P=[{name:"nested quantifier",test:e=>/\([^)]*[+*][^)]*\)[+*{]/.test(e)},{name:"alternation with quantifier",test:e=>/\([^)]*\|[^)]*\)[+*{]/.test(e)}];class O{constructor(e){this.responseMetrics={},this.percentile=e.percentile,this.sampleSize=e.sampleSize,this.multiplier=e.multiplier,this.maxTrackedScopes=e.maxTrackedScopes}trackResponseTime(e,t,r,s){var i,n;if(!e.config.url)return;let a=0;if(e.headers&&e.headers["x-response-time"]?a=parseInt(e.headers["x-response-time"],10):(null===(i=o(e.config))||void 0===i?void 0:i.timestamp)&&(a=Date.now()-((null===(n=o(e.config))||void 0===n?void 0:n.timestamp)||0)),a<=0&&(a=100),!this.responseMetrics[t]){const e=Object.keys(this.responseMetrics);e.length>=this.maxTrackedScopes&&delete this.responseMetrics[e[0]],this.responseMetrics[t]={times:[],sampleSize:this.sampleSize,lastCalculated:0,currentPercentileMs:0,scopeKey:t,normalizedUrl:r,host:s}}const c=this.responseMetrics[t];c.times.push(a),c.times.length>c.sampleSize&&c.times.shift(),this.updatePercentile(t)}getComputedTimeout(e){const t=this.responseMetrics[e];if(t&&this.isActive(t))return Math.round(t.currentPercentileMs*this.multiplier)}isActive(e){return e.times.length>=e.sampleSize&&e.currentPercentileMs>0}getAdaptiveTimeoutMetrics(){return Object.values(this.responseMetrics).map(e=>({scopeKey:e.scopeKey,url:e.normalizedUrl,host:e.host,timeoutMs:Math.round(e.currentPercentileMs*this.multiplier),p95ResponseTimeMs:e.currentPercentileMs,samplesCount:e.times.length}))}reset(){this.responseMetrics={}}updatePercentile(e){const t=this.responseMetrics[e];if(!t||0===t.times.length)return;if(t.times.length<t.sampleSize)return void(t.currentPercentileMs=0);const r=[...t.times].sort((e,t)=>e-t),s=Math.max(0,Math.min(Math.ceil(r.length*this.percentile)-1,r.length-1));t.currentPercentileMs=r[s],t.lastCalculated=Date.now()}}const L={CLOSED:"CLOSED",OPEN:"OPEN",HALF_OPEN:"HALF_OPEN"},F={HOST:"host",URL:"url",HOST_AND_URL:"host+url"};function D(e){return{...e,recentFailures:e.recentFailures.map(e=>({...e}))}}function z(e){return!!e&&"function"==typeof e.then}const j={log:()=>{},error:()=>{},warn:()=>{},debug:()=>{}};class H{constructor(){this.state=new Map}get(e){const t=this.state.get(e);return t?D(t):void 0}set(e,t){this.state.set(e,D(t))}delete(e){this.state.delete(e)}clear(){this.state.clear()}}class N{constructor(e){this.scopeStateCache=new Map,this.knownScopes=new Map,this.scopeLocks=new Map,this.logger=j,this.scope=e.scope,this.stateAdapter=e.stateAdapter,this.maxTrackedScopes=e.maxTrackedScopes}setLogger(e){this.logger=e}createInitialState(){return{state:L.CLOSED,failureCount:0,successCount:0,halfOpenCount:0,nextAttempt:Date.now(),recentFailures:[],lastFailureStatus:void 0,lastFailureCode:void 0}}withLock(e,t){var r;const s=(null!==(r=this.scopeLocks.get(e))&&void 0!==r?r:Promise.resolve()).then(t,t);return this.scopeLocks.set(e,s.then(()=>{},()=>{})),s}async readState(e){let t;try{t=await this.stateAdapter.get(e)}catch(t){this.handleAdapterError("get",e,t)}const r=this.scopeStateCache.get(e),s=t?D(t):r?D(r):this.createInitialState();return this.scopeStateCache.set(e,s),s}async writeState(e,t){const r=this.scopeStateCache.get(e),s=D(t);this.scopeStateCache.set(e,s);try{await this.stateAdapter.set(e,s)}catch(t){r?this.scopeStateCache.set(e,r):this.scopeStateCache.delete(e),this.handleAdapterError("set",e,t)}}getScopeDetails(e){const t=this.normalizeUrl(this.extractPath(e)),r=this.extractHost(e),s=this.resolveScopeKey(e,t,r);if(!this.knownScopes.has(s)){if(this.knownScopes.size>=this.maxTrackedScopes){const e=this.knownScopes.keys().next().value;this.knownScopes.delete(e),this.scopeStateCache.delete(e)}this.knownScopes.set(s,{scopeKey:s,normalizedUrl:t,host:r})}return this.knownScopes.get(s)}getKnownScopes(){return this.knownScopes.values()}getTrackedScopeKeys(e){return e?[e]:Array.from(new Set([...this.knownScopes.keys(),...this.scopeStateCache.keys()]))}deleteDistributedScope(e){try{const t=this.stateAdapter.delete(e);z(t)&&t.catch(t=>{this.handleAdapterError("delete",e,t),this.restoreDistributedClosedState([e])})}catch(t){this.handleAdapterError("delete",e,t),this.restoreDistributedClosedState([e])}}clearDistributedState(e){try{const t=this.stateAdapter.clear();z(t)&&t.catch(t=>{this.handleAdapterError("clear","*",t),this.restoreDistributedClosedState(e)})}catch(t){this.handleAdapterError("clear","*",t),this.restoreDistributedClosedState(e)}}restoreDistributedClosedState(e){e.forEach(e=>{const t=this.stateAdapter.set(e,this.createInitialState());z(t)&&t.catch(t=>{this.handleAdapterError("set",e,t)})})}resolveScopeKey(e,t,r){const s=r?`${r}${t}`:t||"unknown";if("function"==typeof this.scope)try{const t=this.scope(e);return"string"==typeof t&&t.length>0?t:(this.logger.warn("CircuitBreakerPlugin: Custom scope callback returned an empty scope key; using default",{url:e.url}),s)}catch(t){return this.logger.warn("CircuitBreakerPlugin: Custom scope callback threw; using default scope",{error:t instanceof Error?t.message:t,url:e.url}),s}switch(this.scope){case F.HOST:return r||t||"unknown";case F.URL:return t||r||"unknown";default:return s}}normalizeUrl(e){let t=e.split("?")[0].split("#")[0];return t=t.replace(/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\d+)(\/|$)/gi,"/:id$2"),t}resolveScopeKeyPublic(e,t,r){return this.resolveScopeKey(e,t,r)}extractPath(e){const t=this.resolveUrl(e);return t?`${t.pathname}${t.search}${t.hash}`||"/":e.url||"/"}extractHost(e){var t;return null===(t=this.resolveUrl(e))||void 0===t?void 0:t.host}resolveUrl(e){var t,r;if(!e.url)return null;const s=null!==(t=e.baseURL)&&void 0!==t?t:null===(r=this.baseURLGetter)||void 0===r?void 0:r.call(this);if(!/^[a-z][a-z\d+\-.]*:\/\//i.test(e.url)&&!s)return null;try{return new URL(e.url,s)}catch(e){return null}}handleAdapterError(e,t,r){this.logger.warn(`CircuitBreakerPlugin: State adapter ${e} failed; continuing with local circuit state`,{scopeKey:t,error:r instanceof Error?r.message:r})}}const K={failureThreshold:5,openTimeout:3e4,halfOpenMax:1,successThreshold:1,useSlidingWindow:!1,slidingWindowSize:6e4,adaptiveTimeout:!1,adaptiveTimeoutPercentile:.95,adaptiveTimeoutSampleSize:100,adaptiveTimeoutMultiplier:1.5,maxTrackedScopes:500,excludeUrls:[]};class U extends e.AxiosError{constructor(e,t,r,s,i){super(e,null!=s?s:"ECIRCUIT_BREAKER_STATE",r,void 0,i),this.name="CircuitBreakerStateError",this.circuitState=t,Object.setPrototypeOf(this,new.target.prototype)}}class B{constructor(e){this.options=e}rememberLast(e,t){var r;e.lastFailureStatus=null===(r=t.response)||void 0===r?void 0:r.status,e.lastFailureCode=t.code}add(e,t){var r,s;e.recentFailures.push({timestamp:Date.now(),url:(null===(r=t.config)||void 0===r?void 0:r.url)||"unknown",status:null===(s=t.response)||void 0===s?void 0:s.status,errorCode:t.code}),e.failureCount++,this.cleanup(e)}cleanup(e){if(!this.options.useSlidingWindow)return;const t=Date.now()-this.options.slidingWindowSize,r=e.recentFailures.length;e.recentFailures=e.recentFailures.filter(e=>e.timestamp>=t);const s=r-e.recentFailures.length;s>0&&(e.failureCount=Math.max(0,e.failureCount-s))}count(e){return this.options.useSlidingWindow?(this.cleanup(e),e.recentFailures.length):e.failureCount}countSince(e,t){return this.cleanup(e),e.recentFailures.filter(e=>e.timestamp>=t).length}}class ${constructor(e={}){this.name="CircuitBreakerPlugin",this.version="2.0.0",this._metricBaselines=new Map,this._options=function(e={}){var t,r;const s={...K,...e,scope:null!==(t=e.scope)&&void 0!==t?t:F.HOST_AND_URL,stateAdapter:null!==(r=e.stateAdapter)&&void 0!==r?r:new H};return function(e){if(!Number.isInteger(e.failureThreshold)||e.failureThreshold<1)throw new h("failureThreshold must be a positive integer","failureThreshold",e.failureThreshold);if(!Number.isInteger(e.openTimeout)||e.openTimeout<0)throw new h("openTimeout must be a non-negative integer","openTimeout",e.openTimeout);if(!Number.isInteger(e.halfOpenMax)||e.halfOpenMax<1)throw new h("halfOpenMax must be a positive integer","halfOpenMax",e.halfOpenMax);if(void 0!==e.successThreshold&&(!Number.isInteger(e.successThreshold)||e.successThreshold<1))throw new h("successThreshold must be a positive integer","successThreshold",e.successThreshold);if(e.successThreshold>e.halfOpenMax&&(e.successThreshold=e.halfOpenMax),0===e.excludeUrls.length)return;const t=function(e){const t=[];for(let r=0;r<e.length;r++){const s=e[r];if(s instanceof RegExp)for(const e of P)if(e.test(s.source)){t.push({index:r,pattern:s,reason:`Potentially catastrophic backtracking detected (${e.name}): ${s}. Use a string for exact-match exclusions, or simplify the pattern to avoid nested quantifiers.`});break}}return t}(e.excludeUrls);if(0!==t.length)throw new h(t.map(e=>e.reason).join("\n"),"excludeUrls",t.map(e=>e.pattern))}(s),s}(e),this._adaptiveTimeoutTracker=new O({percentile:this._options.adaptiveTimeoutPercentile,sampleSize:this._options.adaptiveTimeoutSampleSize,multiplier:this._options.adaptiveTimeoutMultiplier,maxTrackedScopes:this._options.maxTrackedScopes}),this._scopeManager=new N({scope:this._options.scope,stateAdapter:this._options.stateAdapter,maxTrackedScopes:this._options.maxTrackedScopes}),this._failureWindow=new B({useSlidingWindow:this._options.useSlidingWindow,slidingWindowSize:this._options.slidingWindowSize})}get _responseMetrics(){return this._adaptiveTimeoutTracker.responseMetrics}get _scopeStateCache(){return this._scopeManager.scopeStateCache}get _knownScopes(){return this._scopeManager.knownScopes}_normalizeUrl(e){return this._scopeManager.normalizeUrl(e)}_resolveScopeKey(e,t,r){return this._scopeManager.resolveScopeKeyPublic(e,t,r)}_getScopeDetails(e){return this._scopeManager.getScopeDetails(e)}async _writeScopeState(e,t){return this._scopeManager.writeState(e,t)}initialize(e){this._context=e;const t=e.getLogger();this._scopeManager.setLogger(t),this._scopeManager.baseURLGetter=()=>e.axiosInstance.defaults.baseURL,t.debug("CircuitBreakerPlugin: Initializing with options:",{...this._options});const r=e.axiosInstance;this._requestInterceptorId=r.interceptors.request.use(async e=>{const r=n(e);if(this._options.adaptiveTimeout&&e.url&&!r.timestamp&&c(e,{timestamp:Date.now()}),this._isUrlExcluded(e))return t.debug(`CircuitBreakerPlugin: URL excluded from circuit breaking: ${e.url}`),e;const s=this._scopeManager.getScopeDetails(e),i=await this._scopeManager.withLock(s.scopeKey,async()=>{let e=await this._scopeManager.readState(s.scopeKey);if(e.state===L.OPEN){if(!(Date.now()>=e.nextAttempt))return{action:"reject-open",scopeState:e};e=await this._transitionToHalfOpen(s.scopeKey,e)}if(e.state===L.HALF_OPEN){if(e.halfOpenCount>=this._options.halfOpenMax)return{action:"reject-half-open",scopeState:e};e.halfOpenCount++,await this._scopeManager.writeState(s.scopeKey,e),t.debug(`CircuitBreakerPlugin: HALF_OPEN test request #${e.halfOpenCount} of ${this._options.halfOpenMax} for ${s.scopeKey}`)}return{action:"allow",scopeState:e}});if("reject-open"===i.action){const r=i.scopeState.nextAttempt-Date.now();return t.debug(`CircuitBreakerPlugin: Circuit is OPEN for ${s.scopeKey}: failing fast. Will retry in ${r}ms`),Promise.reject(this._createCircuitStateError(e,i.scopeState,"Circuit is open: failing fast."))}if("reject-half-open"===i.action)return t.debug(`CircuitBreakerPlugin: Circuit is HALF_OPEN for ${s.scopeKey}: too many test requests.`),Promise.reject(this._createCircuitStateError(e,i.scopeState,"Circuit is half-open: too many test requests."));if(this._options.adaptiveTimeout){const r=this._adaptiveTimeoutTracker.getComputedTimeout(s.scopeKey);void 0!==r&&(e.timeout=r,t.debug(`CircuitBreakerPlugin: Setting adaptive timeout for ${s.scopeKey}: ${r}ms`))}return e}),this._responseInterceptorId=r.interceptors.response.use(async e=>{if(this._options.adaptiveTimeout&&e.config.url){const t=this._scopeManager.getScopeDetails(e.config);this._adaptiveTimeoutTracker.trackResponseTime(e,t.scopeKey,t.normalizedUrl,t.host)}if(this._isUrlExcluded(e.config))return e;const r=this._scopeManager.getScopeDetails(e.config);return await this._scopeManager.withLock(r.scopeKey,async()=>{const e=await this._scopeManager.readState(r.scopeKey);if(e.state===L.HALF_OPEN){e.successCount++;const s=this._options.successThreshold||1;e.successCount>=s?(t.debug(`CircuitBreakerPlugin: HALF_OPEN success threshold reached (${e.successCount}/${s}) for ${r.scopeKey}`),await this._resetScope(r.scopeKey)):(await this._scopeManager.writeState(r.scopeKey,e),t.debug(`CircuitBreakerPlugin: HALF_OPEN success: ${e.successCount}/${s} successful test requests for ${r.scopeKey}`))}else e.state===L.CLOSED&&e.failureCount>0&&(e.failureCount=0,e.lastFailureStatus=void 0,e.lastFailureCode=void 0,await this._scopeManager.writeState(r.scopeKey,e))}),e},async e=>{if(!e.config)return Promise.reject(e);if(this._isUrlExcluded(e.config))return Promise.reject(e);if(!this._shouldCountError(e))return t.debug("CircuitBreakerPlugin: Error excluded from circuit breaking by shouldCountError"),Promise.reject(e);const r=this._scopeManager.getScopeDetails(e.config);return await this._scopeManager.withLock(r.scopeKey,async()=>{const s=await this._scopeManager.readState(r.scopeKey);if(this._failureWindow.rememberLast(s,e),this._options.useSlidingWindow){this._failureWindow.add(s,e);const i=this._failureWindow.count(s);i>=this._options.failureThreshold?(t.debug(`CircuitBreakerPlugin: Sliding window failure threshold reached for ${r.scopeKey}: ${i} failures in window`),await this._tripScope(r.scopeKey,s)):await this._scopeManager.writeState(r.scopeKey,s)}else s.failureCount++,t.debug(`CircuitBreakerPlugin: Failure count increased for ${r.scopeKey}: ${s.failureCount}/${this._options.failureThreshold}`),s.state===L.HALF_OPEN||s.failureCount>=this._options.failureThreshold?await this._tripScope(r.scopeKey,s):await this._scopeManager.writeState(r.scopeKey,s)}),Promise.reject(e)})}onBeforeDestroyed(e){e.getLogger().debug("CircuitBreakerPlugin: Removing CircuitBreakerPlugin");const t=e.axiosInstance;void 0!==this._requestInterceptorId&&t.interceptors.request.eject(this._requestInterceptorId),void 0!==this._responseInterceptorId&&t.interceptors.response.eject(this._responseInterceptorId)}getState(e){var t,r;if(e)return null!==(r=null===(t=this._scopeManager.scopeStateCache.get(e))||void 0===t?void 0:t.state)&&void 0!==r?r:L.CLOSED;const s=Array.from(this._scopeManager.scopeStateCache.values()).map(e=>e.state);return s.includes(L.OPEN)?L.OPEN:s.includes(L.HALF_OPEN)?L.HALF_OPEN:L.CLOSED}manualReset(e){var t,r;const s=this._scopeManager.getTrackedScopeKeys(e);if(s.forEach(e=>{var t,r;const s=null!==(r=null===(t=this._scopeManager.scopeStateCache.get(e))||void 0===t?void 0:t.state)&&void 0!==r?r:L.CLOSED;this._scopeManager.scopeStateCache.set(e,this._scopeManager.createInitialState()),this._metricBaselines.delete(e),s!==L.CLOSED&&this._emitStateChange(e,s,L.CLOSED,"manual-reset")}),e)return this._scopeManager.deleteDistributedScope(e),void(null===(t=this._context)||void 0===t||t.getLogger().debug(`CircuitBreakerPlugin: Circuit reset for ${e}`));this._scopeManager.clearDistributedState(s),null===(r=this._context)||void 0===r||r.getLogger().debug("CircuitBreakerPlugin: Circuit reset: entering CLOSED state")}_reset(e){this.manualReset(e)}_trackResponseTime(e){if(!e.config.url||!this._options.adaptiveTimeout)return;const t=this._scopeManager.getScopeDetails(e.config);this._adaptiveTimeoutTracker.trackResponseTime(e,t.scopeKey,t.normalizedUrl,t.host)}resetMetrics(){var e;const t=Date.now();this._metricBaselines.clear(),this._scopeManager.getTrackedScopeKeys().forEach(e=>{var r;const s=null!==(r=this._scopeManager.scopeStateCache.get(e))&&void 0!==r?r:this._scopeManager.createInitialState();this._metricBaselines.set(e,{failureCount:s.failureCount,successCount:s.successCount,halfOpenCount:s.halfOpenCount,resetAt:t})}),this._adaptiveTimeoutTracker.reset(),null===(e=this._context)||void 0===e||e.getLogger().debug("CircuitBreakerPlugin: Circuit metrics reset.")}getAdaptiveTimeoutMetrics(){return this._options.adaptiveTimeout?this._adaptiveTimeoutTracker.getAdaptiveTimeoutMetrics():[]}getMetrics(){const e=this._getScopeMetrics();return{state:this.getState(),failureCount:e.reduce((e,t)=>e+t.failureCount,0),halfOpenCount:e.reduce((e,t)=>e+t.halfOpenCount,0),successCount:e.reduce((e,t)=>e+t.successCount,0),nextAttemptIn:e.reduce((e,t)=>Math.max(e,t.nextAttemptIn),0),failuresInWindow:e.reduce((e,t)=>e+t.failuresInWindow,0),adaptiveTimeouts:this.getAdaptiveTimeoutMetrics(),scopeMetrics:e}}async _tripScope(e,t){var r;if(t.state!==L.OPEN){const s=t.state;t.state=L.OPEN,t.nextAttempt=Date.now()+this._options.openTimeout,t.successCount=0,t.halfOpenCount=0,await this._scopeManager.writeState(e,t),this._emitStateChange(e,s,L.OPEN,s===L.HALF_OPEN?"half-open-failure":"failure-threshold",Math.max(0,t.nextAttempt-Date.now())),null===(r=this._context)||void 0===r||r.getLogger().error(`CircuitBreakerPlugin: Circuit tripped: entering OPEN state for ${e} until ${new Date(t.nextAttempt).toISOString()}`)}}async _resetScope(e){var t,r,s;const i=null!==(r=null===(t=this._scopeManager.scopeStateCache.get(e))||void 0===t?void 0:t.state)&&void 0!==r?r:L.CLOSED;await this._scopeManager.writeState(e,this._scopeManager.createInitialState()),i!==L.CLOSED&&this._emitStateChange(e,i,L.CLOSED,"success-threshold-reached"),null===(s=this._context)||void 0===s||s.getLogger().debug(`CircuitBreakerPlugin: Circuit reset: entering CLOSED state for ${e}.`)}async _transitionToHalfOpen(e,t){var r;const s=t.state;return t.state=L.HALF_OPEN,t.halfOpenCount=0,t.successCount=0,await this._scopeManager.writeState(e,t),this._emitStateChange(e,s,L.HALF_OPEN,"open-timeout-elapsed"),null===(r=this._context)||void 0===r||r.getLogger().debug(`CircuitBreakerPlugin: Transitioning to HALF_OPEN for ${e}.`),t}_emitStateChange(e,t,r,s,i){var n,o;t!==r&&(null===(o=null===(n=this._context)||void 0===n?void 0:n.triggerAndEmit)||void 0===o||o.call(n,"onCircuitStateChanged",{scopeKey:e,from:t,to:r,reason:s,...void 0!==i?{nextAttemptIn:i}:{}}))}_shouldCountError(e){var t;if(!this._options.shouldCountError)return!0;try{return this._options.shouldCountError(e)}catch(e){return null===(t=this._context)||void 0===t||t.getLogger().warn("CircuitBreakerPlugin: shouldCountError callback threw; counting error by default",{error:e instanceof Error?e.message:e}),!0}}_isUrlExcluded(e){return!(!e.url||!this._options.excludeUrls||0===this._options.excludeUrls.length)&&this._options.excludeUrls.some(t=>t instanceof RegExp?t.test(e.url||""):e.url===t)}_createCircuitStateError(e,t,r){const s={...e};return c(s,{requestRetries:0}),new U(r,t.state,s,t.lastFailureCode,void 0!==t.lastFailureStatus?{status:t.lastFailureStatus,statusText:"Circuit Open",config:s,headers:{},data:{error:r}}:void 0)}_getScopeMetrics(){const e=Date.now();return Array.from(this._scopeManager.getKnownScopes()).map(t=>{var r;const s=null!==(r=this._scopeManager.scopeStateCache.get(t.scopeKey))&&void 0!==r?r:this._scopeManager.createInitialState();return{scopeKey:t.scopeKey,url:t.normalizedUrl,host:t.host,state:s.state,failureCount:this._getVisibleCounter(t.scopeKey,"failureCount",s.failureCount),halfOpenCount:this._getVisibleCounter(t.scopeKey,"halfOpenCount",s.halfOpenCount),successCount:this._getVisibleCounter(t.scopeKey,"successCount",s.successCount),nextAttemptIn:Math.max(0,s.nextAttempt-e),failuresInWindow:this._getVisibleFailuresInWindow(t.scopeKey,s)}})}_getVisibleCounter(e,t,r){var s;const i=this._metricBaselines.get(e);return Math.max(0,r-(null!==(s=null==i?void 0:i[t])&&void 0!==s?s:0))}_getVisibleFailuresInWindow(e,t){var r,s;if(!this._options.useSlidingWindow)return this._getVisibleCounter(e,"failureCount",t.failureCount);const i=null!==(s=null===(r=this._metricBaselines.get(e))||void 0===r?void 0:r.resetAt)&&void 0!==s?s:0;return this._failureWindow.countSince(t,i)}}$.STATES=L;const W=["authorization","x-api-key","api-key","apikey","password","x-auth-token","token","refresh-token","x-refresh-token","secret","x-api-secret","client-secret","x-client-secret","access-token","api-token"],Q=["password","token","accessToken","access_token","refreshToken","refresh_token","secret","apiKey","api_key","apiSecret","api_secret","clientSecret","client_secret","credentials","credential","private_key","privateKey"],V={sensitiveHeaders:[],sensitiveFields:[],redactionChar:"*",sanitizeRequestData:!0,sanitizeResponseData:!0,sanitizeUrlParams:!0,allowedFields:[],allowlistOnly:!0},J=e=>e.repeat(8),G=new Map;function X(e){return Array.from(new Set(e.map(e=>e.trim().toLowerCase()).filter(Boolean))).sort()}function Y(e){const t=X([...Q,...e.sensitiveFields]),r=X([...W,...e.sensitiveHeaders]),s=X(e.allowedFields),i=[t.join("|"),r.join("|"),s.join("|")].join("::"),n=G.get(i);if(n)return n;const o={sensitiveFields:t,sensitiveFieldsSet:new Set(t),sensitiveHeaders:r,sensitiveHeadersSet:new Set(r),allowedFieldsSet:new Set(s)};return G.set(i,o),o}function Z(e,t){return t.has(e.toLowerCase())}function ee(e,t,r){const s=e.toLowerCase();if(t.has(s))return!0;for(const e of r)if(s.includes(e))return!0;return!1}function te(e,t={}){if(!e)return e;const r={...V,...t},s=Y(r),i=J(r.redactionChar),n=new WeakMap,o=(e,t)=>{if(null==e)return e;if("object"!=typeof e)return r.allowlistOnly?t&&Z(t,s.allowedFieldsSet)?e:i:e;if(e instanceof Date)return!r.allowlistOnly||t&&Z(t,s.allowedFieldsSet)?new Date(e.getTime()):i;const a=n.get(e);if(a)return a;if(Array.isArray(e)){const t=[];return n.set(e,t),e.forEach((e,r)=>{t[r]=o(e)}),t}const c={};return n.set(e,c),Object.keys(e).forEach(t=>{const n=e[t];c[t]=ee(t,s.sensitiveFieldsSet,s.sensitiveFields)?i:n&&"object"==typeof n?o(n,t):!r.allowlistOnly||Z(t,s.allowedFieldsSet)?n:i}),c};return o(e)}function re(e,t={}){if(!e)return e;const r={...V,...t},s=Y(r),i=J(r.redactionChar),n={...e};for(const e of Object.keys(n)){const t=e.toLowerCase();(s.sensitiveHeadersSet.has(t)||s.sensitiveHeaders.some(e=>t.includes(e)))&&(n[e]=i)}return n}function se(e,t={}){if(!e)return e;const r={...V,...t};if(!r.sanitizeUrlParams)return e;const s=Y(r),i=J(r.redactionChar);try{if(!e.includes("?"))return e;const t=e.indexOf("#"),r=-1===t?"":e.slice(t),n=-1===t?e:e.slice(0,t),o=n.indexOf("?");if(-1===o)return e;const a=n.slice(0,o),c=n.slice(o+1);if(!c)return e;const u=new URLSearchParams(c);let l=!1;const h=new Set;return u.forEach((e,t)=>{h.add(t)}),h.forEach(e=>{ee(e,s.sensitiveFieldsSet,s.sensitiveFields)&&(u.set(e,i),l=!0)}),l?`${a}?${u.toString()}${r}`:e}catch{return e}}class ie{constructor(e={}){this.name="DebugSanitizationPlugin",this.version="1.0.0",this.interceptorIdReq=null,this.interceptorIdRes=null,this.sanitizeOptions=function(e={}){var t;return null!==(t=e.sanitizeOptions)&&void 0!==t?t:{}}(e)}initialize(e){this.context=e,this.interceptorIdReq=e.axiosInstance.interceptors.request.use(e=>(this.logSanitizedRequest(e),e)),this.interceptorIdRes=e.axiosInstance.interceptors.response.use(void 0,e=>(e.config&&this.logSanitizedError(e.config,e),Promise.reject(e)))}onBeforeDestroyed(e){null!==this.interceptorIdReq&&e.axiosInstance.interceptors.request.eject(this.interceptorIdReq),null!==this.interceptorIdRes&&e.axiosInstance.interceptors.response.eject(this.interceptorIdRes)}logSanitizedRequest(e){var t,r;const s=o(e);null===(t=this.context.getLogger())||void 0===t||t.debug("[DebugSanitizationPlugin] Sanitized request",{requestId:null==s?void 0:s.requestId,url:se(e.url||"",this.sanitizeOptions),method:null===(r=e.method)||void 0===r?void 0:r.toUpperCase(),headers:re(e.headers,this.sanitizeOptions),priority:null==s?void 0:s.priority})}logSanitizedError(e,t){var r,s,i,n;const a=o(e);null===(r=this.context.getLogger())||void 0===r||r.debug("[DebugSanitizationPlugin] Sanitized error",{requestId:null==a?void 0:a.requestId,url:se(e.url||"",this.sanitizeOptions),method:null===(s=e.method)||void 0===s?void 0:s.toUpperCase(),status:null===(i=t.response)||void 0===i?void 0:i.status,statusText:null===(n=t.response)||void 0===n?void 0:n.statusText,code:t.code,message:t.message,headers:re(e.headers,this.sanitizeOptions),data:!1!==this.sanitizeOptions.sanitizeRequestData?te(e.data,this.sanitizeOptions):void 0,response:t.response?{data:!1!==this.sanitizeOptions.sanitizeResponseData?te(t.response.data,this.sanitizeOptions):void 0,headers:re(t.response.headers,this.sanitizeOptions)}:void 0})}}class ne{constructor(e=200,t){this.maxStoreSize=e,this.emit=t,this.requests=[]}add(e){if(n(e),this.requests.push(e),this.requests.length>this.maxStoreSize){const e=this.requests.shift();e&&this.emit("onRequestRemovedFromStore",e)}}remove(e){var t;const r=null===(t=o(e))||void 0===t?void 0:t.requestId;this.requests=this.requests.filter(e=>{var t;return(null===(t=o(e))||void 0===t?void 0:t.requestId)!==r})}getAll(){return this.requests.slice()}clear(){this.requests=[]}}const oe={maxRequestsToStore:200,manualRetryMaxAge:3e5,storeNonIdempotent:!1,storeAuthRequests:!1},ae=new Set(["get","head","options"]),ce=["authorization","proxy-authorization","cookie","set-cookie","x-auth-token","x-api-key","api-key","apikey","token","refresh-token","x-refresh-token","x-csrf-token","x-xsrf-token"],ue=new Set(ce);class le{constructor(e={}){this.name="ManualRetryPlugin",this.version="1.0.0";const t=function(e={}){return{...oe,...e}}(e);this.maxRequestsToStore=t.maxRequestsToStore,this.maxAge=t.manualRetryMaxAge,this.storeNonIdempotent=t.storeNonIdempotent,this.storeAuthRequests=t.storeAuthRequests,this.beforeRetryCallback=t.beforeRetry,this.prepareRequestForStoreCallback=t.prepareRequestForStore,this.rehydrateAuthCallback=t.rehydrateAuth,this.customStore=t.requestStore}initialize(e){var t;this.context=e,this.store=null!==(t=this.customStore)&&void 0!==t?t:new ne(this.maxRequestsToStore,e.triggerAndEmit),this.onFailureHandler=e=>{const t=this.prepareStoredRequest(e);t&&this.store.add(t)},e.on("onFailure",this.onFailureHandler)}onBeforeDestroyed(e){var t;e.off("onFailure",this.onFailureHandler),null===(t=this.store)||void 0===t||t.clear()}async retryFailedRequests(){var e,t,r,s,i;const n=this.store.getAll();this.store.clear();const c=Date.now(),u=n.filter(e=>{var t,r,s;const i=c-((null===(t=o(e))||void 0===t?void 0:t.timestamp)||0);return!(i>this.maxAge&&(null===(r=this.context.getLogger())||void 0===r||r.debug("[ManualRetryPlugin] Discarding expired stored request",{requestId:null===(s=o(e))||void 0===s?void 0:s.requestId,ageMs:i,maxAgeMs:this.maxAge}),1))});if(0===u.length)return[];null===(e=this.context.getLogger())||void 0===e||e.debug("[ManualRetryPlugin] Starting manual retry process",{count:u.length,discarded:n.length-u.length}),this.context.triggerAndEmit("onManualRetryProcessStarted");const l=[];for(let e=0;e<u.length;e++){const n=u[e],c=this.beforeRetryCallback?this.beforeRetryCallback(n):n;if(!c){null===(t=this.context.getLogger())||void 0===t||t.debug("[ManualRetryPlugin] Request skipped by beforeRetry callback",{requestId:null===(r=o(n))||void 0===r?void 0:r.requestId});continue}if(this.rehydrateAuthCallback){if(!this.rehydrateAuthCallback(c)){null===(s=this.context.getLogger())||void 0===s||s.debug("[ManualRetryPlugin] Request skipped by rehydrateAuth callback",{requestId:null===(i=o(n))||void 0===i?void 0:i.requestId});continue}}else this.neutralizeDefaultAuthHeaders(c);delete c.signal,a(c,"retryAttempt",0),a(c,"isRetrying",!1),a(c,"manualReplayAttempt",!0),e>0&&await new Promise(t=>setTimeout(t,Math.min(200*e,2e3)));const h=await this.context.axiosInstance.request(c);l.push(h)}return l}getStoredRequests(){return this.store.getAll()}clearStoredRequests(){this.store.clear()}isEligible(e){return function(e,t){if(t)return!0;const r=(e.method||"get").toLowerCase();return!!ae.has(r)||function(e){var t;const r="Idempotency-Key".toLowerCase();return Object.keys(null!==(t=e.headers)&&void 0!==t?t:{}).some(e=>e.toLowerCase()===r)}(e)}(e,this.storeNonIdempotent)}prepareStoredRequest(e){var t,r,s,i,n,a,c;if(null===(t=o(e))||void 0===t?void 0:t.manualReplayAttempt)return null===(r=this.context.getLogger())||void 0===r||r.debug("[ManualRetryPlugin] Skipping replay failure to avoid re-storing it",{requestId:null===(s=o(e))||void 0===s?void 0:s.requestId}),null;if(!this.isEligible(e))return null;if(function(e){var t;return!!e.auth||Object.keys(null!==(t=e.headers)&&void 0!==t?t:{}).some(e=>ue.has(e.toLowerCase()))}(e)&&!this.storeAuthRequests)return null===(i=this.context.getLogger())||void 0===i||i.debug("[ManualRetryPlugin] Skipping storage for auth-bearing request",{requestId:null===(n=o(e))||void 0===n?void 0:n.requestId}),null;const u=function(e){const t={...e,data:b(e.data),headers:e.headers?{...e.headers}:{},params:b(e.params)};return function(e){if(e.headers){for(const t of Object.keys(e.headers))ue.has(t.toLowerCase())&&delete e.headers[t];delete e.auth}}(t),t}(e);if(!this.prepareRequestForStoreCallback)return u;const l=this.prepareRequestForStoreCallback(u);return l||null===(a=this.context.getLogger())||void 0===a||a.debug("[ManualRetryPlugin] Request skipped by prepareRequestForStore",{requestId:null===(c=o(e))||void 0===c?void 0:c.requestId}),l}neutralizeDefaultAuthHeaders(e){const t=this.context.axiosInstance.defaults;!function(e,t,r){var s;const i=null!==(s=null==t?void 0:t.common)&&void 0!==s?s:{};e.headers=e.headers||{};for(const r of ce){const s=r.toLowerCase(),n=Object.keys(i).some(e=>e.toLowerCase()===s),o=!!t&&Object.keys(t).some(e=>e.toLowerCase()===s);(n||o)&&(e.headers[r]=void 0)}r&&(e.auth=void 0)}(e,t.headers,Boolean(t.auth))}}const he={activeTimers:0,activeRetryTimers:0},de={total:0,successes:0,failures:0};class pe{constructor(e){this.getMetricsState=e,this.queueWaitHistory=[],this.retryDelayHistory=[]}recordRequestStart(e){var t;const r=this.getMetricsState();r.totalRequests++,r.requestCountsByPriority[e]=(null!==(t=r.requestCountsByPriority[e])&&void 0!==t?t:0)+1}recordQueueWait(e){this.getMetricsState().queueWaitDuration+=e,this.recordDuration(this.queueWaitHistory,e)}recordRetrySuccess(e){this.getMetricsState().successfulRetries++,this.getPriorityMetrics(e).successes++}recordRetryFailure(e,t){const r=this.getMetricsState();r.failedRetries++,t.response?t.response.status>=500?r.errorTypes.server5xx++:t.response.status>=400&&r.errorTypes.client4xx++:r.errorTypes.network++,this.getPriorityMetrics(e).failures++}recordRetryAttempt(e,t){var r;const s=this.getMetrics