@configdirector/client-sdk 1.9.0 → 1.9.1

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.
@@ -2,5 +2,5 @@ var e=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorC
2
2
  `?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
3
3
  `&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){var t;(t=this.onComment)==null||t.call(this,this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
4
4
  `)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent(c(c({},this.currentEvent),{},{id:this.lastEventId,data:e})),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
5
- `;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,Number.parseInt(e.value,10))}break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let h=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var g=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=h.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=c({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===h.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=h.CONNECTING,this._fetch(this.url,c(c({},this.requestOptions),{},{body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`})).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){var t=this;let{body:n,status:r}=e;if(r===204){t.disconnected();return}if(r>=400){t.scheduleReconnect({status:r});return}if(!n)throw new d(`The server response did not have a body`);t._readyState=h.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new m({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,i),t.scheduleReconnect({status:r,error:new u(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return c(c({},this.headers),e)}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=h.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new p(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new f(`${n} must be a function`);return e}};const _=e=>new g(e);var v=class{constructor(e){this.options=e,this.eventEmitter=new l,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=new Promise((t,r)=>{n.eventSource=_({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:i.instanceId,ephemeral:i.ephemeral}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([a,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(t,n){let r=t==null?0:t;return new e(`${`Connection failed with status: ${t==null?`unknown`:t}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;this.connectionGeneration++,(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const ee=(e,n)=>{if(e.trim().length==0)throw new t(`Invalid config key. The key of a value cannot be empty.`);return te(e,n)},te=(e,n)=>{switch(typeof n){case`boolean`:return{type:`boolean`,value:n?`true`:`false`};case`number`:return y(e,n);case`string`:return{type:`string`,value:n};case`object`:if(n!==null)return x(e,n,``),{type:`json`,value:JSON.stringify(n)}}throw new t(`Invalid value for '${e}': ${w(n)}. Use a boolean, a number, a string, a plain object, or an array.`)},y=(e,n)=>{if(!Number.isFinite(n))throw new t(`Invalid value for '${e}': ${w(n)} is not a finite number.`);if(Number.isInteger(n)){if(!Number.isSafeInteger(n))throw new t(`Invalid value for '${e}': ${n} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(n)}}return{type:`float`,value:b(n)}},b=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},x=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw S(e,n,`${w(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>x(e,t,`${n}[${r}]`));return}if(C(t)){for(let[r,i]of Object.entries(t))x(e,i,n?`${n}.${r}`:r);return}throw S(e,n,`${w(t)} cannot be encoded as JSON`)}},S=(e,n,r)=>new t(`Invalid value for '${e}'${n?` at '${n}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),C=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=e=>{if(e===null)return`null`;if(typeof e==`function`)return`a function`;if(typeof e==`object`){var t,n;return`a ${(t=(n=e.constructor)==null?void 0:n.name)==null?`object`:t} instance`}return typeof e==`symbol`?`a symbol`:String(e)},T=(e,t,n,r)=>{let i=ee(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},E={environmentId:`offline`,projectId:`offline`};var D=class{constructor(e){this.source=e,this.emitter=new l,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){var e=this;let t=ne(e.source);return e.emitter.emit(`configSetReceived`,c(c({},E),{},{kind:`full`,configs:t})),e}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const ne=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return re(e.values);case`rejected`:throw new n(e.message)}},re=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,T(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof t?new n(`The offline values could not be loaded. ${e.message}`):e}},ie=(e,n,r)=>{var i;if((n==null?void 0:n.mode)===`offline`)return{kind:`stay-offline`,source:oe(n)};let a=(i=n==null?void 0:n.mode)==null?`streaming`:i;if(!e||e.trim().length==0)throw new t(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`);return(n==null?void 0:n.values)===void 0?{kind:`connect`,mode:a,clientSdkKey:e,baseUrl:ae(n==null?void 0:n.url,r)}:{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${a}'.`}}},ae=(e,n)=>{if(!e)return`https://client-sdk-api.configdirector.com`;try{return n(e)}catch(n){throw new t(`Invalid base URL '${e}'. Parsing failed: ${n}`)}},oe=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},O=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},k=e=>e===`number`||e===`bigint`,se=new Set([`boolean`,`integer`,`float`]),ce=(e,t)=>{let n=e.value,r=O(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return F(n,t,r,e.valueId);if(typeof t==`string`)return se.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=A(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(k(typeof t)&&e.type===`integer`){let i=j(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(k(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=M(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},A=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},j=e=>{let t=N(e);return t==null?void 0:Math.trunc(t)},M=e=>N(e),N=e=>{if(!e||!P(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},P=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},F=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return I(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},I=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},L={off:-1,error:0,warn:1,info:2,debug:3},R=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,c(c({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var z=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=R()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){if(L[this.level]>=L[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},B=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const V=(e,t)=>new z(e==null?`warn`:e,t==null?new B:t),H={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},U=(e,t)=>new URL(e,t==null?void 0:t.toString()),W=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},G=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),K=e=>{try{return e(globalThis)}catch(e){return}},le=()=>K(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),ue=()=>K(e=>{var t;return(t=e.location)==null?void 0:t.host}),q=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},J=`configdirector-sdk:instance-id`,Y=1e3,de=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,X=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},Z=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=X(n,2166136261);return X(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},fe=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!de.test(n)?!1:i===Z(n,r)},pe=async(e,t)=>{let n;try{n=await e.getItem(J)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}return fe(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},me=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:Z(t,r)};try{return await e.setItem(J,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},he=async(e,t,n,r)=>{let i=await pe(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await me(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},ge=(e,t=q())=>{let n=G();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${Y}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},Y)});return Promise.race([he(t,n,r,e),a]).finally(()=>clearTimeout(i))};var _e=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(t){var n=this;if(!t.ok)throw n.isStatusFatal(t.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(t.status,await t.text())):new e(`Connection failed with status: ${t.status}`,t.status)}handleFetchError(t){throw this.isFetchErrorFatal(t)?(this.fatalError=!0,this.close(),new e(`Connection failed with fatal error: ${t}. This is an unrecoverable error, retry attempts will be ignored.`)):t instanceof SyntaxError?new e(`Failed to parse the response from the server: ${t}`):new e(`Connection failed with error: ${t}.`)}prepareFatalResponseStatusError(t,n){var r,i;let a=t==null?0:t;return new e(`${`Connection failed with status: ${t==null?`unknown`:t}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const ve=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),c(c({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var ye=class extends _e{constructor(e){var t;super(),this.options=e,this.eventEmitter=new l,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=(t=e.pollingInterval)==null?60:t}async connect(e,t){var n=this;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await ve(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const be=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,xe=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!be(t))return!1;return!0},Se=e=>e==null||typeof e==`string`&&xe(e),Ce=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},we=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},Te=e=>{let t=e==null?void 0:e.kind;return Se(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:we(Ce(t),128)}},Ee=e=>e>=55296&&e<=56319,De=e=>e>=56320&&e<=57343,Oe=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:Ee(r)&&n+1<e.length&&De(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},Q=`configdirector-sdk:cached-values:`,ke=256*1024,Ae=(e,t,n)=>{var r;if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if((t==null?void 0:t.enabled)===!1)return{kind:`no cache`,reason:`turned off`};let i=(r=t==null?void 0:t.provider)==null?n==null?void 0:n(e.clientSdkKey):r;return i?{kind:`cache`,provider:i,clientSdkKey:e.clientSdkKey}:{kind:`no cache`,reason:`no provider available`}},$=(e,t)=>{var n;let r=(n=e==null?void 0:e.kind)==null?`user`:n;return(e==null?void 0:e.id)==null?{contextKind:r,anonymousInstanceId:t}:{contextKind:r,contextId:e.id}},je=(e,t)=>e.contextKind===t.contextKind?`contextId`in e&&`contextId`in t?e.contextId===t.contextId:`anonymousInstanceId`in e&&`anonymousInstanceId`in t?e.anonymousInstanceId===t.anonymousInstanceId:!1:!1,Me=(e,t,n)=>n?`live values already arrived`:je(e.contextTag,t)?`adopt`:`context mismatch`,Ne=e=>{if(!e||typeof e!=`object`)return!1;let{contextKind:t,contextId:n,anonymousInstanceId:r}=e;return typeof t==`string`?typeof n==`string`||typeof r==`string`:!1},Pe=e=>!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.key==`string`),Fe=(e,t)=>{if(!t||typeof t!=`object`)return!1;let n=t;return n.formatVersion===1&&n.clientSdkKey===e&&Ne(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&Pe(n.configs)&&typeof n.receivedAt==`number`};var Ie=class{constructor(e,t,n){this.provider=e,this.clientSdkKey=t,this.logger=n,this.warned=new Set,this.writing=!1}read(){return this.pendingRead!=null||(this.pendingRead=this.readEntry()),this.pendingRead}replace(e){this.queuedCachedValues=e,this.writeQueued()}async readEntry(){var e=this;let t;try{t=await e.provider.read()}catch(t){return e.warnOnce(`read failed`,`Could not read the values kept on the device, starting without them:`,t),{outcome:`failed`}}if(t==null||t===``)return{outcome:`nothing stored`};let n=e.parseEntry(t);return n?{outcome:`stored`,cachedValues:n}:(e.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await e.removeEntry(),{outcome:`unreadable`})}parseEntry(e){try{let t=JSON.parse(e);return Fe(this.clientSdkKey,t)?t:void 0}catch(e){return}}async writeQueued(){var e=this;if(!e.writing){e.writing=!0;try{for(;e.queuedCachedValues;){let t=e.queuedCachedValues;e.queuedCachedValues=void 0,await e.writeEntry(t)}}finally{e.writing=!1}}}async writeEntry(e){var t=this;let n=c({formatVersion:1,clientSdkKey:t.clientSdkKey},e),r=JSON.stringify(n),i=Oe(r),a=t.provider.sizeLimit();if(i>a){t.warnOnce(`over the size limit`,`The values received (${i} bytes) exceed the caching provider's limit of ${a} bytes, so no values are kept on the device`),await t.removeEntry();return}try{await t.provider.write(r)}catch(e){t.warnOnce(`write failed`,`Could not keep the values on the device:`,e)}}async removeEntry(){var e=this;try{await e.provider.remove()}catch(t){e.warnOnce(`remove failed`,`Could not remove the values kept on the device:`,t)}}warnOnce(e,t,...n){this.warned.has(e)||(this.warned.add(e),this.logger.warn(`[ConfigDirectorClient] ${t}`,...n))}},Le=class e{static from(t,n,r,i,a){return typeof n==`object`?new e(t,void 0,r,n,a):new e(t,n,r,i,a)}constructor(e,t,n,r,i){var a,o,s,u,d,f,p,m,h,g,_;this.handlersMap=new Map,this.eventEmitter=new l,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=(a=r==null?void 0:r.logger)==null?V():a,this.clientSession=ge(this.logger,i==null?void 0:i.instanceIdStorage),this.timeout=(o=r==null||(s=r.connection)==null?void 0:s.timeout)==null?3e3:o;let v=(u=i==null?void 0:i.urlFactory)==null?U:u;this.connectionPlan=ie(t,r==null?void 0:r.connection,v),this.cachedValuesStore=this.buildCachedValuesStore(Ae(this.connectionPlan,r==null?void 0:r.caching,i==null?void 0:i.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=(d=i==null?void 0:i.transport)==null?this.buildTransport(n,r,v,i):d,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,this.servingCachedValues=!1,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=c(c({},this.configSet.configs),e.configs),this.keepValuesOnTheDevice(this.configSet);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r==null||(f=r.hooks)==null?void 0:f.clientReady),this.registerHandler(`configEvaluated`,r==null||(p=r.hooks)==null?void 0:p.configEvaluated),this.registerHandler(`configsUpdated`,r==null||(m=r.hooks)==null?void 0:m.configsUpdated),this.registerHandler(`contextUpdated`,r==null||(h=r.hooks)==null?void 0:h.contextUpdated),this.registerHandler(`connectionError`,r==null||(g=r.hooks)==null?void 0:g.connectionError),this.registerHandler(`cachedValuesLoaded`,r==null||(_=r.hooks)==null?void 0:_.cachedValuesLoaded)}buildCachedValuesStore(e){switch(e.kind){case`no cache`:this.logger.debug(`[ConfigDirectorClient] No values are kept on the device: ${e.reason}`);return;case`cache`:{let t=new Ie(e.provider,e.clientSdkKey,this.logger);return t.read(),t}}}startCachedValuesAdoption(){let e=this.cachedValuesStore;!e||this.cachedValuesAdoptionStarted||(this.cachedValuesAdoptionStarted=!0,this.adoptCachedValues(e))}async adoptCachedValues(e){var t=this;let n=await e.read();switch(n.outcome){case`nothing stored`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:r}=await t.clientSession,i=$(t.submittedContext,r),a=Me(n.cachedValues,i,t.hasReceivedConfigSet);switch(a){case`adopt`:t.serveCachedValues(n.cachedValues);return;case`live values already arrived`:case`context mismatch`:t.logger.debug(`[ConfigDirectorClient] The values kept on the device were not adopted: ${a}`);return}}serveCachedValues(e){let{environmentId:t,projectId:n,configs:r}=e;this.configSet={environmentId:t,projectId:n,configs:r,kind:`full`},this.servingCachedValues=!0;let i=Object.keys(r);this.emit(`cachedValuesLoaded`,{}),this.emit(`configsUpdated`,{keys:i,removedKeys:[]}),this.updateWatchers(i),this.logger.debug(`[ConfigDirectorClient] Serving the values kept on the device until live values arrive:`,{keys:i})}keepValuesOnTheDevice(e){let t=this.cachedValuesStore;if(!t)return;let n=this.submittedContext,r=Date.now();this.clientSession.then(({instanceId:i})=>t.replace({contextTag:$(n,i),environmentId:e.environmentId,projectId:e.projectId,configs:e.configs,receivedAt:r}))}servedReason(e){return this.servingCachedValues&&e===`found-match`?`cached`:e}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=W(t,{defaultSeconds:60,minimumSeconds:30});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return H;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t==null?void 0:t.metadata})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new D(i.source);case`connect`:var a,o;return new(this.getTransportConstructor(i.mode))({clientSession:this.clientSession,clientSdkKey:i.clientSdkKey,baseUrl:i.baseUrl,resolveUrl:n,metaContext:c(c({},t==null?void 0:t.metadata),{},{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:le(),host:ue()}),logger:this.logger,fetch:r==null?void 0:r.fetch,connectionRetryDelay:(a=r==null?void 0:r.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):a,pollingInterval:this.pollingIntervalFor(i.mode,t==null||(o=t.connection)==null?void 0:o.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return ye;case`streaming`:return v}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){var t=this;switch(t.connectionPlan.kind){case`connect`:await t.submitContext(e,`context update`);return;case`stay-offline`:t.storeContext(t.admittedContextFor(e,`context update`));return}}storeContext(e){this.currentContext=e,this.emit(`contextUpdated`,{context:e})}async submitContext(e,t){var n=this;await n.connectToTransport(n.admittedContextFor(e,t),t)}admittedContextFor(e,t){let n=Te(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){var r=this;r.submittedContext=e,t===`initialization`&&r.startCachedValuesAdoption();try{r.ready=!1,r.readyPromise=new Promise(e=>{r.readyResolve=e}).then(e=>{e||(r.ready=!0,r.initializing=!1,r.emit(`clientReady`,{action:t}),r.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await r.transport.connect(e==null?{}:e,r.timeout,t),r.currentContext=e,r.telemetryClient.updateContext(e).catch(e=>r.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),r.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-n,a=r.timeout-i;clearTimeout(r.timeoutTimer),r.timeoutTimer=void 0,a>0&&await Promise.race([r.readyPromise,new Promise(e=>{r.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(r.timeoutTimer)),r.ready||r.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${r.timeout}ms. ${r.timeoutWarningDetails()}`)}catch(e){if(e instanceof n)throw r.initializing=!1,e;r.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`;case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&(n==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:O(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ce(t,n),s=this.servedReason(o.reason);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:s}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:s,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}validateDefaultValue(e){if(e==null)throw new t(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new t(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1;return}}async resumeNetwork(){var e=this;switch(e.connectionPlan.kind){case`stay-offline`:return;case`connect`:await e.connectToTransport(e.currentContext,`network resume`);return}}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{U as a,T as c,e as d,n as f,q as i,l,Q as n,H as o,t as p,ke as r,V as s,Le as t,c as u};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-BgO5uN9D.mjs.map
5
+ `;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,Number.parseInt(e.value,10))}break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let h=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var g=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=h.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=c({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===h.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=h.CONNECTING,this._fetch(this.url,c(c({},this.requestOptions),{},{body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`})).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){var t=this;let{body:n,status:r}=e;if(r===204){t.disconnected();return}if(r>=400){t.scheduleReconnect({status:r});return}if(!n)throw new d(`The server response did not have a body`);t._readyState=h.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new m({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,i),t.scheduleReconnect({status:r,error:new u(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return c(c({},this.headers),e)}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=h.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new p(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new f(`${n} must be a function`);return e}};const _=e=>new g(e);var v=class{constructor(e){this.options=e,this.eventEmitter=new l,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=new Promise((t,r)=>{n.eventSource=_({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:i.instanceId,ephemeral:i.ephemeral}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([a,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(t,n){let r=t==null?0:t;return new e(`${`Connection failed with status: ${t==null?`unknown`:t}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;this.connectionGeneration++,(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const ee=(e,n)=>{if(e.trim().length==0)throw new t(`Invalid config key. The key of a value cannot be empty.`);return te(e,n)},te=(e,n)=>{switch(typeof n){case`boolean`:return{type:`boolean`,value:n?`true`:`false`};case`number`:return y(e,n);case`string`:return{type:`string`,value:n};case`object`:if(n!==null)return x(e,n,``),{type:`json`,value:JSON.stringify(n)}}throw new t(`Invalid value for '${e}': ${w(n)}. Use a boolean, a number, a string, a plain object, or an array.`)},y=(e,n)=>{if(!Number.isFinite(n))throw new t(`Invalid value for '${e}': ${w(n)} is not a finite number.`);if(Number.isInteger(n)){if(!Number.isSafeInteger(n))throw new t(`Invalid value for '${e}': ${n} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(n)}}return{type:`float`,value:b(n)}},b=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},x=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw S(e,n,`${w(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>x(e,t,`${n}[${r}]`));return}if(C(t)){for(let[r,i]of Object.entries(t))x(e,i,n?`${n}.${r}`:r);return}throw S(e,n,`${w(t)} cannot be encoded as JSON`)}},S=(e,n,r)=>new t(`Invalid value for '${e}'${n?` at '${n}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),C=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=e=>{if(e===null)return`null`;if(typeof e==`function`)return`a function`;if(typeof e==`object`){var t,n;return`a ${(t=(n=e.constructor)==null?void 0:n.name)==null?`object`:t} instance`}return typeof e==`symbol`?`a symbol`:String(e)},T=(e,t,n,r)=>{let i=ee(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},E={environmentId:`offline`,projectId:`offline`};var D=class{constructor(e){this.source=e,this.emitter=new l,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){var e=this;let t=ne(e.source);return e.emitter.emit(`configSetReceived`,c(c({},E),{},{kind:`full`,configs:t})),e}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const ne=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return re(e.values);case`rejected`:throw new n(e.message)}},re=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,T(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof t?new n(`The offline values could not be loaded. ${e.message}`):e}},ie=(e,n,r)=>{var i;if((n==null?void 0:n.mode)===`offline`)return{kind:`stay-offline`,source:oe(n)};let a=(i=n==null?void 0:n.mode)==null?`streaming`:i;if(!e||e.trim().length==0)throw new t(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`);return(n==null?void 0:n.values)===void 0?{kind:`connect`,mode:a,clientSdkKey:e,baseUrl:ae(n==null?void 0:n.url,r)}:{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${a}'.`}}},ae=(e,n)=>{if(!e)return`https://client-sdk-api.configdirector.com`;try{return n(e)}catch(n){throw new t(`Invalid base URL '${e}'. Parsing failed: ${n}`)}},oe=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},O=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},k=e=>e===`number`||e===`bigint`,se=new Set([`boolean`,`integer`,`float`]),ce=(e,t)=>{let n=e.value,r=O(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return F(n,t,r,e.valueId);if(typeof t==`string`)return se.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=A(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(k(typeof t)&&e.type===`integer`){let i=j(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(k(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=M(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},A=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},j=e=>{let t=N(e);return t==null?void 0:Math.trunc(t)},M=e=>N(e),N=e=>{if(!e||!P(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},P=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},F=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return I(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},I=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},L={off:-1,error:0,warn:1,info:2,debug:3},R=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,c(c({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var z=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=R()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){if(L[this.level]>=L[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},B=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const V=(e,t)=>new z(e==null?`warn`:e,t==null?new B:t),H={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},U=(e,t)=>new URL(e,t==null?void 0:t.toString()),W=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},G=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),K=e=>{try{return e(globalThis)}catch(e){return}},le=()=>K(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),ue=()=>K(e=>{var t;return(t=e.location)==null?void 0:t.host}),q=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},J=`configdirector-sdk:instance-id`,Y=1e3,de=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,X=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},Z=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=X(n,2166136261);return X(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},fe=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!de.test(n)?!1:i===Z(n,r)},pe=async(e,t)=>{let n;try{n=await e.getItem(J)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}return fe(r)?{outcome:`stored`,instanceId:r.id}:(t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`})},me=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:Z(t,r)};try{return await e.setItem(J,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},he=async(e,t,n,r)=>{let i=await pe(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await me(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},ge=(e,t=q())=>{let n=G();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${Y}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},Y)});return Promise.race([he(t,n,r,e),a]).finally(()=>clearTimeout(i))};var _e=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(t){var n=this;if(!t.ok)throw n.isStatusFatal(t.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(t.status,await t.text())):new e(`Connection failed with status: ${t.status}`,t.status)}handleFetchError(t){throw this.isFetchErrorFatal(t)?(this.fatalError=!0,this.close(),new e(`Connection failed with fatal error: ${t}. This is an unrecoverable error, retry attempts will be ignored.`)):t instanceof SyntaxError?new e(`Failed to parse the response from the server: ${t}`):new e(`Connection failed with error: ${t}.`)}prepareFatalResponseStatusError(t,n){var r,i;let a=t==null?0:t;return new e(`${`Connection failed with status: ${t==null?`unknown`:t}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const ve=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),c(c({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var ye=class extends _e{constructor(e){var t;super(),this.options=e,this.eventEmitter=new l,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=(t=e.pollingInterval)==null?60:t}async connect(e,t){var n=this;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await ve(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const be=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,xe=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!be(t))return!1;return!0},Se=e=>e==null||typeof e==`string`&&xe(e),Ce=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},we=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},Te=e=>{let t=e==null?void 0:e.kind;return Se(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:we(Ce(t),128)}},Ee=e=>e>=55296&&e<=56319,De=e=>e>=56320&&e<=57343,Oe=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:Ee(r)&&n+1<e.length&&De(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},Q=`configdirector-sdk:cached-values:`,ke=256*1024,Ae=(e,t,n)=>{var r;if(e.kind===`stay-offline`)return{kind:`no cache`,reason:`offline mode`};if((t==null?void 0:t.enabled)===!1)return{kind:`no cache`,reason:`turned off`};let i=(r=t==null?void 0:t.provider)==null?n==null?void 0:n(e.clientSdkKey):r;return i?{kind:`cache`,provider:i,clientSdkKey:e.clientSdkKey}:{kind:`no cache`,reason:`no provider available`}},$=(e,t)=>{var n;let r=(n=e==null?void 0:e.kind)==null?`user`:n;return(e==null?void 0:e.id)==null?{contextKind:r,anonymousInstanceId:t}:{contextKind:r,contextId:e.id}},je=(e,t)=>e.contextKind===t.contextKind?`contextId`in e&&`contextId`in t?e.contextId===t.contextId:`anonymousInstanceId`in e&&`anonymousInstanceId`in t?e.anonymousInstanceId===t.anonymousInstanceId:!1:!1,Me=(e,t,n)=>n?`live values already arrived`:je(e.contextTag,t)?`adopt`:`context mismatch`,Ne=e=>{if(!e||typeof e!=`object`)return!1;let{contextKind:t,contextId:n,anonymousInstanceId:r}=e;return typeof t==`string`?typeof n==`string`||typeof r==`string`:!1},Pe=e=>!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.key==`string`),Fe=(e,t)=>{if(!t||typeof t!=`object`)return!1;let n=t;return n.formatVersion===1&&n.clientSdkKey===e&&Ne(n.contextTag)&&typeof n.environmentId==`string`&&typeof n.projectId==`string`&&Pe(n.configs)&&typeof n.receivedAt==`number`};var Ie=class{constructor(e,t,n){this.provider=e,this.clientSdkKey=t,this.logger=n,this.warned=new Set,this.writing=!1}read(){return this.pendingRead!=null||(this.pendingRead=this.readEntry()),this.pendingRead}replace(e){this.queuedCachedValues=e,this.writeQueued()}async readEntry(){var e=this;let t;try{t=await e.provider.read()}catch(t){return e.warnOnce(`read failed`,`Could not read the values kept on the device, starting without them:`,t),{outcome:`failed`}}if(t==null||t===``)return{outcome:`nothing stored`};let n=e.parseEntry(t);return n?{outcome:`stored`,cachedValues:n}:(e.warnOnce(`unreadable`,`The values kept on the device could not be read and were removed, starting without them`),await e.removeEntry(),{outcome:`unreadable`})}parseEntry(e){try{let t=JSON.parse(e);return Fe(this.clientSdkKey,t)?t:void 0}catch(e){return}}async writeQueued(){var e=this;if(!e.writing){e.writing=!0;try{for(;e.queuedCachedValues;){let t=e.queuedCachedValues;e.queuedCachedValues=void 0,await e.writeEntry(t)}}finally{e.writing=!1}}}async writeEntry(e){var t=this;let n=c({formatVersion:1,clientSdkKey:t.clientSdkKey},e),r=JSON.stringify(n),i=Oe(r),a=t.provider.sizeLimit();if(i>a){t.warnOnce(`over the size limit`,`The values received (${i} bytes) exceed the caching provider's limit of ${a} bytes, so no values are kept on the device`),await t.removeEntry();return}try{await t.provider.write(r)}catch(e){t.warnOnce(`write failed`,`Could not keep the values on the device:`,e)}}async removeEntry(){var e=this;try{await e.provider.remove()}catch(t){e.warnOnce(`remove failed`,`Could not remove the values kept on the device:`,t)}}warnOnce(e,t,...n){this.warned.has(e)||(this.warned.add(e),this.logger.warn(`[ConfigDirectorClient] ${t}`,...n))}},Le=class e{static from(t,n,r,i,a){return typeof n==`object`?new e(t,void 0,r,n,a):new e(t,n,r,i,a)}constructor(e,t,n,r,i){var a,o,s,u,d,f,p,m,h,g,_;this.handlersMap=new Map,this.eventEmitter=new l,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.servingCachedValues=!1,this.cachedValuesAdoptionStarted=!1,this.logger=(a=r==null?void 0:r.logger)==null?V():a,this.clientSession=ge(this.logger,i==null?void 0:i.instanceIdStorage),this.timeout=(o=r==null||(s=r.connection)==null?void 0:s.timeout)==null?3e3:o;let v=(u=i==null?void 0:i.urlFactory)==null?U:u;this.connectionPlan=ie(t,r==null?void 0:r.connection,v),this.cachedValuesStore=this.buildCachedValuesStore(Ae(this.connectionPlan,r==null?void 0:r.caching,i==null?void 0:i.platformCachingProvider)),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=(d=i==null?void 0:i.transport)==null?this.buildTransport(n,r,v,i):d,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,this.servingCachedValues=!1,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=c(c({},this.configSet.configs),e.configs),this.keepValuesOnTheDevice(this.configSet);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r==null||(f=r.hooks)==null?void 0:f.clientReady),this.registerHandler(`configEvaluated`,r==null||(p=r.hooks)==null?void 0:p.configEvaluated),this.registerHandler(`configsUpdated`,r==null||(m=r.hooks)==null?void 0:m.configsUpdated),this.registerHandler(`contextUpdated`,r==null||(h=r.hooks)==null?void 0:h.contextUpdated),this.registerHandler(`connectionError`,r==null||(g=r.hooks)==null?void 0:g.connectionError),this.registerHandler(`cachedValuesLoaded`,r==null||(_=r.hooks)==null?void 0:_.cachedValuesLoaded)}buildCachedValuesStore(e){switch(e.kind){case`no cache`:this.logger.debug(`[ConfigDirectorClient] No values are kept on the device: ${e.reason}`);return;case`cache`:{let t=new Ie(e.provider,e.clientSdkKey,this.logger);return t.read(),t}}}startCachedValuesAdoption(){let e=this.cachedValuesStore;!e||this.cachedValuesAdoptionStarted||(this.cachedValuesAdoptionStarted=!0,this.adoptCachedValues(e))}async adoptCachedValues(e){var t=this;let n=await e.read();switch(n.outcome){case`nothing stored`:case`unreadable`:case`failed`:return;case`stored`:break}let{instanceId:r}=await t.clientSession,i=$(t.submittedContext,r),a=Me(n.cachedValues,i,t.hasReceivedConfigSet);switch(a){case`adopt`:t.serveCachedValues(n.cachedValues);return;case`live values already arrived`:case`context mismatch`:t.logger.debug(`[ConfigDirectorClient] The values kept on the device were not adopted: ${a}`);return}}serveCachedValues(e){let{environmentId:t,projectId:n,configs:r}=e;this.configSet={environmentId:t,projectId:n,configs:r,kind:`full`},this.servingCachedValues=!0;let i=Object.keys(r);this.emit(`cachedValuesLoaded`,{}),this.emit(`configsUpdated`,{keys:i,removedKeys:[]}),this.updateWatchers(i),this.logger.debug(`[ConfigDirectorClient] Serving the values kept on the device until live values arrive:`,{keys:i})}keepValuesOnTheDevice(e){let t=this.cachedValuesStore;if(!t)return;let n=this.submittedContext,r=Date.now();this.clientSession.then(({instanceId:i})=>t.replace({contextTag:$(n,i),environmentId:e.environmentId,projectId:e.projectId,configs:e.configs,receivedAt:r}))}servedReason(e){return this.servingCachedValues&&e===`found-match`?`cached`:e}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=W(t,{defaultSeconds:60,minimumSeconds:30});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return H;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t==null?void 0:t.metadata,clientSession:this.clientSession})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new D(i.source);case`connect`:var a,o;return new(this.getTransportConstructor(i.mode))({clientSession:this.clientSession,clientSdkKey:i.clientSdkKey,baseUrl:i.baseUrl,resolveUrl:n,metaContext:c(c({},t==null?void 0:t.metadata),{},{sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:le(),host:ue()}),logger:this.logger,fetch:r==null?void 0:r.fetch,connectionRetryDelay:(a=r==null?void 0:r.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):a,pollingInterval:this.pollingIntervalFor(i.mode,t==null||(o=t.connection)==null?void 0:o.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return ye;case`streaming`:return v}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){var t=this;switch(t.connectionPlan.kind){case`connect`:await t.submitContext(e,`context update`);return;case`stay-offline`:t.storeContext(t.admittedContextFor(e,`context update`));return}}storeContext(e){this.currentContext=e,this.emit(`contextUpdated`,{context:e})}async submitContext(e,t){var n=this;await n.connectToTransport(n.admittedContextFor(e,t),t)}admittedContextFor(e,t){let n=Te(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){var r=this;r.submittedContext=e,t===`initialization`&&r.startCachedValuesAdoption();try{r.ready=!1,r.readyPromise=new Promise(e=>{r.readyResolve=e}).then(e=>{e||(r.ready=!0,r.initializing=!1,r.emit(`clientReady`,{action:t}),r.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await r.transport.connect(e==null?{}:e,r.timeout,t),r.currentContext=e,r.telemetryClient.updateContext(e).catch(e=>r.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),r.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-n,a=r.timeout-i;clearTimeout(r.timeoutTimer),r.timeoutTimer=void 0,a>0&&await Promise.race([r.readyPromise,new Promise(e=>{r.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(r.timeoutTimer)),r.ready||r.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${r.timeout}ms. ${r.timeoutWarningDetails()}`)}catch(e){if(e instanceof n)throw r.initializing=!1,e;r.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`;case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&(n==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:O(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ce(t,n),s=this.servedReason(o.reason);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:s}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:s,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}validateDefaultValue(e){if(e==null)throw new t(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new t(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1;return}}async resumeNetwork(){var e=this;switch(e.connectionPlan.kind){case`stay-offline`:return;case`connect`:await e.connectToTransport(e.currentContext,`network resume`);return}}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{U as a,T as c,e as d,n as f,q as i,l,Q as n,H as o,t as p,ke as r,V as s,Le as t,c as u};
6
+ //# sourceMappingURL=DefaultConfigDirectorClient-D6d8ZpDr.mjs.map