@configdirector/openfeature-web-provider 1.6.0 → 1.6.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,4 +2,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
|
|
|
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(`:`)){this.onComment?.(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({...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`:/^\d+$/.test(e.value)&&this.onRetry?.(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 l=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var u=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=l.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),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===l.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=l.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=l.CONNECTING,this._fetch(this.url,{...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){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new a(`The server response did not have a body`);this._readyState=l.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new c({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new i(`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=l.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...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=l.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`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 o(`${n} must be a function`);return e}};const d=e=>new u(e);var f=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){this.eventSource&&this.close();let n=new Promise((t,n)=>{this.eventSource=d({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:this.options.fetch,body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);if(!t){let t=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,t),n(t)}return t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt),n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onError:e=>{this.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});return clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,Promise.race([n,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(this),t)})]).finally(()=>clearTimeout(this.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(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}`:``}. 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(){this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const p=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},m=e=>e===`number`||e===`bigint`,h=new Set([`boolean`,`integer`,`float`]),g=(e,t)=>{let n=e.value,r=p(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return S(n,t,r,e.valueId);if(typeof t==`string`)return h.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=_(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(m(typeof t)&&e.type===`integer`){let i=v(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(m(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=y(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`}},_=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},v=e=>{let t=b(e);return t==null?void 0:Math.trunc(t)},y=e=>b(e),b=e=>{if(!e||!x(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},x=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},S=(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 C(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{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},C=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},w={off:-1,error:0,warn:1,info:2,debug:3},T=()=>{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,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var E=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=T()}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){w[this.level]>=w[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},D=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const O=(e,t)=>new E(e??`warn`,t??new D),k=(e,t)=>new URL(e,t?.toString()),A=e=>{if(e)try{return new URL(e)}catch(t){throw new r(`Invalid URL '${e}'. Parsing failed: ${t}`)}},j=(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.`},M=()=>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)}),N=`configdirector-sdk:instance-id`,P=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,F=(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},I=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=F(n,2166136261);return F(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},L=()=>{try{return globalThis.localStorage??void 0}catch{return}},ee=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||!P.test(n)?!1:i===I(n,r)},R=(e,t)=>{let n;try{n=e.getItem(N)}catch(e){t?.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch{t?.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!ee(r)){t?.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t?.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},z=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:I(t,r)};try{e.setItem(N,JSON.stringify(i))}catch(e){n?.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},B=e=>{let t=L();if(!t)return M();let n=R(t,e);if(n)return n;let r=M();return z(t,r,e),r};var V=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(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new n(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new n(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new n(`Failed to parse the response from the server: ${e}`):new n(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const H=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var U=class extends V{constructor(e){super(),this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e,t){this.clearPollingInterval();try{await this.fetchConfigs(e,t)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}async fetchConfigs(e,t){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let n=await H(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(n),n.status==200){let e=JSON.parse(await n.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.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 W=e=>{try{return e(globalThis)}catch{return}},G=()=>W(e=>e.navigator?.userAgent),K=()=>W(e=>e.location?.host);var q=class{constructor(e,n,r,i,a){this.handlersMap=new Map,this.eventEmitter=new t,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=i?.logger??O(),this.instanceId=B(this.logger),this.timeout=i?.connection?.timeout??3e3,this.validateSdkKeyPresence(n);let o=a?.urlFactory??k,s=this.parseUrl(i?.connection?.url,o)??`https://client-sdk-api.configdirector.com`;this.connectionMode=i?.connection?.mode??`streaming`,this.telemetryClient=e,this.transport=a?.transport??this.buildTransport(n,r,s,o,i,a),this.transport.on(`configSetReceived`,e=>{this.hasReceivedConfigSet=!0,this.readyResolve?.();let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs={...this.configSet.configs,...e.configs};let n=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n,removedKeys:t})}),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`,i?.hooks?.clientReady),this.registerHandler(`configEvaluated`,i?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,i?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,i?.hooks?.contextUpdated),this.registerHandler(`connectionError`,i?.hooks?.connectionError)}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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=j(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:{...i?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:G(),host:K()},logger:this.logger,fetch:a?.fetch,connectionRetryDelay:a?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.resolvePollingIntervalForMode(i?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return U;default:return f}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.initializing=!1,this.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout,t),this.currentContext=e,this.telemetryClient.updateContext(e),this.emit(`contextUpdated`,{context:e});let r=new Date().getTime()-n,i=this.timeout-r;clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,i>0&&await Promise.race([this.readyPromise,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(),i)})]).finally(()=>clearTimeout(this.timeoutTimer)),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}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){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigState(e,t,n.defaultValue);n.handler(r)})}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?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t){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:this.currentContext?.id,key:e,defaultValue:n,requestedType:p(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=g(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,type:t.type,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,evaluatedValueId:r.parsedValueId,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:r.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.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)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new r(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new r(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new r(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new r(`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(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){await this.connectToTransport(this.currentContext,`network resume`)}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close(),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};const J=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var Y=class{constructor(e){this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}startWorker(){if(this.worker)return this.worker;let e=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})));e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker().postMessage(t)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:J({value:e.defaultValue,type:e.type}),evaluatedValue:J({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const X=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},Z=Math.ceil(128/Math.log2(62)),Q=new TextEncoder,$=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,Q.encode(e?.toString()??``));return X(new Uint8Array(t,0,16),Z)},te=(e,t,n)=>{let r=n?.logger??O(),i=A(n?.connection?.url)??`https://client-sdk-api.configdirector.com`;return new q(new Y({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n?.metadata?.appName,appVersion:n?.metadata?.appVersion},logger:r,baseUrl:i,urlFactory:k,valueIdGenerator:$}),e,t,{...n,logger:r})};var ne=class t{constructor(n,r){this.awaitingRecovery=!1,this.metadata={name:t.name},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=te(n,{sdkName:`js-openfeature-web-provider`,sdkVersion:`1.6.0`},r),this.client.on(`clientReady`,()=>{this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(e.ProviderEvents.Ready))}),this.client.on(`configsUpdated`,({keys:t,removedKeys:n})=>{this.events.emit(e.ProviderEvents.ConfigurationChanged,{flagsChanged:[...t,...n]})})}async initialize(e){this.awaitingRecovery=!1,await this.client.initialize(this.mapContext(e)),this.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){this.awaitingRecovery=!1,await this.client.updateContext(this.mapContext(t)),this.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return this.evaluate(e,t)}resolveStringEvaluation(e,t){return this.evaluate(e,t)}resolveNumberEvaluation(e,t){return this.evaluate(e,t)}resolveObjectEvaluation(e,t){return this.evaluate(e,t)}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(t){if(!this.client.isReady)throw this.awaitingRecovery=!0,new e.ProviderNotReadyError(t)}evaluate(e,t){return{value:this.client.getValue(e,t)}}mapContext(e){if(!e)return{};let t=(e.targetingKey??e.id)?.toString(),n=e.name?.toString(),r=e?.traits||{},i=typeof r==`object`&&Object.keys(r).length>0,a=e.anonymous;return{id:t,name:n,traits:i?r:void 0,anonymous:typeof a==`boolean`?a:void 0}}};exports.ConfigDirectorProvider=ne;
|
|
5
|
+
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(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 l=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var u=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=l.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),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===l.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=l.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=l.CONNECTING,this._fetch(this.url,{...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){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new a(`The server response did not have a body`);this._readyState=l.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new c({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new i(`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=l.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...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=l.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`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 o(`${n} must be a function`);return e}};const d=e=>new u(e);var f=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){this.eventSource&&this.close();let n=new Promise((t,n)=>{this.eventSource=d({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:this.options.fetch,body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);if(!t){let t=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,t),n(t)}return t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt),n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onError:e=>{this.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});return clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,Promise.race([n,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(this),t)})]).finally(()=>clearTimeout(this.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(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}`:``}. 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(){this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const p=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},m=e=>e===`number`||e===`bigint`,h=new Set([`boolean`,`integer`,`float`]),g=(e,t)=>{let n=e.value,r=p(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return S(n,t,r,e.valueId);if(typeof t==`string`)return h.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=_(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(m(typeof t)&&e.type===`integer`){let i=v(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(m(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=y(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`}},_=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},v=e=>{let t=b(e);return t==null?void 0:Math.trunc(t)},y=e=>b(e),b=e=>{if(!e||!x(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},x=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},S=(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 C(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{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},C=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},w={off:-1,error:0,warn:1,info:2,debug:3},T=()=>{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,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var E=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=T()}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){w[this.level]>=w[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},D=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const O=(e,t)=>new E(e??`warn`,t??new D),k=(e,t)=>new URL(e,t?.toString()),A=e=>{if(e)try{return new URL(e)}catch(t){throw new r(`Invalid URL '${e}'. Parsing failed: ${t}`)}},j=(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.`},M=()=>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)}),N=`configdirector-sdk:instance-id`,P=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,F=(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},I=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=F(n,2166136261);return F(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},L=()=>{try{return globalThis.localStorage??void 0}catch{return}},ee=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||!P.test(n)?!1:i===I(n,r)},R=(e,t)=>{let n;try{n=e.getItem(N)}catch(e){t?.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch{t?.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!ee(r)){t?.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t?.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},z=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:I(t,r)};try{e.setItem(N,JSON.stringify(i))}catch(e){n?.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},B=e=>{let t=L();if(!t)return M();let n=R(t,e);if(n)return n;let r=M();return z(t,r,e),r};var V=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(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new n(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new n(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new n(`Failed to parse the response from the server: ${e}`):new n(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const H=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var U=class extends V{constructor(e){super(),this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??60}async connect(e,t){this.clearPollingInterval();try{await this.fetchConfigs(e,t)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}async fetchConfigs(e,t){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let n=await H(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(n),n.status==200){let e=JSON.parse(await n.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.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 W=e=>{try{return e(globalThis)}catch{return}},G=()=>W(e=>e.navigator?.userAgent),K=()=>W(e=>e.location?.host);var q=class{constructor(e,n,r,i,a){this.handlersMap=new Map,this.eventEmitter=new t,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=i?.logger??O(),this.instanceId=B(this.logger),this.timeout=i?.connection?.timeout??3e3,this.validateSdkKeyPresence(n);let o=a?.urlFactory??k,s=this.parseUrl(i?.connection?.url,o)??`https://client-sdk-api.configdirector.com`;this.connectionMode=i?.connection?.mode??`streaming`,this.telemetryClient=e,this.transport=a?.transport??this.buildTransport(n,r,s,o,i,a),this.transport.on(`configSetReceived`,e=>{this.hasReceivedConfigSet=!0,this.readyResolve?.();let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs={...this.configSet.configs,...e.configs};let n=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n,removedKeys:t})}),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`,i?.hooks?.clientReady),this.registerHandler(`configEvaluated`,i?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,i?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,i?.hooks?.contextUpdated),this.registerHandler(`connectionError`,i?.hooks?.connectionError)}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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=j(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:{...i?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:G(),host:K()},logger:this.logger,fetch:a?.fetch,connectionRetryDelay:a?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.resolvePollingIntervalForMode(i?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return U;default:return f}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.initializing=!1,this.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout,t),this.currentContext=e,this.telemetryClient.updateContext(e).catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),this.emit(`contextUpdated`,{context:e});let r=new Date().getTime()-n,i=this.timeout-r;clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,i>0&&await Promise.race([this.readyPromise,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(),i)})]).finally(()=>clearTimeout(this.timeoutTimer)),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}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){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigState(e,t,n.defaultValue);n.handler(r)})}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?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t){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:this.currentContext?.id,key:e,defaultValue:n,requestedType:p(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=g(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,type:t.type,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,evaluatedValueId:r.parsedValueId,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:r.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.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)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new r(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new r(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new r(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new r(`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(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){await this.connectToTransport(this.currentContext,`network resume`)}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close().catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,e)),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};const J=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var Y=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:J({value:e.defaultValue,type:e.type}),evaluatedValue:J({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const X=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},Z=Math.ceil(128/Math.log2(62)),Q=new TextEncoder,$=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,Q.encode(e?.toString()??``));return X(new Uint8Array(t,0,16),Z)},te=(e,t,n)=>{let r=n?.logger??O(),i=A(n?.connection?.url)??`https://client-sdk-api.configdirector.com`;return new q(new Y({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n?.metadata?.appName,appVersion:n?.metadata?.appVersion},logger:r,baseUrl:i,urlFactory:k,valueIdGenerator:$}),e,t,{...n,logger:r})};var ne=class t{constructor(n,r){this.awaitingRecovery=!1,this.metadata={name:t.name},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=te(n,{sdkName:`js-openfeature-web-provider`,sdkVersion:`1.6.1`},r),this.client.on(`clientReady`,()=>{this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(e.ProviderEvents.Ready))}),this.client.on(`configsUpdated`,({keys:t,removedKeys:n})=>{this.events.emit(e.ProviderEvents.ConfigurationChanged,{flagsChanged:[...t,...n]})})}async initialize(e){this.awaitingRecovery=!1,await this.client.initialize(this.mapContext(e)),this.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){this.awaitingRecovery=!1,await this.client.updateContext(this.mapContext(t)),this.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return this.evaluate(e,t)}resolveStringEvaluation(e,t){return this.evaluate(e,t)}resolveNumberEvaluation(e,t){return this.evaluate(e,t)}resolveObjectEvaluation(e,t){return this.evaluate(e,t)}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(t){if(!this.client.isReady)throw this.awaitingRecovery=!0,new e.ProviderNotReadyError(t)}evaluate(e,t){return{value:this.client.getValue(e,t)}}mapContext(e){if(!e)return{};let t=(e.targetingKey??e.id)?.toString(),n=e.name?.toString(),r=e?.traits||{},i=typeof r==`object`&&Object.keys(r).length>0,a=e.anonymous;return{id:t,name:n,traits:i?r:void 0,anonymous:typeof a==`boolean`?a:void 0}}};exports.ConfigDirectorProvider=ne;
|
|
@@ -2,5 +2,5 @@ import{OpenFeatureEventEmitter as e,ProviderEvents as t,ProviderNotReadyError as
|
|
|
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(h(h({},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 _=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var v=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=_.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=h({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===_.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=_.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=_.CONNECTING,this._fetch(this.url,h(h({},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 s(`The server response did not have a body`);t._readyState=_.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new g({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 o(`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=_.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return h(h({},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=_.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new l(`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 c(`${n} must be a function`);return e}};const y=e=>new v(e);var b=class{constructor(e){this.options=e,this.eventEmitter=new r,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;n.eventSource&&n.close();let r=new Promise((t,r)=>{n.eventSource=y({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:n.options.instanceId}),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([r,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(e,t){let n=e==null?0:e;return new i(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${t?` Error: ${t}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,n)}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;(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const x=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},S=e=>e===`number`||e===`bigint`,C=new Set([`boolean`,`integer`,`float`]),ee=(e,t)=>{let n=e.value,r=x(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return k(n,t,r,e.valueId);if(typeof t==`string`)return C.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=w(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(S(typeof t)&&e.type===`integer`){let i=T(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(S(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=E(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`}},w=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},T=e=>{let t=D(e);return t==null?void 0:Math.trunc(t)},E=e=>D(e),D=e=>{if(!e||!O(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},O=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},k=(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 A(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`}}},A=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},j={off:-1,error:0,warn:1,info:2,debug:3},M=()=>{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,h(h({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var te=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=M()}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(j[this.level]>=j[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},ne=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const N=(e,t)=>new te(e==null?`warn`:e,t==null?new ne:t),P=(e,t)=>new URL(e,t==null?void 0:t.toString()),F=e=>{if(e)try{return new URL(e)}catch(t){throw new a(`Invalid URL '${e}'. Parsing failed: ${t}`)}},I=`https://client-sdk-api.configdirector.com`,L=(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.`},R=()=>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)}),z=`configdirector-sdk:instance-id`,B=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,V=(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},H=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=V(n,2166136261);return V(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},U=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},W=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||!B.test(n)?!1:i===H(n,r)},G=(e,t)=>{let n;try{n=e.getItem(z)}catch(e){t==null||t.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch(e){t==null||t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!W(r)){t==null||t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t==null||t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},K=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:H(t,r)};try{e.setItem(z,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},q=e=>{let t=U();if(!t)return R();let n=G(t,e);if(n)return n;let r=R();return K(t,r,e),r};var J=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(e){var t=this;if(!e.ok)throw t.isStatusFatal(e.status)?(t.fatalError=!0,t.close(),t.prepareFatalResponseStatusError(e.status,await e.text())):new i(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new i(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new i(`Failed to parse the response from the server: ${e}`):new i(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){var n,r;let a=e==null?0:e;return new i(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((n=t==null||(r=t.trim())==null?void 0:r.length)==null?0:n)>0?` (${t})`:``}. 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 Y=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(),h(h({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var X=class extends J{constructor(e){var t;super(),this.options=e,this.eventEmitter=new r,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;n.clearPollingInterval();try{await n.fetchConfigs(e,t)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}async fetchConfigs(e,t){var n=this;if(n.fatalError){n.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await Y(t,n.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId,lastUpdateTimestamp:n.lastUpdateTimestamp})},n.logger);if(await n.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());n.lastUpdateTimestamp=e.timestamp,n.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{n.handleFetchError(e)}catch(e){throw n.fatalError&&n.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 Z=e=>{try{return e(globalThis)}catch(e){return}},re=()=>Z(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),ie=()=>Z(e=>{var t;return(t=e.location)==null?void 0:t.host});var ae=class{constructor(e,t,n,i,a){var o,s,c,l,u,d,f,p,m,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new r,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?N():o,this.instanceId=q(this.logger),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(t);let x=(l=a==null?void 0:a.urlFactory)==null?P:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?I:u;this.connectionMode=(f=i==null||(p=i.connection)==null?void 0:p.mode)==null?`streaming`:f,this.telemetryClient=e,this.transport=(m=a==null?void 0:a.transport)==null?this.buildTransport(t,n,S,x,i,a):m,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=h(h({},this.configSet.configs),e.configs);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`,i==null||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.connectionError)}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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=L(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:h(h({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:re(),host:ie()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return X;default:return b}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}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:x(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ee(t,n);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:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,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)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new a(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new a(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new a(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new a(`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(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}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(),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};const Q=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var $=class{constructor(e){var t,n,r,i;this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}startWorker(){if(this.worker)return this.worker;let e=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})));e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}async updateContext(e){var t=this;if(t.closePromise)return;let n={type:`UpdateContext`,payload:{context:e}};t.startWorker().postMessage(n)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return h(h({},e),{},{defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const oe=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},se=Math.ceil(128/Math.log2(62)),ce=new TextEncoder,le=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,ce.encode((t=e==null?void 0:e.toString())==null?``:t));return oe(new Uint8Array(n,0,16),se)},ue=(e,t,n)=>{var r,i,a,o,s;let c=(r=n==null?void 0:n.logger)==null?N():r,l=(i=F(n==null||(a=n.connection)==null?void 0:a.url))==null?I:i;return new ae(new $({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n==null||(o=n.metadata)==null?void 0:o.appName,appVersion:n==null||(s=n.metadata)==null?void 0:s.appVersion},logger:c,baseUrl:l,urlFactory:P,valueIdGenerator:le}),e,t,h(h({},n),{},{logger:c}))};var de=class r{constructor(n,i){this.awaitingRecovery=!1,this.metadata={name:r.name},this.runsOn=`client`,this.events=new e,this.client=ue(n,{sdkName:`js-openfeature-web-provider`,sdkVersion:`1.6.0`},i),this.client.on(`clientReady`,()=>{this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(t.Ready))}),this.client.on(`configsUpdated`,({keys:e,removedKeys:n})=>{this.events.emit(t.ConfigurationChanged,{flagsChanged:[...e,...n]})})}async initialize(e){var t=this;t.awaitingRecovery=!1,await t.client.initialize(t.mapContext(e)),t.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){var n=this;n.awaitingRecovery=!1,await n.client.updateContext(n.mapContext(t)),n.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return this.evaluate(e,t)}resolveStringEvaluation(e,t){return this.evaluate(e,t)}resolveNumberEvaluation(e,t){return this.evaluate(e,t)}resolveObjectEvaluation(e,t){return this.evaluate(e,t)}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(e){if(!this.client.isReady)throw this.awaitingRecovery=!0,new n(e)}evaluate(e,t){return{value:this.client.getValue(e,t)}}mapContext(e){var t,n,r;if(!e)return{};let i=(t=(n=e.targetingKey)==null?e.id:n)==null?void 0:t.toString(),a=(r=e.name)==null?void 0:r.toString(),o=(e==null?void 0:e.traits)||{},s=typeof o==`object`&&Object.keys(o).length>0,c=e.anonymous;return{id:i,name:a,traits:s?o:void 0,anonymous:typeof c==`boolean`?c:void 0}}};export{de as ConfigDirectorProvider};
|
|
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 _=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var v=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=_.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=h({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===_.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=_.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=_.CONNECTING,this._fetch(this.url,h(h({},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 s(`The server response did not have a body`);t._readyState=_.OPEN,t._onConnect(),t.reconnectAttempt=0;let i=new g({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 o(`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=_.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return h(h({},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=_.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new l(`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 c(`${n} must be a function`);return e}};const y=e=>new v(e);var b=class{constructor(e){this.options=e,this.eventEmitter=new r,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){var n=this;n.eventSource&&n.close();let r=new Promise((t,r)=>{n.eventSource=y({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:n.options.instanceId}),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([r,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(e,t){let n=e==null?0:e;return new i(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${t?` Error: ${t}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,n)}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;(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const x=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},S=e=>e===`number`||e===`bigint`,C=new Set([`boolean`,`integer`,`float`]),ee=(e,t)=>{let n=e.value,r=x(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return k(n,t,r,e.valueId);if(typeof t==`string`)return C.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=w(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(S(typeof t)&&e.type===`integer`){let i=T(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(S(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=E(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`}},w=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},T=e=>{let t=D(e);return t==null?void 0:Math.trunc(t)},E=e=>D(e),D=e=>{if(!e||!O(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},O=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},k=(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 A(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`}}},A=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},j={off:-1,error:0,warn:1,info:2,debug:3},M=()=>{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,h(h({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var te=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=M()}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(j[this.level]>=j[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},ne=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const N=(e,t)=>new te(e==null?`warn`:e,t==null?new ne:t),P=(e,t)=>new URL(e,t==null?void 0:t.toString()),F=e=>{if(e)try{return new URL(e)}catch(t){throw new a(`Invalid URL '${e}'. Parsing failed: ${t}`)}},I=`https://client-sdk-api.configdirector.com`,L=(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.`},R=()=>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)}),z=`configdirector-sdk:instance-id`,B=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,V=(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},H=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=V(n,2166136261);return V(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},U=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},W=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||!B.test(n)?!1:i===H(n,r)},G=(e,t)=>{let n;try{n=e.getItem(z)}catch(e){t==null||t.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch(e){t==null||t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!W(r)){t==null||t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t==null||t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},K=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:H(t,r)};try{e.setItem(z,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},q=e=>{let t=U();if(!t)return R();let n=G(t,e);if(n)return n;let r=R();return K(t,r,e),r};var J=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(e){var t=this;if(!e.ok)throw t.isStatusFatal(e.status)?(t.fatalError=!0,t.close(),t.prepareFatalResponseStatusError(e.status,await e.text())):new i(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new i(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new i(`Failed to parse the response from the server: ${e}`):new i(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){var n,r;let a=e==null?0:e;return new i(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((n=t==null||(r=t.trim())==null?void 0:r.length)==null?0:n)>0?` (${t})`:``}. 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 Y=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(),h(h({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var X=class extends J{constructor(e){var t;super(),this.options=e,this.eventEmitter=new r,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;n.clearPollingInterval();try{await n.fetchConfigs(e,t)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}async fetchConfigs(e,t){var n=this;if(n.fatalError){n.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await Y(t,n.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId,lastUpdateTimestamp:n.lastUpdateTimestamp})},n.logger);if(await n.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());n.lastUpdateTimestamp=e.timestamp,n.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{n.handleFetchError(e)}catch(e){throw n.fatalError&&n.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 Z=e=>{try{return e(globalThis)}catch(e){return}},re=()=>Z(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),ie=()=>Z(e=>{var t;return(t=e.location)==null?void 0:t.host});var ae=class{constructor(e,t,n,i,a){var o,s,c,l,u,d,f,p,m,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new r,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?N():o,this.instanceId=q(this.logger),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(t);let x=(l=a==null?void 0:a.urlFactory)==null?P:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?I:u;this.connectionMode=(f=i==null||(p=i.connection)==null?void 0:p.mode)==null?`streaming`:f,this.telemetryClient=e,this.transport=(m=a==null?void 0:a.transport)==null?this.buildTransport(t,n,S,x,i,a):m,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=h(h({},this.configSet.configs),e.configs);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`,i==null||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.connectionError)}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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=L(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:h(h({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:re(),host:ie()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return X;default:return b}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}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:x(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=ee(t,n);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:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,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)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new a(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new a(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new a(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new a(`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(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}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()}};const Q=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var $=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=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(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return h(h({},e),{},{defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const oe=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},se=Math.ceil(128/Math.log2(62)),ce=new TextEncoder,le=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,ce.encode((t=e==null?void 0:e.toString())==null?``:t));return oe(new Uint8Array(n,0,16),se)},ue=(e,t,n)=>{var r,i,a,o,s;let c=(r=n==null?void 0:n.logger)==null?N():r,l=(i=F(n==null||(a=n.connection)==null?void 0:a.url))==null?I:i;return new ae(new $({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n==null||(o=n.metadata)==null?void 0:o.appName,appVersion:n==null||(s=n.metadata)==null?void 0:s.appVersion},logger:c,baseUrl:l,urlFactory:P,valueIdGenerator:le}),e,t,h(h({},n),{},{logger:c}))};var de=class r{constructor(n,i){this.awaitingRecovery=!1,this.metadata={name:r.name},this.runsOn=`client`,this.events=new e,this.client=ue(n,{sdkName:`js-openfeature-web-provider`,sdkVersion:`1.6.1`},i),this.client.on(`clientReady`,()=>{this.awaitingRecovery&&(this.awaitingRecovery=!1,this.events.emit(t.Ready))}),this.client.on(`configsUpdated`,({keys:e,removedKeys:n})=>{this.events.emit(t.ConfigurationChanged,{flagsChanged:[...e,...n]})})}async initialize(e){var t=this;t.awaitingRecovery=!1,await t.client.initialize(t.mapContext(e)),t.requireReady(`ConfigDirector did not become ready during initialization. Flags resolve to their default values until the connection succeeds.`)}async onContextChange(e,t){var n=this;n.awaitingRecovery=!1,await n.client.updateContext(n.mapContext(t)),n.requireReady(`ConfigDirector did not become ready after the context changed. Flags resolve against the previous context until the connection succeeds.`)}resolveBooleanEvaluation(e,t){return this.evaluate(e,t)}resolveStringEvaluation(e,t){return this.evaluate(e,t)}resolveNumberEvaluation(e,t){return this.evaluate(e,t)}resolveObjectEvaluation(e,t){return this.evaluate(e,t)}onClose(){return this.client.dispose(),Promise.resolve()}requireReady(e){if(!this.client.isReady)throw this.awaitingRecovery=!0,new n(e)}evaluate(e,t){return{value:this.client.getValue(e,t)}}mapContext(e){var t,n,r;if(!e)return{};let i=(t=(n=e.targetingKey)==null?e.id:n)==null?void 0:t.toString(),a=(r=e.name)==null?void 0:r.toString(),o=(e==null?void 0:e.traits)||{},s=typeof o==`object`&&Object.keys(o).length>0,c=e.anonymous;return{id:i,name:a,traits:s?o:void 0,anonymous:typeof c==`boolean`?c:void 0}}};export{de as ConfigDirectorProvider};
|
|
6
6
|
//# sourceMappingURL=configdirector-openfeature-web-provider.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-openfeature-web-provider.mjs","names":["this","this","this","this","this"],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/errors.ts","../../eventsource/src/errors.ts","../../eventsource/src/EventSourceParser.ts","../../eventsource/src/types.ts","../../eventsource/src/EventSourceClient.ts","../../eventsource/src/index.ts","../../js-client-core/src/StreamingTransport.ts","../../shared/src/value-parser.ts","../../shared/src/logger.ts","../../js-client-core/src/logger.ts","../../shared/src/url.ts","../../shared/src/constants.ts","../../shared/src/transport/pollingInterval.ts","../../shared/src/instance-id.ts","../../js-client-core/src/instance-id.ts","../../shared/src/transport/AbstractPollingTransport.ts","../../shared/src/fetchWithTimeout.ts","../../js-client-core/src/PollingTransport.ts","../../js-client-core/src/browser-globals.ts","../../js-client-core/src/DefaultConfigDirectorClient.ts","../../shared/src/telemetry/utils.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/ConfigDirectorProvider.ts"],"sourcesContent":["type EventType = string | symbol;\ntype EventsRecord = Record<EventType, any>;\n\ntype Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (\n payload: TEventsRecord[TKey],\n) => void;\n\nexport interface EventProvider<TEventsRecord extends EventsRecord> {\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;\n clear(): void;\n}\n\nexport class Emitter<TEventsRecord extends EventsRecord> implements EventProvider<TEventsRecord> {\n private handlerMap: Map<keyof TEventsRecord, Array<(payload: any) => void>> = new Map();\n\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (handlers) {\n handlers.push(handler);\n } else {\n this.handlerMap.set(name, [handler]);\n }\n }\n\n once<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n function onceHandler(payload: TEventsRecord[keyof TEventsRecord]) {\n self.off(name, onceHandler);\n handler.apply(self, payload);\n }\n this.on(name, onceHandler);\n }\n\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n if (handler) {\n const listenerIndex = handlers.indexOf(handler);\n if (listenerIndex >= 0) {\n handlers.splice(listenerIndex, 1);\n }\n } else {\n this.handlerMap.set(name, []);\n }\n }\n\n clear() {\n this.handlerMap.clear();\n }\n\n emit<TName extends keyof TEventsRecord>(name: TName, payload: TEventsRecord[TName]) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n handlers.slice().map((h) => h(payload));\n }\n}\n","export class ConfigDirectorConnectionError extends Error {\n public override readonly name: string = \"ConfigDirectorConnectionError\";\n public readonly status?: number;\n\n constructor(message: string, status?: number) {\n super(message);\n this.status = status;\n\n Object.setPrototypeOf(this, ConfigDirectorConnectionError.prototype);\n }\n}\n\nexport class ConfigDirectorValidationError extends Error {\n public override readonly name: string = \"ConfigDirectorValidationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorValidationError.prototype);\n }\n}\n\nexport class ConfigDirectorInitializationError extends Error {\n public override readonly name: string = \"ConfigDirectorInitializationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorInitializationError.prototype);\n }\n}\n","export class StreamClosedError extends Error {\n public override readonly name: string = \"StreamClosedError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, StreamClosedError.prototype);\n }\n}\n\nexport class MissingResponseBodyError extends Error {\n public override readonly name: string = \"MissingResponseBodyError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, MissingResponseBodyError.prototype);\n }\n}\n\nexport class InvalidOptionError extends Error {\n public override readonly name: string = \"InvalidOptionError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, InvalidOptionError.prototype);\n }\n}\n\nexport class ValueOutOfRangeError extends Error {\n public override readonly name: string = \"ValueOutOfRangeError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ValueOutOfRangeError.prototype);\n }\n}\n","import {\n type EventSourceParserOptions,\n type EventSourceMessageHandler,\n type EventSourceCommentHandler,\n type EventParserRetryCallback,\n} from \"./types\";\n\ntype ParsedField = {\n field: string;\n value: string;\n};\n\nexport class EventSourceParser {\n private isFirstChunk = true;\n private bufferedInput = \"\";\n private currentEvent: { type?: string; data: string } = { data: \"\" };\n private lastEventId: string | undefined;\n private onEvent: EventSourceMessageHandler;\n private onRetry: EventParserRetryCallback | undefined;\n private onComment: EventSourceCommentHandler | undefined;\n\n constructor(options: EventSourceParserOptions) {\n this.currentEvent = { data: \"\" };\n this.onEvent = options.onEvent ?? (() => {});\n this.onRetry = options.onRetry;\n this.onComment = options.onComment;\n }\n\n public parse(chunk: string): void {\n let input = chunk;\n\n if (this.isFirstChunk) {\n this.isFirstChunk = false;\n if (input.startsWith(\"\\uFEFF\")) {\n input = input.slice(1);\n } else if (input.startsWith(\"\\xEF\\xBB\\xBF\")) {\n input = input.slice(3);\n }\n }\n\n const lines = this.scanLines(this.bufferedInput + input);\n for (const line of lines) {\n this.dispatchLine(line);\n }\n }\n\n // Per the SSE spec, any data still buffered when the stream ends is discarded —\n // an event requires a terminating empty line to be dispatched.\n public finish(): void {\n this.bufferedInput = \"\";\n }\n\n /**\n * Scans `text` character by character to extract complete lines, recognizing\n * CR, LF, and CRLF as line terminators per the SSE spec. Any unterminated\n * trailing text is buffered and prepended to the next chunk.\n */\n private scanLines(text: string): string[] {\n const lines: string[] = [];\n let lineStart = 0;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"\\r\" || ch === \"\\n\") {\n lines.push(text.slice(lineStart, i));\n // Consume CRLF as a single terminator rather than two separate lines.\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") {\n i++;\n }\n i++;\n lineStart = i;\n } else {\n i++;\n }\n }\n\n this.bufferedInput = text.slice(lineStart);\n return lines;\n }\n\n private dispatchLine(line: string): void {\n if (line.startsWith(\":\")) {\n this.onComment?.(this.extractValue(line, 1));\n return;\n }\n\n if (line === \"\") {\n this.emitEvent();\n return;\n }\n\n this.applyField(this.parseField(line));\n }\n\n private emitEvent(): void {\n const data = this.currentEvent.data.endsWith(\"\\n\")\n ? this.currentEvent.data.slice(0, -1)\n : this.currentEvent.data;\n\n if (data !== \"\") {\n this.onEvent({ ...this.currentEvent, id: this.lastEventId, data });\n }\n\n this.currentEvent = { data: \"\" };\n }\n\n private applyField(parsed: ParsedField): void {\n switch (parsed.field) {\n case \"event\":\n this.currentEvent.type = parsed.value;\n break;\n case \"data\":\n this.currentEvent.data += parsed.value + \"\\n\";\n break;\n case \"id\":\n // Spec: ignore id values that contain a null character.\n if (!parsed.value.includes(\"\\0\")) {\n this.lastEventId = parsed.value;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(parsed.value)) {\n this.onRetry?.(Number.parseInt(parsed.value, 10));\n }\n break;\n default:\n break;\n }\n }\n\n private parseField(line: string): ParsedField {\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n return { field: line, value: \"\" };\n }\n return { field: line.slice(0, colon), value: this.extractValue(line, colon + 1) };\n }\n\n /** Returns the value portion of a line, stripping a single leading space per spec. */\n private extractValue(line: string, from: number): string {\n return line[from] === \" \" ? line.slice(from + 1) : line.slice(from);\n }\n}\n","export type ReconnectionState = {\n attempt: number;\n serverReconnectionTime: number;\n status?: number | undefined;\n error?: Error | undefined;\n};\n\nexport enum ReadyState {\n OPEN = \"open\",\n CLOSED = \"closed\",\n CONNECTING = \"connecting\",\n}\n\nexport type EventSourceClientOptions = {\n url: { toString(): string } | string;\n method?: string;\n headers?: Record<string, string>;\n body?: string | (() => string);\n mode?: \"cors\" | \"no-cors\" | \"same-origin\";\n credentials?: \"include\" | \"omit\" | \"same-origin\";\n redirect?: \"error\" | \"follow\";\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n lastEventId?: string;\n fetch?: (url: string, init: RequestInit) => Promise<Response>;\n onError?: (error: Error) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onMessage?: EventSourceMessageHandler;\n onComment?: EventSourceCommentHandler;\n shouldReconnect?: (state: ReconnectionState) => boolean;\n calculateReconnectDelay?: (state: ReconnectionState) => number;\n};\n\nexport type EventSourceMessage = {\n id?: string | undefined;\n type?: string;\n data: string;\n};\n\nexport type EventSourceMessageHandler = (message: EventSourceMessage) => void;\nexport type EventSourceCommentHandler = (comment: string) => void;\n\nexport type EventParserRetryCallback = (retry: number) => void;\n\nexport type EventSourceParserOptions = {\n onEvent?: EventSourceMessageHandler;\n onRetry?: EventParserRetryCallback;\n onComment?: EventSourceCommentHandler;\n};\n","import {\n InvalidOptionError,\n MissingResponseBodyError,\n StreamClosedError,\n ValueOutOfRangeError,\n} from \"./errors\";\nimport { EventSourceParser } from \"./EventSourceParser\";\nimport {\n type EventSourceClientOptions,\n type EventSourceCommentHandler,\n type EventSourceMessageHandler,\n type ReconnectionState,\n ReadyState,\n} from \"./types\";\n\nexport class EventSourceClient {\n private readonly DEFAULT_SHOULD_RECONNECT = () => true;\n private readonly DEFAULT_CALCULATE_RECONNECT_DELAY = () => this.serverReconnectionTime;\n private readonly url: string;\n private readonly headers?: Record<string, string>;\n private readonly body: () => string | undefined;\n private readonly requestOptions;\n private lastEventId?: string;\n private reconnectAttempt: number = 0;\n private abortController: AbortController = new AbortController();\n private reconnectTimeout: ReturnType<typeof setTimeout> | undefined;\n private _readyState: ReadyState = ReadyState.CLOSED;\n private serverReconnectionTime: number = 2_000;\n private _fetch: (url: string, init: RequestInit) => Promise<Response>;\n private _onError: (error: Error) => void;\n private _onMessage: EventSourceMessageHandler;\n private _onComment: EventSourceCommentHandler;\n private _onConnect: () => void;\n private _onDisconnect: () => void;\n private _shouldReconnect: (state: ReconnectionState) => boolean;\n private _calculateReconnectDelay: (state: ReconnectionState) => number;\n\n constructor(options: EventSourceClientOptions) {\n this.url = options.url.toString();\n this.lastEventId = options.lastEventId;\n this.headers = {\n Accept: \"text/event-stream\",\n ...options.headers,\n };\n const body = options.body;\n this.body = typeof body === \"function\" ? body : () => body;\n this.requestOptions = {\n method: options.method ?? \"GET\",\n mode: options.mode,\n credentials: options.credentials,\n redirect: options.redirect,\n referrer: options.referrer,\n referrerPolicy: options.referrerPolicy,\n };\n this._fetch = options.fetch ?? ((url, init) => fetch(url, init));\n this._onError = this.resolveCallback(options.onError, () => {}, \"onError\");\n this._onConnect = this.resolveCallback(options.onConnect, () => {}, \"onConnect\");\n this._onDisconnect = this.resolveCallback(options.onDisconnect, () => {}, \"onDisconnect\");\n this._onMessage = this.resolveCallback(options.onMessage, () => {}, \"onMessage\");\n this._onComment = this.resolveCallback(options.onComment, () => {}, \"onComment\");\n this._shouldReconnect = this.resolveCallback(\n options.shouldReconnect,\n this.DEFAULT_SHOULD_RECONNECT,\n \"shouldReconnect\",\n );\n this._calculateReconnectDelay = this.resolveCallback(\n options.calculateReconnectDelay,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"calculateReconnectDelay\",\n );\n }\n\n public set onError(value: (error: Error) => void) {\n this._onError = this.resolveCallback(value, () => {}, \"onError\");\n }\n\n public set onMessage(value: EventSourceMessageHandler) {\n this._onMessage = this.resolveCallback(value, () => {}, \"onMessage\");\n }\n\n public set onComment(value: EventSourceCommentHandler) {\n this._onComment = this.resolveCallback(value, () => {}, \"onComment\");\n }\n\n public set onConnect(value: () => void) {\n this._onConnect = this.resolveCallback(value, () => {}, \"onConnect\");\n }\n\n public set onDisconnect(value: () => void) {\n this._onDisconnect = this.resolveCallback(value, () => {}, \"onDisconnect\");\n }\n\n public set shouldReconnect(value: (state: ReconnectionState) => boolean) {\n this._shouldReconnect = this.resolveCallback(value, this.DEFAULT_SHOULD_RECONNECT, \"shouldReconnect\");\n }\n\n public set calculateReconnectDelay(value: (state: ReconnectionState) => number) {\n this._calculateReconnectDelay = this.resolveCallback(\n value,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"shouldReconnect\",\n );\n }\n\n public get readyState(): ReadyState {\n return this._readyState;\n }\n\n public connect() {\n if (this._readyState !== ReadyState.CLOSED) {\n return;\n }\n\n this.reconnectAttempt = 0;\n this.initiateConnection();\n }\n\n public close() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this.abortController.abort();\n }\n\n private initiateConnection() {\n this.abortController = new AbortController();\n this._readyState = ReadyState.CONNECTING;\n\n this._fetch(this.url, {\n ...this.requestOptions,\n body: this.body(),\n headers: this.buildRequestHeaders(),\n signal: this.abortController.signal,\n cache: \"no-store\",\n })\n .then((response) => this.handleFetchResponse(response))\n .catch((error: Error) => {\n if (error.name === \"AbortError\" || this.abortController.signal.aborted) {\n this.close();\n return;\n }\n\n this._onError(error);\n this.scheduleReconnect({ error });\n });\n }\n\n private async handleFetchResponse(response: Response) {\n const { body, status } = response;\n\n if (status === 204) {\n this.disconnected();\n return;\n }\n\n if (status >= 400) {\n this.scheduleReconnect({ status });\n return;\n }\n\n if (!body) {\n throw new MissingResponseBodyError(\"The server response did not have a body\");\n }\n\n this._readyState = ReadyState.OPEN;\n this._onConnect();\n this.reconnectAttempt = 0;\n\n const parser = new EventSourceParser({\n onEvent: (event) => {\n if (typeof event.id === \"string\") {\n this.lastEventId = event.id;\n }\n this._onMessage(event);\n },\n onComment: (comment) => this._onComment(comment),\n onRetry: (retryDelay) => (this.serverReconnectionTime = retryDelay),\n });\n\n await this.readResponseStream(body, parser);\n\n this.scheduleReconnect({\n status,\n error: new StreamClosedError(\"The server response stream was closed\"),\n });\n }\n\n private async readResponseStream(body: ReadableStream<Uint8Array>, parser: EventSourceParser) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let done = false;\n while (!done) {\n const result = await reader.read();\n if (result.value) {\n parser.parse(decoder.decode(result.value, { stream: true }));\n }\n done = result.done;\n }\n\n parser.finish();\n }\n\n private disconnected() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this._onDisconnect();\n }\n\n private buildRequestHeaders(): Record<string, string> {\n const lastEventIdHeader = this.lastEventId ? { \"Last-Event-ID\": this.lastEventId } : undefined;\n return {\n ...this.headers,\n ...lastEventIdHeader,\n };\n }\n\n private scheduleReconnect(state: { status?: number; error?: Error }) {\n if (this.abortController.signal.aborted) {\n return;\n }\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectAttempt += 1;\n\n const reconnectionState: ReconnectionState = {\n attempt: this.reconnectAttempt,\n status: state.status,\n error: state.error,\n serverReconnectionTime: this.serverReconnectionTime,\n };\n\n if (!this._shouldReconnect(reconnectionState)) {\n this.disconnected();\n return;\n }\n\n this._readyState = ReadyState.CONNECTING;\n let delay = this._calculateReconnectDelay(reconnectionState);\n\n if (!Number.isFinite(delay) || delay < 1 || delay > 1_000 * 60 * 60) {\n this._onError(\n new ValueOutOfRangeError(\n `The calculated reconnect delay is out of range: ${delay}. Defaulting to ${this.serverReconnectionTime}`,\n ),\n );\n delay = this.serverReconnectionTime;\n }\n\n this.reconnectTimeout = setTimeout(() => this.initiateConnection(), delay);\n }\n\n private resolveCallback<T extends (...args: any[]) => any>(\n provided: unknown,\n fallback: T,\n optionName: string,\n ): T {\n if (provided == null) return fallback;\n if (typeof provided !== \"function\") {\n throw new InvalidOptionError(`${optionName} must be a function`);\n }\n return provided as T;\n }\n}\n","import { EventSourceClient } from \"./EventSourceClient\";\nimport { type EventSourceClientOptions } from \"./types\";\n\nexport const createEventSourceClient = (options: EventSourceClientOptions) => {\n return new EventSourceClient(options);\n};\n","import type {\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { ConfigDirectorConnectionError } from \"./errors\";\nimport { createEventSourceClient } from \"@eventsource/index\";\nimport type { EventSourceClient } from \"@eventsource/EventSourceClient\";\nimport type { UrlLike } from \"@shared/url\";\n\nexport class StreamingTransport implements Transport {\n private logger: ConfigDirectorLogger;\n private eventSource: EventSourceClient | undefined;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(private readonly options: TransportOptions) {\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/sse/v1\", options.baseUrl);\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n if (this.eventSource) {\n this.close();\n }\n\n const eventSourcePromise = new Promise<this>((resolve, reject) => {\n this.eventSource = createEventSourceClient({\n url: this.url,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n fetch: this.options.fetch,\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: this.options.instanceId,\n }),\n\n onMessage: ({ data }) => {\n this.dispatchMessage(data);\n },\n onConnect: () => {\n this.logger.debug(\"[StreamingTransport] Connected\");\n resolve(this);\n },\n shouldReconnect: (state) => {\n const reconnect = !this.isStatusFatal(state.status);\n if (!reconnect) {\n const error = this.prepareFatalError(state.status, state.error);\n this.eventEmitter.emit(\"connectionError\", error);\n reject(error);\n }\n return reconnect;\n },\n calculateReconnectDelay: (state) => {\n const delay = this.options.connectionRetryDelay(state.attempt);\n const logMessage = `[StreamingTransport] Scheduling reconnect attempt #${state.attempt} in ${delay}ms.`;\n if (state.attempt <= 5) {\n this.logger.info(logMessage);\n } else {\n this.logger.warn(logMessage);\n }\n return delay;\n },\n onError: (error) => {\n this.logger.debug(\"[StreamingTransport] Error: \", error);\n },\n onDisconnect: () => {\n this.logger.debug(\"[StreamingTransport] Disconnected\");\n },\n });\n this.eventSource.connect();\n });\n\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n return Promise.race([\n eventSourcePromise,\n new Promise<this>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(this), timeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n private dispatchMessage(data: string) {\n try {\n const json = JSON.parse(data);\n this.eventEmitter.emit(\"configSetReceived\", json);\n } catch (error) {\n this.logger.error(\"[StreamingTransport] Error parsing and dispatching config data update: \", error);\n }\n }\n\n private prepareFatalError(\n responseStatus: number | undefined,\n error: Error | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}.`;\n const errorLine = error ? ` Error: ${error}` : \"\";\n const message = `${headline}${errorLine}. This is an unrecoverable error, will not attempt to reconnect.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n private isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n\n public close() {\n this.eventSource?.close();\n clearTimeout(this.timeoutTimer);\n }\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import type { ConfigState, ConfigType, ConfigValueType, EvaluationReason } from \"./types\";\n\ntype NativeType = \"string\" | \"number\" | \"bigint\" | \"boolean\" | \"symbol\" | \"undefined\" | \"object\" | \"function\";\n\ntype ParseResult<T extends ConfigValueType> = {\n parsedValue: T;\n parsedValueId: string | null | undefined;\n requestedType: NativeType | string;\n usedDefault: boolean;\n reason: EvaluationReason;\n};\n\nexport const getRequestedType = <T extends ConfigValueType>(defaultValue: T): string => {\n const baseType = typeof defaultValue;\n if (baseType === \"object\") {\n try {\n return (defaultValue as object).constructor?.name ?? baseType;\n } catch {\n return baseType;\n }\n } else if (baseType === \"function\") {\n try {\n const functionName = (defaultValue as any).name;\n return functionName ? `function: ${functionName}` : baseType;\n } catch {\n return baseType;\n }\n }\n return baseType;\n};\n\nconst isNumericNativeType = (requestedType: NativeType): boolean => {\n return requestedType === \"number\" || requestedType === \"bigint\";\n};\n\nconst configTypesNotReadableAsString: ReadonlySet<ConfigType> = new Set<ConfigType>([\"boolean\", \"integer\", \"float\"]);\n\nexport const parseConfigValue = <T extends ConfigValueType>(\n configState: ConfigState,\n defaultValue: T,\n): ParseResult<T> => {\n const value = configState.value;\n const requestedType = getRequestedType(defaultValue);\n\n if (value == null || value === \"\") {\n return {\n parsedValue: defaultValue as T,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"value-missing\",\n };\n }\n\n if (configState.type === \"json\") {\n return parseJson(value, defaultValue, requestedType, configState.valueId);\n }\n\n if (typeof defaultValue === \"string\") {\n if (configTypesNotReadableAsString.has(configState.type)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: value as T,\n parsedValueId: configState.valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n if (\n typeof defaultValue === \"boolean\" &&\n (configState.type === \"boolean\" || configState.type === \"string\" || configState.type === \"enum\")\n ) {\n const boolValue = parseConfigBoolean(value);\n const hasBoolean = typeof boolValue === \"boolean\";\n return {\n parsedValue: (hasBoolean ? boolValue : defaultValue) as T,\n parsedValueId: hasBoolean ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasBoolean,\n reason: hasBoolean ? \"found-match\" : \"invalid-boolean\",\n };\n }\n\n if (isNumericNativeType(typeof defaultValue) && configState.type === \"integer\") {\n const numValue = parseConfigInteger(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n if (\n isNumericNativeType(typeof defaultValue) &&\n (configState.type === \"float\" || configState.type === \"enum\" || configState.type === \"string\")\n ) {\n const numValue = parseConfigFloat(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n};\n\nconst parseConfigBoolean = (value: string): boolean | undefined => {\n if (!value) {\n return;\n }\n const lowerValue = value.toLowerCase();\n if (lowerValue != \"true\" && lowerValue != \"false\") {\n return;\n }\n return lowerValue === \"true\";\n};\n\nconst parseConfigInteger = (value: string): number | undefined => {\n const num = parseStrictNumber(value);\n return num == null ? undefined : Math.trunc(num);\n};\n\nconst parseConfigFloat = (value: string): number | undefined => {\n return parseStrictNumber(value);\n};\n\nconst parseStrictNumber = (value: string): number | undefined => {\n if (!value || !isDecimalCharacters(value)) {\n return;\n }\n const num = Number(value);\n if (isNaN(num) || !isFinite(num)) {\n return;\n }\n return num;\n};\n\nconst isDecimalCharacters = (value: string): boolean => {\n for (const character of value) {\n const isDigit = character >= \"0\" && character <= \"9\";\n if (!isDigit && !\"+-.eE\".includes(character)) {\n return false;\n }\n }\n return true;\n};\n\nconst parseJson = <T extends ConfigValueType>(\n jsonString: string,\n defaultValue: T,\n requestedType: string,\n valueId: string | null | undefined,\n): ParseResult<T> => {\n if (typeof defaultValue === \"string\") {\n return {\n parsedValue: jsonString as T,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n try {\n const parsed = JSON.parse(jsonString);\n if (!isJsonTypeCompatible(parsed, defaultValue)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: parsed,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n } catch {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"invalid-json\",\n };\n }\n};\n\nconst isJsonTypeCompatible = (parsed: unknown, defaultValue: ConfigValueType): boolean => {\n if (parsed === null) {\n return false;\n }\n const defaultType = typeof defaultValue;\n if (defaultType === \"bigint\") {\n return typeof parsed === \"number\";\n }\n return typeof parsed === defaultType;\n};\n","import type { ConfigDirectorLogger, ConfigDirectorLogMessageDecorator, ConfigDirectorLoggingLevel } from \"./types\";\n\nconst LEVELS: Record<ConfigDirectorLoggingLevel, number> = {\n off: -1,\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nconst buildDateFormatter = () => {\n const baseOptions: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n };\n\n try {\n return new Intl.DateTimeFormat(\n undefined,\n { ...baseOptions, fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions,\n );\n } catch {\n return new Intl.DateTimeFormat(undefined, baseOptions);\n }\n};\n\nexport class DefaultConsoleLogger implements ConfigDirectorLogger {\n private readonly dateFormatter;\n\n constructor(private readonly level: ConfigDirectorLoggingLevel, private readonly decorator: ConfigDirectorLogMessageDecorator) {\n this.level = level;\n this.decorator = decorator;\n this.dateFormatter = buildDateFormatter();\n }\n\n debug(message: string, ...args: any): void {\n this.log(console.debug, \"debug\", message, ...args);\n }\n\n info(message: string, ...args: any): void {\n this.log(console.info, \"info\", message, ...args);\n }\n\n warn(message: string, ...args: any): void {\n this.log(console.warn, \"warn\", message, ...args);\n }\n\n error(message: string, ...args: any): void {\n this.log(console.error, \"error\", message, ...args);\n }\n\n protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any) {\n if (LEVELS[this.level] >= LEVELS[level]) {\n loggerFunction(`[${this.dateFormatter.format(new Date())}] ${this.decorator?.decorateMessage(message)}`, ...args);\n }\n }\n}\n","import { type ConfigDirectorLogMessageDecorator, type ConfigDirectorLoggingLevel } from \"./types\";\nimport { DefaultConsoleLogger } from \"../../shared/src/logger\";\nexport { DefaultConsoleLogger } from \"../../shared/src/logger\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:js-client-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n","import { ConfigDirectorValidationError } from \"./errors\";\n\nexport interface UrlLike {\n toString(): string;\n}\n\nexport type UrlFactory = (input: string, base?: UrlLike) => UrlLike;\n\nexport const defaultUrlFactory: UrlFactory = (input, base) => new URL(input, base?.toString());\n\nexport const parseUrl = (url: string | undefined): URL | undefined => {\n if (!url) {\n return;\n }\n\n try {\n return new URL(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid URL '${url}'. Parsing failed: ${error}`);\n }\n};\n","export const CLIENT_BASE_URL = \"https://client-sdk-api.configdirector.com\";\nexport const CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS = 60;\nexport const CLIENT_MIN_POLLING_INTERVAL_SECONDS = 30;\nexport const SERVER_DEFAULT_POLLING_INTERVAL_SECONDS = 300;\nexport const SERVER_MIN_POLLING_INTERVAL_SECONDS = 60;\n","export type PollingIntervalDefaults = {\n defaultSeconds: number;\n minimumSeconds: number;\n};\n\nexport type ResolvedPollingInterval = {\n seconds: number;\n warning: string | undefined;\n};\n\nexport const resolvePollingInterval = (\n configuredSeconds: number | undefined,\n defaults: PollingIntervalDefaults,\n): ResolvedPollingInterval => {\n if (configuredSeconds === undefined) {\n return { seconds: defaults.defaultSeconds, warning: undefined };\n }\n if (configuredSeconds >= defaults.minimumSeconds) {\n return { seconds: configuredSeconds, warning: undefined };\n }\n return {\n seconds: defaults.minimumSeconds,\n warning: `pollingInterval of ${configuredSeconds} seconds is below the minimum of ${defaults.minimumSeconds} seconds. Using ${defaults.minimumSeconds} seconds.`,\n };\n};\n","// React Native's Hermes engine does not expose a global `crypto`, unlike browsers and Node 19+.\nexport const generateInstanceId = (): string => {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (placeholder) => {\n const random = (Math.random() * 16) | 0;\n const value = placeholder === \"x\" ? random : (random & 0x3) | 0x8;\n return value.toString(16);\n });\n};\n","import { generateInstanceId } from \"@shared/instance-id\";\nimport type { ConfigDirectorLogger } from \"./types\";\n\nconst STORAGE_KEY = \"configdirector-sdk:instance-id\";\nconst RECORD_VERSION = 1;\nconst MAX_AGE_MS = 6 * 60 * 60 * 1_000;\nconst CHECKSUM_SALT = \"configdirector.instanceId.v1\";\nconst UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\ntype StoredInstanceId = {\n v: number;\n id: string;\n createdAt: number;\n checksum: string;\n};\n\nconst fnv1a = (input: string, offsetBasis: number): number => {\n let hash = offsetBasis;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n\nconst checksumFor = (id: string, createdAt: number): string => {\n const payload = `${CHECKSUM_SALT}|${id}|${createdAt}`;\n const low = fnv1a(payload, 0x811c9dc5);\n const high = fnv1a(`${low}|${payload}`, 0x01000193);\n return high.toString(16).padStart(8, \"0\") + low.toString(16).padStart(8, \"0\");\n};\n\nconst getLocalStorage = (): Storage | undefined => {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage ?? undefined;\n } catch {\n return undefined;\n }\n};\n\nconst isUsableRecord = (record: unknown): record is StoredInstanceId => {\n if (!record || typeof record !== \"object\") {\n return false;\n }\n\n const { v, id, createdAt, checksum } = record as Partial<StoredInstanceId>;\n if (v !== RECORD_VERSION || typeof id !== \"string\" || typeof checksum !== \"string\") {\n return false;\n }\n\n if (typeof createdAt !== \"number\" || !Number.isInteger(createdAt) || createdAt <= 0) {\n return false;\n }\n\n if (!UUID_V4_PATTERN.test(id)) {\n return false;\n }\n\n return checksum === checksumFor(id, createdAt);\n};\n\nconst readStoredInstanceId = (storage: Storage, logger?: ConfigDirectorLogger): string | undefined => {\n let raw: string | null;\n try {\n raw = storage.getItem(STORAGE_KEY);\n } catch (error) {\n logger?.debug(\"[ConfigDirectorClient] Could not read the stored instance id, generating a new one\", error);\n return undefined;\n }\n\n if (!raw) {\n return undefined;\n }\n\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one\");\n return undefined;\n }\n\n if (!isUsableRecord(record)) {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id failed validation, generating a new one\");\n return undefined;\n }\n\n const age = Date.now() - record.createdAt;\n if (age < 0 || age >= MAX_AGE_MS) {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id has expired, generating a new one\");\n return undefined;\n }\n\n return record.id;\n};\n\nconst storeInstanceId = (storage: Storage, id: string, logger?: ConfigDirectorLogger) => {\n const createdAt = Date.now();\n const record: StoredInstanceId = { v: RECORD_VERSION, id, createdAt, checksum: checksumFor(id, createdAt) };\n try {\n storage.setItem(STORAGE_KEY, JSON.stringify(record));\n } catch (error) {\n logger?.debug(\"[ConfigDirectorClient] Could not persist the instance id\", error);\n }\n};\n\nexport const resolveInstanceId = (logger?: ConfigDirectorLogger): string => {\n const storage = getLocalStorage();\n if (!storage) {\n return generateInstanceId();\n }\n\n const storedInstanceId = readStoredInstanceId(storage, logger);\n if (storedInstanceId) {\n return storedInstanceId;\n }\n\n const instanceId = generateInstanceId();\n storeInstanceId(storage, instanceId, logger);\n return instanceId;\n};\n","import { ConfigDirectorConnectionError } from \"../errors\";\n\nexport abstract class AbstractPollingTransport {\n protected fatalError = false;\n protected pollingInterval: ReturnType<typeof setInterval> | undefined;\n protected abstract pollingIntervalSeconds: number;\n\n protected clearPollingInterval() {\n clearInterval(this.pollingInterval);\n }\n\n protected schedulePollingInterval(callback: () => void) {\n clearInterval(this.pollingInterval);\n if (this.pollingIntervalSeconds <= 0) {\n return;\n }\n this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1_000);\n }\n\n protected async handleNonOkResponse(response: Response) {\n if (!response.ok) {\n if (this.isStatusFatal(response.status)) {\n this.fatalError = true;\n this.close();\n throw this.prepareFatalResponseStatusError(response.status, await response.text());\n } else {\n throw new ConfigDirectorConnectionError(\n `Connection failed with status: ${response.status}`,\n response.status,\n );\n }\n }\n }\n\n protected handleFetchError(fetchError: unknown) {\n if (this.isFetchErrorFatal(fetchError)) {\n this.fatalError = true;\n this.close();\n throw new ConfigDirectorConnectionError(\n `Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`,\n );\n } else if (fetchError instanceof SyntaxError) {\n throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);\n } else {\n throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);\n }\n }\n\n protected prepareFatalResponseStatusError(\n responseStatus: number,\n errorBody: string | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}`;\n const serverBody = (errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : \"\";\n const message = `${headline}${serverBody}. This is an unrecoverable error, retry attempts will be ignored.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n protected isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n protected isFetchErrorFatal(fetchError: unknown): boolean {\n return (fetchError as any)?.name === \"NotAllowedError\";\n }\n\n public get isConnected(): boolean {\n return this.pollingInterval !== undefined;\n }\n\n public close() {\n clearInterval(this.pollingInterval);\n this.pollingInterval = undefined;\n }\n\n public abstract clear(): void;\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import { type ConfigDirectorLogger } from \"./types\";\nimport type { UrlLike } from \"./url\";\n\nexport const fetchWithTimeout = async (\n timeout: number,\n resource: string | UrlLike | Request,\n options: RequestInit | undefined,\n logger: ConfigDirectorLogger,\n) => {\n const abortController = new AbortController();\n const abortTimeoutId = setTimeout(() => {\n logger.debug(\"[fetchWithTimeout] Reached timeout, aborting request\");\n abortController.abort();\n }, timeout);\n\n try {\n const response = await fetch(typeof resource === \"string\" || resource instanceof Request ? resource : resource.toString(), {\n ...options,\n signal: abortController.signal,\n });\n clearTimeout(abortTimeoutId);\n return response;\n } catch (error) {\n logger.warn(\"[fetchWithTimeout] Fetch error: \", error);\n clearTimeout(abortTimeoutId);\n throw error;\n }\n};\n","import type {\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { AbstractPollingTransport } from \"@shared/transport/AbstractPollingTransport\";\nimport { fetchWithTimeout } from \"@shared/fetchWithTimeout\";\nimport type { UrlLike } from \"@shared/url\";\nimport { CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS } from \"@shared/constants\";\n\nexport class PollingTransport extends AbstractPollingTransport implements Transport {\n protected pollingIntervalSeconds: number;\n private logger: ConfigDirectorLogger;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private lastUpdateTimestamp: string | undefined;\n\n constructor(private readonly options: TransportOptions) {\n super();\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/polling/v1\", options.baseUrl);\n this.pollingIntervalSeconds = options.pollingInterval ?? CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS;\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n this.clearPollingInterval();\n\n try {\n await this.fetchConfigs(context, timeout);\n } finally {\n // A transient failure on the first fetch must not leave the client without a\n // connection, so polling is scheduled either way. An unrecoverable failure has\n // already closed the transport and must not be retried.\n if (!this.fatalError) {\n this.schedulePollingInterval(() => {\n void this.fetchConfigs(context, timeout).catch((error) => {\n this.logger.error(\"[PollingTransport] Error during polling:\", error);\n });\n });\n }\n }\n\n return this;\n }\n\n private async fetchConfigs(context: ConfigDirectorContext, timeout: number) {\n if (this.fatalError) {\n this.logger.warn(\n \"[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.\",\n );\n return;\n }\n\n try {\n const response = await fetchWithTimeout(\n timeout,\n this.url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: this.options.instanceId,\n lastUpdateTimestamp: this.lastUpdateTimestamp,\n }),\n },\n this.logger,\n );\n\n await this.handleNonOkResponse(response);\n\n if (response.status == 200) {\n const json = JSON.parse(await response.text());\n this.lastUpdateTimestamp = json.timestamp;\n this.eventEmitter.emit(\"configSetReceived\", json);\n }\n } catch (fetchError) {\n try {\n this.handleFetchError(fetchError);\n } catch (handledError) {\n if (this.fatalError) {\n this.eventEmitter.emit(\"connectionError\", handledError as Error);\n }\n throw handledError;\n }\n }\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n}\n","type BrowserGlobals = {\n navigator?: { userAgent?: string };\n location?: { host?: string };\n};\n\nconst read = (readValue: (globals: BrowserGlobals) => string | undefined): string | undefined => {\n try {\n return readValue(globalThis as BrowserGlobals);\n } catch {\n return undefined;\n }\n};\n\nexport const readUserAgent = (): string | undefined => read((globals) => globals.navigator?.userAgent);\n\nexport const readHost = (): string | undefined => read((globals) => globals.location?.host);\n","import { Emitter } from \"./Emitter\";\nimport { StreamingTransport } from \"./StreamingTransport\";\nimport { getRequestedType, parseConfigValue } from \"../../shared/src/value-parser\";\nimport type {\n ConfigSet,\n ConfigState,\n ConfigDirectorContext,\n ConfigDirectorClientOptions,\n ConfigDirectorClient,\n ClientEvents,\n WatchHandler,\n ConfigValueType,\n ConfigDirectorLogger,\n Transport,\n ClientConnectAction,\n IdentifyingSdkOptions,\n InternalClientOptions,\n ConnectionMode,\n ConfigEvaluation,\n HookHandler,\n} from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorValidationError } from \"./errors\";\nimport type { TelemetryClient } from \"./telemetry\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport type { UrlFactory, UrlLike } from \"@shared/url\";\nimport {\n CLIENT_BASE_URL,\n CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS,\n CLIENT_MIN_POLLING_INTERVAL_SECONDS,\n} from \"@shared/constants\";\nimport { resolvePollingInterval } from \"@shared/transport/pollingInterval\";\nimport { resolveInstanceId } from \"./instance-id\";\nimport { PollingTransport } from \"./PollingTransport\";\nimport { readHost, readUserAgent } from \"./browser-globals\";\nconst MAX_EXPONENTIAL_DELAY = 9; // 2^9 = 512 seconds, to cap it to under 10min\n\ntype WatchHandlerWithOptions<T extends ConfigValueType> = {\n handler: WatchHandler<T>;\n defaultValue: T;\n requestedType: string;\n};\n\nexport class DefaultConfigDirectorClient implements ConfigDirectorClient {\n private logger: ConfigDirectorLogger;\n private telemetryClient: TelemetryClient;\n private configSet: ConfigSet | undefined;\n private handlersMap: Map<string, WatchHandlerWithOptions<any>[]> = new Map();\n private transport: Transport;\n private eventEmitter = new Emitter<ClientEvents>();\n private timeout: number;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private ready = false;\n private initializing = false;\n private hasReceivedConfigSet = false;\n private readyPromise: Promise<void> | undefined;\n private readyResolve: ((cancelled?: boolean) => void) | undefined;\n private currentContext?: ConfigDirectorContext;\n private connectionMode: ConnectionMode;\n private instanceId: string;\n\n constructor(\n telemetryClient: TelemetryClient,\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n internalClientOptions?: InternalClientOptions,\n ) {\n this.logger = clientOptions?.logger ?? createDefaultLogger();\n this.instanceId = resolveInstanceId(this.logger);\n this.timeout = clientOptions?.connection?.timeout ?? 3_000;\n this.validateSdkKeyPresence(clientSdkKey);\n const urlFactory: UrlFactory = internalClientOptions?.urlFactory ?? defaultUrlFactory;\n const baseUrl = this.parseUrl(clientOptions?.connection?.url, urlFactory) ?? CLIENT_BASE_URL;\n this.connectionMode = clientOptions?.connection?.mode ?? \"streaming\";\n this.telemetryClient = telemetryClient;\n this.transport =\n internalClientOptions?.transport ??\n this.buildTransport(clientSdkKey, sdkOptions, baseUrl, urlFactory, clientOptions, internalClientOptions);\n\n this.transport.on(\"configSetReceived\", (configSet: ConfigSet) => {\n this.hasReceivedConfigSet = true;\n this.readyResolve?.();\n const removedKeys = this.findKeysRemovedBy(configSet);\n if (!this.configSet || configSet.kind == \"full\") {\n this.configSet = configSet;\n } else {\n this.configSet.configs = {\n ...this.configSet.configs,\n ...configSet.configs,\n };\n }\n const keys = Object.keys(configSet.configs);\n this.emit(\"configsUpdated\", { keys, removedKeys });\n this.updateWatchers([...keys, ...removedKeys]);\n this.logger.debug(\"[ConfigDirectorClient] ConfigSet updated from server:\", { keys, removedKeys });\n });\n\n this.transport.on(\"connectionError\", (error: Error) => {\n this.initializing = false;\n this.logger.error(\n \"[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.\",\n error,\n );\n this.emit(\"connectionError\", { error });\n });\n\n this.registerHandler(\"clientReady\", clientOptions?.hooks?.clientReady);\n this.registerHandler(\"configEvaluated\", clientOptions?.hooks?.configEvaluated);\n this.registerHandler(\"configsUpdated\", clientOptions?.hooks?.configsUpdated);\n this.registerHandler(\"contextUpdated\", clientOptions?.hooks?.contextUpdated);\n this.registerHandler(\"connectionError\", clientOptions?.hooks?.connectionError);\n }\n\n private registerHandler<T extends keyof ClientEvents>(\n event: T,\n handler: HookHandler<T> | HookHandler<T>[] | undefined,\n ) {\n if (!handler) {\n return;\n }\n\n const handlers = Array.isArray(handler) ? handler : [handler];\n for (const h of handlers) {\n if (typeof h === \"function\") {\n this.on(event, h);\n }\n }\n }\n\n private resolvePollingIntervalForMode(configuredSeconds: number | undefined): number | undefined {\n if (this.connectionMode !== \"polling\") {\n return undefined;\n }\n const resolved = resolvePollingInterval(configuredSeconds, {\n defaultSeconds: CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS,\n minimumSeconds: CLIENT_MIN_POLLING_INTERVAL_SECONDS,\n });\n if (resolved.warning) {\n this.logger.warn(`[ConfigDirectorClient] ${resolved.warning}`);\n }\n return resolved.seconds;\n }\n\n private buildTransport(\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n baseUrl: UrlLike,\n urlFactory: UrlFactory,\n clientOptions: ConfigDirectorClientOptions | undefined,\n internalClientOptions: InternalClientOptions | undefined,\n ): Transport {\n const transportConstructor = this.getTransportConstructor(this.connectionMode);\n return new transportConstructor({\n instanceId: this.instanceId,\n clientSdkKey,\n baseUrl,\n resolveUrl: urlFactory,\n metaContext: {\n ...clientOptions?.metadata,\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n userAgent: readUserAgent(),\n host: readHost(),\n },\n logger: this.logger,\n fetch: internalClientOptions?.fetch,\n connectionRetryDelay:\n internalClientOptions?.connectionRetryDelay ??\n ((attempt: number) => {\n const seconds = Math.pow(2, Math.min(attempt, MAX_EXPONENTIAL_DELAY));\n return seconds * 1_000;\n }),\n pollingInterval: this.resolvePollingIntervalForMode(clientOptions?.connection?.pollingInterval),\n });\n }\n\n private getTransportConstructor(connectionMode?: ConnectionMode) {\n switch (connectionMode) {\n case \"polling\":\n return PollingTransport;\n default:\n return StreamingTransport;\n }\n }\n\n public async initialize(context?: ConfigDirectorContext) {\n if (!this.hasReceivedConfigSet) {\n this.initializing = true;\n }\n await this.connectToTransport(context, \"initialization\");\n }\n\n public async updateContext(context: ConfigDirectorContext) {\n await this.connectToTransport(context, \"context update\");\n }\n\n public get context(): ConfigDirectorContext | undefined {\n return this.currentContext;\n }\n\n private async connectToTransport(context: ConfigDirectorContext | undefined, caller: ClientConnectAction) {\n try {\n this.ready = false;\n this.readyPromise = new Promise<boolean | undefined>((resolve) => {\n this.readyResolve = resolve;\n }).then((cancelled) => {\n if (cancelled) {\n return;\n }\n this.ready = true;\n this.initializing = false;\n this.emit(\"clientReady\", { action: caller });\n this.logger.debug(\"[ConfigDirectorClient] Received initial payload from the server, client is ready\");\n });\n const startTime = new Date().getTime();\n await this.transport.connect(context ?? {}, this.timeout, caller);\n this.currentContext = context;\n this.telemetryClient.updateContext(context);\n this.emit(\"contextUpdated\", { context });\n\n const elapsedTime = new Date().getTime() - startTime;\n const remainingTimeout = this.timeout - elapsedTime;\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n if (remainingTimeout > 0) {\n await Promise.race([\n this.readyPromise,\n new Promise<void>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(), remainingTimeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n if (!this.ready) {\n const warningDetails =\n \"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.\";\n this.logger.warn(\n `[ConfigDirectorClient] Timed out waiting for ${caller} after ${this.timeout}ms. ${warningDetails}`,\n );\n }\n } catch (error) {\n this.logger.error(`[ConfigDirectorClient] An error occurred during ${caller}: `, error);\n }\n }\n\n private findKeysRemovedBy(configSet: ConfigSet): string[] {\n if (!this.configSet || configSet.kind != \"full\") {\n return [];\n }\n return Object.keys(this.configSet.configs).filter((key) => !Object.prototype.hasOwnProperty.call(configSet.configs, key));\n }\n\n private updateWatchers(configKeys: string[]) {\n configKeys.forEach((configKey) => this.updateWatchersForConfig(configKey));\n }\n\n private updateWatchersForConfig(configKey: string) {\n const configState = this.configSet?.configs[configKey];\n this.handlersMap.get(configKey)?.forEach((h) => {\n const value = this.getValueFromConfigState(configKey, configState, h.defaultValue);\n h.handler(value);\n });\n }\n\n public watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>) {\n this.validateDefaultValue(defaultValue);\n\n const handlers = this.handlersMap.get(configKey);\n const handlerWithOptions = { handler: callback, defaultValue, requestedType: typeof defaultValue };\n if (handlers) {\n handlers.push(handlerWithOptions);\n } else {\n this.handlersMap.set(configKey, [handlerWithOptions]);\n }\n\n return () => this.unwatch(configKey, callback);\n }\n\n public unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>) {\n const handlers = this.handlersMap.get(configKey);\n if (!handlers) {\n return;\n }\n\n if (callback) {\n const index = handlers.findIndex((h) => h.handler == callback);\n if (index >= 0) {\n handlers?.splice(index, 1);\n }\n } else {\n handlers.splice(0);\n }\n }\n\n public getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T {\n this.validateDefaultValue(defaultValue);\n\n const configState = this.configSet?.configs[configKey];\n return this.getValueFromConfigState(configKey, configState, defaultValue);\n }\n\n private getValueFromConfigState<T extends ConfigValueType>(\n configKey: string,\n configState: ConfigState | undefined,\n defaultValue: T,\n ): T {\n if (!configState) {\n this.logger.debug(\n `[ConfigDirectorClient] No config state found for '${configKey}', returning default value '${defaultValue}'`,\n );\n const reason = this.isReady ? \"config-state-missing\" : \"client-not-ready\";\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: getRequestedType(defaultValue),\n evaluatedValue: defaultValue,\n usedDefault: true,\n evaluationReason: reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: defaultValue,\n isDefaultValue: true,\n reason,\n context: this.context,\n });\n return defaultValue;\n }\n\n const parseResult = parseConfigValue<T>(configState, defaultValue);\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n type: configState.type,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: parseResult.requestedType,\n evaluatedValue: parseResult.parsedValue,\n evaluatedValueId: parseResult.parsedValueId,\n usedDefault: parseResult.usedDefault,\n evaluationReason: parseResult.reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: parseResult.parsedValue,\n valueId: parseResult.parsedValueId ?? undefined,\n isDefaultValue: parseResult.usedDefault,\n reason: parseResult.reason,\n context: this.context,\n });\n this.logger.debug(`[ConfigDirectorClient] Evaluated '${configKey}' to '${parseResult.parsedValue}'`);\n return parseResult.parsedValue;\n }\n\n private dispatchEvaluationEvent(event: ConfigEvaluation) {\n setTimeout(() => this.emit(\"configEvaluated\", { evaluation: event }), 0);\n }\n\n private emit<TName extends keyof ClientEvents>(name: TName, payload: ClientEvents[TName]) {\n try {\n this.eventEmitter.emit(name, payload);\n } catch (error) {\n this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${name}'`, error);\n }\n }\n\n private parseUrl(url: string | undefined, urlFactory: UrlFactory): UrlLike | undefined {\n if (!url) {\n return;\n }\n\n try {\n return urlFactory(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid base URL '${url}'. Parsing failed: ${error}`);\n }\n }\n\n private validateSdkKeyPresence(sdkKey: string | null | undefined) {\n if (!sdkKey || sdkKey.trim().length == 0) {\n throw new ConfigDirectorValidationError(\n \"No client SDK key was provided, the client cannot be instantiated without a valid client SDK key\",\n );\n }\n }\n\n private validateDefaultValue<T extends ConfigValueType>(defaultValue: T) {\n if (defaultValue === undefined || defaultValue === null) {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config must be defined and non-null.\",\n );\n }\n\n if (typeof defaultValue === \"function\") {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config cannot be a function.\",\n );\n }\n }\n\n public get isReady(): boolean {\n return this.ready;\n }\n\n public get isInitializing(): boolean {\n return this.initializing;\n }\n\n public on<T extends keyof ClientEvents>(eventName: T, handler: (event: ClientEvents[T]) => void): void {\n this.eventEmitter.on(eventName, handler);\n }\n\n public off<T extends keyof ClientEvents>(eventName: T, handler?: (payload: ClientEvents[T]) => void) {\n this.eventEmitter.off(eventName, handler);\n }\n\n public clear() {\n this.logger.debug(\"[ConfigDirectorClient] clear() has been called, removing all observers\");\n this.eventEmitter.clear();\n this.handlersMap.clear();\n }\n\n public unwatchAll() {\n this.handlersMap.clear();\n }\n\n public pauseNetwork(): void {\n this.logger.debug(\"[ConfigDirectorClient] pauseNetwork() called, pausing transport connection\");\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n this.transport.close();\n this.ready = false;\n }\n\n public async resumeNetwork(): Promise<void> {\n await this.connectToTransport(this.currentContext, \"network resume\");\n }\n\n public async close() {\n this.logger.debug(\"[ConfigDirectorClient] close() has been called, closing connection to server\");\n clearTimeout(this.timeoutTimer);\n this.readyResolve?.(true);\n this.telemetryClient.close();\n this.transport.close();\n this.ready = false;\n this.initializing = false;\n }\n\n public dispose() {\n this.clear();\n this.close();\n }\n}\n","import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private startWorker(): Worker {\n if (this.worker) {\n return this.worker;\n }\n const worker = new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n return worker;\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker().postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n createDefaultLogger,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory, parseUrl } from \"@shared/url\";\nimport { CLIENT_BASE_URL } from \"@shared/constants\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\nexport const createBrowserClient = (\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n const logger = clientOptions?.logger ?? createDefaultLogger();\n const baseUrl = parseUrl(clientOptions?.connection?.url) ?? CLIENT_BASE_URL;\n const telemetryClient = new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: clientOptions?.metadata?.appName,\n appVersion: clientOptions?.metadata?.appVersion,\n },\n logger: logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n });\n\n return new DefaultConfigDirectorClient(telemetryClient, clientSdkKey, sdkOptions, {\n ...clientOptions,\n logger,\n });\n};\n","import type {\n EvaluationContext,\n JsonValue,\n Paradigm,\n Provider,\n ProviderMetadata,\n ResolutionDetails,\n} from \"@openfeature/web-sdk\";\nimport { OpenFeatureEventEmitter, ProviderEvents, ProviderNotReadyError } from \"@openfeature/web-sdk\";\nimport type {\n ConfigDirectorClient,\n ConfigDirectorClientOptions,\n ConfigDirectorContext,\n ConfigValueType,\n} from \"@js-client-core/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\n\nexport class ConfigDirectorProvider implements Provider {\n private readonly client: ConfigDirectorClient;\n private awaitingRecovery = false;\n\n readonly metadata: ProviderMetadata = {\n name: ConfigDirectorProvider.name,\n };\n readonly runsOn: Paradigm = \"client\";\n readonly events = new OpenFeatureEventEmitter();\n\n public constructor(clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions) {\n this.client = createBrowserClient(\n clientSdkKey,\n {\n sdkName: \"js-openfeature-web-provider\",\n sdkVersion: \"__VERSION__\",\n },\n clientOptions,\n );\n this.client.on(\"clientReady\", () => {\n if (!this.awaitingRecovery) {\n return;\n }\n this.awaitingRecovery = false;\n this.events.emit(ProviderEvents.Ready);\n });\n this.client.on(\"configsUpdated\", ({ keys, removedKeys }) => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [...keys, ...removedKeys] });\n });\n }\n\n async initialize(context: EvaluationContext) {\n this.awaitingRecovery = false;\n await this.client.initialize(this.mapContext(context));\n this.requireReady(\n \"ConfigDirector did not become ready during initialization. Flags resolve to their default values \" +\n \"until the connection succeeds.\",\n );\n }\n\n async onContextChange?(_oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {\n this.awaitingRecovery = false;\n await this.client.updateContext(this.mapContext(newContext));\n this.requireReady(\n \"ConfigDirector did not become ready after the context changed. Flags resolve against the previous \" +\n \"context until the connection succeeds.\",\n );\n }\n\n resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T> {\n return this.evaluate(flagKey, defaultValue as ConfigValueType) as ResolutionDetails<T>;\n }\n\n onClose?(): Promise<void> {\n this.client.dispose();\n return Promise.resolve();\n }\n\n private requireReady(message: string) {\n if (this.client.isReady) {\n return;\n }\n this.awaitingRecovery = true;\n throw new ProviderNotReadyError(message);\n }\n\n private evaluate<T extends ConfigValueType>(configKey: string, defaultValue: T): ResolutionDetails<T> {\n const value = this.client.getValue(configKey, defaultValue);\n return {\n value,\n };\n }\n\n private mapContext(openFeatureContext: EvaluationContext): ConfigDirectorContext {\n if (!openFeatureContext) {\n return {};\n }\n\n const id = (openFeatureContext.targetingKey ?? openFeatureContext[\"id\"])?.toString();\n const name = openFeatureContext[\"name\"]?.toString();\n const traits = (openFeatureContext?.[\"traits\"] as Record<string, unknown>) || {};\n const hasTraits = typeof traits === \"object\" && Object.keys(traits).length > 0;\n const anonymousProp = openFeatureContext[\"anonymous\"];\n\n return {\n id,\n name,\n traits: hasTraits ? traits : undefined,\n anonymous: typeof anonymousProp === \"boolean\" ? anonymousProp : undefined,\n };\n }\n}\n"],"mappings":"8GAaA,IAAa,EAAb,KAAiG,eAC/F,KAAQ,WAAsE,IAAI,IAElF,GAAsC,EAAa,EAAwC,CACzF,IAAM,EAAW,KAAK,WAAW,IAAI,EAAK,CACtC,EACF,EAAS,KAAK,EAAQ,CAEtB,KAAK,WAAW,IAAI,EAAM,CAAC,EAAQ,CAAC,CAIxC,KAAwC,EAAa,EAAwC,CAE3F,IAAM,EAAO,KACb,SAAS,EAAY,EAA6C,CAChE,EAAK,IAAI,EAAM,EAAY,CAC3B,EAAQ,MAAM,EAAM,EAAQ,CAE9B,KAAK,GAAG,EAAM,EAAY,CAG5B,IAAuC,EAAa,EAAyC,CAC3F,IAAM,EAAW,KAAK,WAAW,IAAI,EAAK,CACrC,KAIL,GAAI,EAAS,CACX,IAAM,EAAgB,EAAS,QAAQ,EAAQ,CAC3C,GAAiB,GACnB,EAAS,OAAO,EAAe,EAAE,MAGnC,KAAK,WAAW,IAAI,EAAM,EAAE,CAAC,CAIjC,OAAQ,CACN,KAAK,WAAW,OAAO,CAGzB,KAAwC,EAAa,EAA+B,CAClF,IAAM,EAAW,KAAK,WAAW,IAAI,EAAK,CACrC,GAIL,EAAS,OAAO,CAAC,IAAK,GAAM,EAAE,EAAQ,CAAC,GC7D9B,EAAb,MAAa,UAAsC,KAAM,CAIvD,YAAY,EAAiB,EAAiB,CAC5C,MAAM,EAAQ,CAJhB,KAAyB,KAAe,gCAKtC,KAAK,OAAS,EAEd,OAAO,eAAe,KAAM,EAA8B,UAAU,GAI3D,EAAb,MAAa,UAAsC,KAAM,CAGvD,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,gCAKtC,OAAO,eAAe,KAAM,EAA8B,UAAU,GClB3D,EAAb,MAAa,UAA0B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AAmD,CAC3F,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAAwB,EAAiB,EAAiD,CACxF,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAAwB,EAAiB,EAAiD,CACxF,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAA6C,EAAiB,EAAuC,CACnG,OAAO,KAAK,SAAS,EAAS,EAAgC,CAGhE,SAA0B,CAExB,OADA,KAAK,OAAO,SAAS,CACd,QAAQ,SAAS,CAG1B,aAAqB,EAAiB,CAChC,SAAK,OAAO,QAIhB,KADA,MAAK,iBAAmB,GAClB,IAAI,EAAsB,EAAQ,CAG1C,SAA4C,EAAmB,EAAuC,CAEpG,MAAO,CACL,MAFY,KAAK,OAAO,SAAS,EAAW,EAAa,CAG1D,CAGH,WAAmB,EAA8D,WAC/E,GAAI,CAAC,EACH,MAAO,EAAE,CAGX,IAAM,GAAA,GAAA,EAAM,EAAmB,eAAA,KAAgB,EAAmB,GAAnC,IAAmC,KAAA,IAAA,GAAA,EAAQ,UAAU,CAC9E,GAAA,EAAO,EAAmB,OAAA,KAAA,IAAA,GAAA,EAAS,UAAU,CAC7C,GAAA,GAAA,KAAA,IAAA,GAAU,EAAqB,SAAyC,EAAE,CAC1E,EAAY,OAAO,GAAW,UAAY,OAAO,KAAK,EAAO,CAAC,OAAS,EACvE,EAAgB,EAAmB,UAEzC,MAAO,CACL,KACA,OACA,OAAQ,EAAY,EAAS,IAAA,GAC7B,UAAW,OAAO,GAAkB,UAAY,EAAgB,IAAA,GACjE"}
|
|
1
|
+
{"version":3,"file":"configdirector-openfeature-web-provider.mjs","names":["this","this","this","this","this"],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/errors.ts","../../eventsource/src/errors.ts","../../eventsource/src/EventSourceParser.ts","../../eventsource/src/types.ts","../../eventsource/src/EventSourceClient.ts","../../eventsource/src/index.ts","../../js-client-core/src/StreamingTransport.ts","../../shared/src/value-parser.ts","../../shared/src/logger.ts","../../js-client-core/src/logger.ts","../../shared/src/url.ts","../../shared/src/constants.ts","../../shared/src/transport/pollingInterval.ts","../../shared/src/instance-id.ts","../../js-client-core/src/instance-id.ts","../../shared/src/transport/AbstractPollingTransport.ts","../../shared/src/fetchWithTimeout.ts","../../js-client-core/src/PollingTransport.ts","../../js-client-core/src/browser-globals.ts","../../js-client-core/src/DefaultConfigDirectorClient.ts","../../shared/src/telemetry/utils.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/ConfigDirectorProvider.ts"],"sourcesContent":["type EventType = string | symbol;\ntype EventsRecord = Record<EventType, any>;\n\ntype Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (\n payload: TEventsRecord[TKey],\n) => void;\n\nexport interface EventProvider<TEventsRecord extends EventsRecord> {\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;\n clear(): void;\n}\n\nexport class Emitter<TEventsRecord extends EventsRecord> implements EventProvider<TEventsRecord> {\n private handlerMap: Map<keyof TEventsRecord, Array<(payload: any) => void>> = new Map();\n\n on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (handlers) {\n handlers.push(handler);\n } else {\n this.handlerMap.set(name, [handler]);\n }\n }\n\n once<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n function onceHandler(payload: TEventsRecord[keyof TEventsRecord]) {\n self.off(name, onceHandler);\n handler.apply(self, payload);\n }\n this.on(name, onceHandler);\n }\n\n off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n if (handler) {\n const listenerIndex = handlers.indexOf(handler);\n if (listenerIndex >= 0) {\n handlers.splice(listenerIndex, 1);\n }\n } else {\n this.handlerMap.set(name, []);\n }\n }\n\n clear() {\n this.handlerMap.clear();\n }\n\n emit<TName extends keyof TEventsRecord>(name: TName, payload: TEventsRecord[TName]) {\n const handlers = this.handlerMap.get(name);\n if (!handlers) {\n return;\n }\n\n handlers.slice().map((h) => h(payload));\n }\n}\n","export class ConfigDirectorConnectionError extends Error {\n public override readonly name: string = \"ConfigDirectorConnectionError\";\n public readonly status?: number;\n\n constructor(message: string, status?: number) {\n super(message);\n this.status = status;\n\n Object.setPrototypeOf(this, ConfigDirectorConnectionError.prototype);\n }\n}\n\nexport class ConfigDirectorValidationError extends Error {\n public override readonly name: string = \"ConfigDirectorValidationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorValidationError.prototype);\n }\n}\n\nexport class ConfigDirectorInitializationError extends Error {\n public override readonly name: string = \"ConfigDirectorInitializationError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorInitializationError.prototype);\n }\n}\n","export class StreamClosedError extends Error {\n public override readonly name: string = \"StreamClosedError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, StreamClosedError.prototype);\n }\n}\n\nexport class MissingResponseBodyError extends Error {\n public override readonly name: string = \"MissingResponseBodyError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, MissingResponseBodyError.prototype);\n }\n}\n\nexport class InvalidOptionError extends Error {\n public override readonly name: string = \"InvalidOptionError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, InvalidOptionError.prototype);\n }\n}\n\nexport class ValueOutOfRangeError extends Error {\n public override readonly name: string = \"ValueOutOfRangeError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ValueOutOfRangeError.prototype);\n }\n}\n","import {\n type EventSourceParserOptions,\n type EventSourceMessageHandler,\n type EventSourceCommentHandler,\n type EventParserRetryCallback,\n} from \"./types\";\n\ntype ParsedField = {\n field: string;\n value: string;\n};\n\nexport class EventSourceParser {\n private isFirstChunk = true;\n private bufferedInput = \"\";\n private currentEvent: { type?: string; data: string } = { data: \"\" };\n private lastEventId: string | undefined;\n private onEvent: EventSourceMessageHandler;\n private onRetry: EventParserRetryCallback | undefined;\n private onComment: EventSourceCommentHandler | undefined;\n\n constructor(options: EventSourceParserOptions) {\n this.currentEvent = { data: \"\" };\n this.onEvent = options.onEvent ?? (() => {});\n this.onRetry = options.onRetry;\n this.onComment = options.onComment;\n }\n\n public parse(chunk: string): void {\n let input = chunk;\n\n if (this.isFirstChunk) {\n this.isFirstChunk = false;\n if (input.startsWith(\"\\uFEFF\")) {\n input = input.slice(1);\n } else if (input.startsWith(\"\\xEF\\xBB\\xBF\")) {\n input = input.slice(3);\n }\n }\n\n const lines = this.scanLines(this.bufferedInput + input);\n for (const line of lines) {\n this.dispatchLine(line);\n }\n }\n\n // Per the SSE spec, any data still buffered when the stream ends is discarded —\n // an event requires a terminating empty line to be dispatched.\n public finish(): void {\n this.bufferedInput = \"\";\n }\n\n /**\n * Scans `text` character by character to extract complete lines, recognizing\n * CR, LF, and CRLF as line terminators per the SSE spec. Any unterminated\n * trailing text is buffered and prepended to the next chunk.\n */\n private scanLines(text: string): string[] {\n const lines: string[] = [];\n let lineStart = 0;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"\\r\" || ch === \"\\n\") {\n lines.push(text.slice(lineStart, i));\n // Consume CRLF as a single terminator rather than two separate lines.\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") {\n i++;\n }\n i++;\n lineStart = i;\n } else {\n i++;\n }\n }\n\n this.bufferedInput = text.slice(lineStart);\n return lines;\n }\n\n private dispatchLine(line: string): void {\n if (line.startsWith(\":\")) {\n this.onComment?.(this.extractValue(line, 1));\n return;\n }\n\n if (line === \"\") {\n this.emitEvent();\n return;\n }\n\n this.applyField(this.parseField(line));\n }\n\n private emitEvent(): void {\n const data = this.currentEvent.data.endsWith(\"\\n\")\n ? this.currentEvent.data.slice(0, -1)\n : this.currentEvent.data;\n\n if (data !== \"\") {\n this.onEvent({ ...this.currentEvent, id: this.lastEventId, data });\n }\n\n this.currentEvent = { data: \"\" };\n }\n\n private applyField(parsed: ParsedField): void {\n switch (parsed.field) {\n case \"event\":\n this.currentEvent.type = parsed.value;\n break;\n case \"data\":\n this.currentEvent.data += parsed.value + \"\\n\";\n break;\n case \"id\":\n // Spec: ignore id values that contain a null character.\n if (!parsed.value.includes(\"\\0\")) {\n this.lastEventId = parsed.value;\n }\n break;\n case \"retry\":\n if (/^\\d+$/.test(parsed.value)) {\n this.onRetry?.(Number.parseInt(parsed.value, 10));\n }\n break;\n default:\n break;\n }\n }\n\n private parseField(line: string): ParsedField {\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n return { field: line, value: \"\" };\n }\n return { field: line.slice(0, colon), value: this.extractValue(line, colon + 1) };\n }\n\n /** Returns the value portion of a line, stripping a single leading space per spec. */\n private extractValue(line: string, from: number): string {\n return line[from] === \" \" ? line.slice(from + 1) : line.slice(from);\n }\n}\n","export type ReconnectionState = {\n attempt: number;\n serverReconnectionTime: number;\n status?: number | undefined;\n error?: Error | undefined;\n};\n\nexport enum ReadyState {\n OPEN = \"open\",\n CLOSED = \"closed\",\n CONNECTING = \"connecting\",\n}\n\nexport type EventSourceClientOptions = {\n url: { toString(): string } | string;\n method?: string;\n headers?: Record<string, string>;\n body?: string | (() => string);\n mode?: \"cors\" | \"no-cors\" | \"same-origin\";\n credentials?: \"include\" | \"omit\" | \"same-origin\";\n redirect?: \"error\" | \"follow\";\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n lastEventId?: string;\n fetch?: (url: string, init: RequestInit) => Promise<Response>;\n onError?: (error: Error) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onMessage?: EventSourceMessageHandler;\n onComment?: EventSourceCommentHandler;\n shouldReconnect?: (state: ReconnectionState) => boolean;\n calculateReconnectDelay?: (state: ReconnectionState) => number;\n};\n\nexport type EventSourceMessage = {\n id?: string | undefined;\n type?: string;\n data: string;\n};\n\nexport type EventSourceMessageHandler = (message: EventSourceMessage) => void;\nexport type EventSourceCommentHandler = (comment: string) => void;\n\nexport type EventParserRetryCallback = (retry: number) => void;\n\nexport type EventSourceParserOptions = {\n onEvent?: EventSourceMessageHandler;\n onRetry?: EventParserRetryCallback;\n onComment?: EventSourceCommentHandler;\n};\n","import {\n InvalidOptionError,\n MissingResponseBodyError,\n StreamClosedError,\n ValueOutOfRangeError,\n} from \"./errors\";\nimport { EventSourceParser } from \"./EventSourceParser\";\nimport {\n type EventSourceClientOptions,\n type EventSourceCommentHandler,\n type EventSourceMessageHandler,\n type ReconnectionState,\n ReadyState,\n} from \"./types\";\n\nexport class EventSourceClient {\n private readonly DEFAULT_SHOULD_RECONNECT = () => true;\n private readonly DEFAULT_CALCULATE_RECONNECT_DELAY = () => this.serverReconnectionTime;\n private readonly url: string;\n private readonly headers?: Record<string, string>;\n private readonly body: () => string | undefined;\n private readonly requestOptions;\n private lastEventId?: string;\n private reconnectAttempt: number = 0;\n private abortController: AbortController = new AbortController();\n private reconnectTimeout: ReturnType<typeof setTimeout> | undefined;\n private _readyState: ReadyState = ReadyState.CLOSED;\n private serverReconnectionTime: number = 2_000;\n private _fetch: (url: string, init: RequestInit) => Promise<Response>;\n private _onError: (error: Error) => void;\n private _onMessage: EventSourceMessageHandler;\n private _onComment: EventSourceCommentHandler;\n private _onConnect: () => void;\n private _onDisconnect: () => void;\n private _shouldReconnect: (state: ReconnectionState) => boolean;\n private _calculateReconnectDelay: (state: ReconnectionState) => number;\n\n constructor(options: EventSourceClientOptions) {\n this.url = options.url.toString();\n this.lastEventId = options.lastEventId;\n this.headers = {\n Accept: \"text/event-stream\",\n ...options.headers,\n };\n const body = options.body;\n this.body = typeof body === \"function\" ? body : () => body;\n this.requestOptions = {\n method: options.method ?? \"GET\",\n mode: options.mode,\n credentials: options.credentials,\n redirect: options.redirect,\n referrer: options.referrer,\n referrerPolicy: options.referrerPolicy,\n };\n this._fetch = options.fetch ?? ((url, init) => fetch(url, init));\n this._onError = this.resolveCallback(options.onError, () => {}, \"onError\");\n this._onConnect = this.resolveCallback(options.onConnect, () => {}, \"onConnect\");\n this._onDisconnect = this.resolveCallback(options.onDisconnect, () => {}, \"onDisconnect\");\n this._onMessage = this.resolveCallback(options.onMessage, () => {}, \"onMessage\");\n this._onComment = this.resolveCallback(options.onComment, () => {}, \"onComment\");\n this._shouldReconnect = this.resolveCallback(\n options.shouldReconnect,\n this.DEFAULT_SHOULD_RECONNECT,\n \"shouldReconnect\",\n );\n this._calculateReconnectDelay = this.resolveCallback(\n options.calculateReconnectDelay,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"calculateReconnectDelay\",\n );\n }\n\n public set onError(value: (error: Error) => void) {\n this._onError = this.resolveCallback(value, () => {}, \"onError\");\n }\n\n public set onMessage(value: EventSourceMessageHandler) {\n this._onMessage = this.resolveCallback(value, () => {}, \"onMessage\");\n }\n\n public set onComment(value: EventSourceCommentHandler) {\n this._onComment = this.resolveCallback(value, () => {}, \"onComment\");\n }\n\n public set onConnect(value: () => void) {\n this._onConnect = this.resolveCallback(value, () => {}, \"onConnect\");\n }\n\n public set onDisconnect(value: () => void) {\n this._onDisconnect = this.resolveCallback(value, () => {}, \"onDisconnect\");\n }\n\n public set shouldReconnect(value: (state: ReconnectionState) => boolean) {\n this._shouldReconnect = this.resolveCallback(value, this.DEFAULT_SHOULD_RECONNECT, \"shouldReconnect\");\n }\n\n public set calculateReconnectDelay(value: (state: ReconnectionState) => number) {\n this._calculateReconnectDelay = this.resolveCallback(\n value,\n this.DEFAULT_CALCULATE_RECONNECT_DELAY,\n \"shouldReconnect\",\n );\n }\n\n public get readyState(): ReadyState {\n return this._readyState;\n }\n\n public connect() {\n if (this._readyState !== ReadyState.CLOSED) {\n return;\n }\n\n this.reconnectAttempt = 0;\n this.initiateConnection();\n }\n\n public close() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this.abortController.abort();\n }\n\n private initiateConnection() {\n this.abortController = new AbortController();\n this._readyState = ReadyState.CONNECTING;\n\n this._fetch(this.url, {\n ...this.requestOptions,\n body: this.body(),\n headers: this.buildRequestHeaders(),\n signal: this.abortController.signal,\n cache: \"no-store\",\n })\n .then((response) => this.handleFetchResponse(response))\n .catch((error: Error) => {\n if (error.name === \"AbortError\" || this.abortController.signal.aborted) {\n this.close();\n return;\n }\n\n this._onError(error);\n this.scheduleReconnect({ error });\n });\n }\n\n private async handleFetchResponse(response: Response) {\n const { body, status } = response;\n\n if (status === 204) {\n this.disconnected();\n return;\n }\n\n if (status >= 400) {\n this.scheduleReconnect({ status });\n return;\n }\n\n if (!body) {\n throw new MissingResponseBodyError(\"The server response did not have a body\");\n }\n\n this._readyState = ReadyState.OPEN;\n this._onConnect();\n this.reconnectAttempt = 0;\n\n const parser = new EventSourceParser({\n onEvent: (event) => {\n if (typeof event.id === \"string\") {\n this.lastEventId = event.id;\n }\n this._onMessage(event);\n },\n onComment: (comment) => this._onComment(comment),\n onRetry: (retryDelay) => (this.serverReconnectionTime = retryDelay),\n });\n\n await this.readResponseStream(body, parser);\n\n this.scheduleReconnect({\n status,\n error: new StreamClosedError(\"The server response stream was closed\"),\n });\n }\n\n private async readResponseStream(body: ReadableStream<Uint8Array>, parser: EventSourceParser) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let done = false;\n while (!done) {\n const result = await reader.read();\n if (result.value) {\n parser.parse(decoder.decode(result.value, { stream: true }));\n }\n done = result.done;\n }\n\n parser.finish();\n }\n\n private disconnected() {\n clearTimeout(this.reconnectTimeout);\n this._readyState = ReadyState.CLOSED;\n this._onDisconnect();\n }\n\n private buildRequestHeaders(): Record<string, string> {\n const lastEventIdHeader = this.lastEventId ? { \"Last-Event-ID\": this.lastEventId } : undefined;\n return {\n ...this.headers,\n ...lastEventIdHeader,\n };\n }\n\n private scheduleReconnect(state: { status?: number; error?: Error }) {\n if (this.abortController.signal.aborted) {\n return;\n }\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectAttempt += 1;\n\n const reconnectionState: ReconnectionState = {\n attempt: this.reconnectAttempt,\n status: state.status,\n error: state.error,\n serverReconnectionTime: this.serverReconnectionTime,\n };\n\n if (!this._shouldReconnect(reconnectionState)) {\n this.disconnected();\n return;\n }\n\n this._readyState = ReadyState.CONNECTING;\n let delay = this._calculateReconnectDelay(reconnectionState);\n\n if (!Number.isFinite(delay) || delay < 1 || delay > 1_000 * 60 * 60) {\n this._onError(\n new ValueOutOfRangeError(\n `The calculated reconnect delay is out of range: ${delay}. Defaulting to ${this.serverReconnectionTime}`,\n ),\n );\n delay = this.serverReconnectionTime;\n }\n\n this.reconnectTimeout = setTimeout(() => this.initiateConnection(), delay);\n }\n\n private resolveCallback<T extends (...args: any[]) => any>(\n provided: unknown,\n fallback: T,\n optionName: string,\n ): T {\n if (provided == null) return fallback;\n if (typeof provided !== \"function\") {\n throw new InvalidOptionError(`${optionName} must be a function`);\n }\n return provided as T;\n }\n}\n","import { EventSourceClient } from \"./EventSourceClient\";\nimport { type EventSourceClientOptions } from \"./types\";\n\nexport const createEventSourceClient = (options: EventSourceClientOptions) => {\n return new EventSourceClient(options);\n};\n","import type {\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { ConfigDirectorConnectionError } from \"./errors\";\nimport { createEventSourceClient } from \"@eventsource/index\";\nimport type { EventSourceClient } from \"@eventsource/EventSourceClient\";\nimport type { UrlLike } from \"@shared/url\";\n\nexport class StreamingTransport implements Transport {\n private logger: ConfigDirectorLogger;\n private eventSource: EventSourceClient | undefined;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(private readonly options: TransportOptions) {\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/sse/v1\", options.baseUrl);\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n if (this.eventSource) {\n this.close();\n }\n\n const eventSourcePromise = new Promise<this>((resolve, reject) => {\n this.eventSource = createEventSourceClient({\n url: this.url,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n fetch: this.options.fetch,\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: this.options.instanceId,\n }),\n\n onMessage: ({ data }) => {\n this.dispatchMessage(data);\n },\n onConnect: () => {\n this.logger.debug(\"[StreamingTransport] Connected\");\n resolve(this);\n },\n shouldReconnect: (state) => {\n const reconnect = !this.isStatusFatal(state.status);\n if (!reconnect) {\n const error = this.prepareFatalError(state.status, state.error);\n this.eventEmitter.emit(\"connectionError\", error);\n reject(error);\n }\n return reconnect;\n },\n calculateReconnectDelay: (state) => {\n const delay = this.options.connectionRetryDelay(state.attempt);\n const logMessage = `[StreamingTransport] Scheduling reconnect attempt #${state.attempt} in ${delay}ms.`;\n if (state.attempt <= 5) {\n this.logger.info(logMessage);\n } else {\n this.logger.warn(logMessage);\n }\n return delay;\n },\n onError: (error) => {\n this.logger.debug(\"[StreamingTransport] Error: \", error);\n },\n onDisconnect: () => {\n this.logger.debug(\"[StreamingTransport] Disconnected\");\n },\n });\n this.eventSource.connect();\n });\n\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n return Promise.race([\n eventSourcePromise,\n new Promise<this>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(this), timeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n private dispatchMessage(data: string) {\n try {\n const json = JSON.parse(data);\n this.eventEmitter.emit(\"configSetReceived\", json);\n } catch (error) {\n this.logger.error(\"[StreamingTransport] Error parsing and dispatching config data update: \", error);\n }\n }\n\n private prepareFatalError(\n responseStatus: number | undefined,\n error: Error | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}.`;\n const errorLine = error ? ` Error: ${error}` : \"\";\n const message = `${headline}${errorLine}. This is an unrecoverable error, will not attempt to reconnect.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n private isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n\n public close() {\n this.eventSource?.close();\n clearTimeout(this.timeoutTimer);\n }\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import type { ConfigState, ConfigType, ConfigValueType, EvaluationReason } from \"./types\";\n\ntype NativeType = \"string\" | \"number\" | \"bigint\" | \"boolean\" | \"symbol\" | \"undefined\" | \"object\" | \"function\";\n\ntype ParseResult<T extends ConfigValueType> = {\n parsedValue: T;\n parsedValueId: string | null | undefined;\n requestedType: NativeType | string;\n usedDefault: boolean;\n reason: EvaluationReason;\n};\n\nexport const getRequestedType = <T extends ConfigValueType>(defaultValue: T): string => {\n const baseType = typeof defaultValue;\n if (baseType === \"object\") {\n try {\n return (defaultValue as object).constructor?.name ?? baseType;\n } catch {\n return baseType;\n }\n } else if (baseType === \"function\") {\n try {\n const functionName = (defaultValue as any).name;\n return functionName ? `function: ${functionName}` : baseType;\n } catch {\n return baseType;\n }\n }\n return baseType;\n};\n\nconst isNumericNativeType = (requestedType: NativeType): boolean => {\n return requestedType === \"number\" || requestedType === \"bigint\";\n};\n\nconst configTypesNotReadableAsString: ReadonlySet<ConfigType> = new Set<ConfigType>([\"boolean\", \"integer\", \"float\"]);\n\nexport const parseConfigValue = <T extends ConfigValueType>(\n configState: ConfigState,\n defaultValue: T,\n): ParseResult<T> => {\n const value = configState.value;\n const requestedType = getRequestedType(defaultValue);\n\n if (value == null || value === \"\") {\n return {\n parsedValue: defaultValue as T,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"value-missing\",\n };\n }\n\n if (configState.type === \"json\") {\n return parseJson(value, defaultValue, requestedType, configState.valueId);\n }\n\n if (typeof defaultValue === \"string\") {\n if (configTypesNotReadableAsString.has(configState.type)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: value as T,\n parsedValueId: configState.valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n if (\n typeof defaultValue === \"boolean\" &&\n (configState.type === \"boolean\" || configState.type === \"string\" || configState.type === \"enum\")\n ) {\n const boolValue = parseConfigBoolean(value);\n const hasBoolean = typeof boolValue === \"boolean\";\n return {\n parsedValue: (hasBoolean ? boolValue : defaultValue) as T,\n parsedValueId: hasBoolean ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasBoolean,\n reason: hasBoolean ? \"found-match\" : \"invalid-boolean\",\n };\n }\n\n if (isNumericNativeType(typeof defaultValue) && configState.type === \"integer\") {\n const numValue = parseConfigInteger(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n if (\n isNumericNativeType(typeof defaultValue) &&\n (configState.type === \"float\" || configState.type === \"enum\" || configState.type === \"string\")\n ) {\n const numValue = parseConfigFloat(value);\n const hasNumber = typeof numValue === \"number\";\n return {\n parsedValue: (hasNumber ? numValue : defaultValue) as T,\n parsedValueId: hasNumber ? configState.valueId : undefined,\n requestedType,\n usedDefault: !hasNumber,\n reason: hasNumber ? \"found-match\" : \"invalid-number\",\n };\n }\n\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n};\n\nconst parseConfigBoolean = (value: string): boolean | undefined => {\n if (!value) {\n return;\n }\n const lowerValue = value.toLowerCase();\n if (lowerValue != \"true\" && lowerValue != \"false\") {\n return;\n }\n return lowerValue === \"true\";\n};\n\nconst parseConfigInteger = (value: string): number | undefined => {\n const num = parseStrictNumber(value);\n return num == null ? undefined : Math.trunc(num);\n};\n\nconst parseConfigFloat = (value: string): number | undefined => {\n return parseStrictNumber(value);\n};\n\nconst parseStrictNumber = (value: string): number | undefined => {\n if (!value || !isDecimalCharacters(value)) {\n return;\n }\n const num = Number(value);\n if (isNaN(num) || !isFinite(num)) {\n return;\n }\n return num;\n};\n\nconst isDecimalCharacters = (value: string): boolean => {\n for (const character of value) {\n const isDigit = character >= \"0\" && character <= \"9\";\n if (!isDigit && !\"+-.eE\".includes(character)) {\n return false;\n }\n }\n return true;\n};\n\nconst parseJson = <T extends ConfigValueType>(\n jsonString: string,\n defaultValue: T,\n requestedType: string,\n valueId: string | null | undefined,\n): ParseResult<T> => {\n if (typeof defaultValue === \"string\") {\n return {\n parsedValue: jsonString as T,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n }\n\n try {\n const parsed = JSON.parse(jsonString);\n if (!isJsonTypeCompatible(parsed, defaultValue)) {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"type-mismatch\",\n };\n }\n return {\n parsedValue: parsed,\n parsedValueId: valueId,\n requestedType,\n usedDefault: false,\n reason: \"found-match\",\n };\n } catch {\n return {\n parsedValue: defaultValue,\n parsedValueId: undefined,\n requestedType,\n usedDefault: true,\n reason: \"invalid-json\",\n };\n }\n};\n\nconst isJsonTypeCompatible = (parsed: unknown, defaultValue: ConfigValueType): boolean => {\n if (parsed === null) {\n return false;\n }\n const defaultType = typeof defaultValue;\n if (defaultType === \"bigint\") {\n return typeof parsed === \"number\";\n }\n return typeof parsed === defaultType;\n};\n","import type { ConfigDirectorLogger, ConfigDirectorLogMessageDecorator, ConfigDirectorLoggingLevel } from \"./types\";\n\nconst LEVELS: Record<ConfigDirectorLoggingLevel, number> = {\n off: -1,\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nconst buildDateFormatter = () => {\n const baseOptions: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n };\n\n try {\n return new Intl.DateTimeFormat(\n undefined,\n { ...baseOptions, fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions,\n );\n } catch {\n return new Intl.DateTimeFormat(undefined, baseOptions);\n }\n};\n\nexport class DefaultConsoleLogger implements ConfigDirectorLogger {\n private readonly dateFormatter;\n\n constructor(private readonly level: ConfigDirectorLoggingLevel, private readonly decorator: ConfigDirectorLogMessageDecorator) {\n this.level = level;\n this.decorator = decorator;\n this.dateFormatter = buildDateFormatter();\n }\n\n debug(message: string, ...args: any): void {\n this.log(console.debug, \"debug\", message, ...args);\n }\n\n info(message: string, ...args: any): void {\n this.log(console.info, \"info\", message, ...args);\n }\n\n warn(message: string, ...args: any): void {\n this.log(console.warn, \"warn\", message, ...args);\n }\n\n error(message: string, ...args: any): void {\n this.log(console.error, \"error\", message, ...args);\n }\n\n protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any) {\n if (LEVELS[this.level] >= LEVELS[level]) {\n loggerFunction(`[${this.dateFormatter.format(new Date())}] ${this.decorator?.decorateMessage(message)}`, ...args);\n }\n }\n}\n","import { type ConfigDirectorLogMessageDecorator, type ConfigDirectorLoggingLevel } from \"./types\";\nimport { DefaultConsoleLogger } from \"../../shared/src/logger\";\nexport { DefaultConsoleLogger } from \"../../shared/src/logger\";\n\nclass LogMessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:js-client-sdk] ${message}`;\n }\n}\n\nexport const createDefaultLogger = (\n level?: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return new DefaultConsoleLogger(level ?? \"warn\", messageDecorator ?? new LogMessageDecorator());\n};\n","import { ConfigDirectorValidationError } from \"./errors\";\n\nexport interface UrlLike {\n toString(): string;\n}\n\nexport type UrlFactory = (input: string, base?: UrlLike) => UrlLike;\n\nexport const defaultUrlFactory: UrlFactory = (input, base) => new URL(input, base?.toString());\n\nexport const parseUrl = (url: string | undefined): URL | undefined => {\n if (!url) {\n return;\n }\n\n try {\n return new URL(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid URL '${url}'. Parsing failed: ${error}`);\n }\n};\n","export const CLIENT_BASE_URL = \"https://client-sdk-api.configdirector.com\";\nexport const CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS = 60;\nexport const CLIENT_MIN_POLLING_INTERVAL_SECONDS = 30;\nexport const SERVER_DEFAULT_POLLING_INTERVAL_SECONDS = 300;\nexport const SERVER_MIN_POLLING_INTERVAL_SECONDS = 60;\n","export type PollingIntervalDefaults = {\n defaultSeconds: number;\n minimumSeconds: number;\n};\n\nexport type ResolvedPollingInterval = {\n seconds: number;\n warning: string | undefined;\n};\n\nexport const resolvePollingInterval = (\n configuredSeconds: number | undefined,\n defaults: PollingIntervalDefaults,\n): ResolvedPollingInterval => {\n if (configuredSeconds === undefined) {\n return { seconds: defaults.defaultSeconds, warning: undefined };\n }\n if (configuredSeconds >= defaults.minimumSeconds) {\n return { seconds: configuredSeconds, warning: undefined };\n }\n return {\n seconds: defaults.minimumSeconds,\n warning: `pollingInterval of ${configuredSeconds} seconds is below the minimum of ${defaults.minimumSeconds} seconds. Using ${defaults.minimumSeconds} seconds.`,\n };\n};\n","// React Native's Hermes engine does not expose a global `crypto`, unlike browsers and Node 19+.\nexport const generateInstanceId = (): string => {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (placeholder) => {\n const random = (Math.random() * 16) | 0;\n const value = placeholder === \"x\" ? random : (random & 0x3) | 0x8;\n return value.toString(16);\n });\n};\n","import { generateInstanceId } from \"@shared/instance-id\";\nimport type { ConfigDirectorLogger } from \"./types\";\n\nconst STORAGE_KEY = \"configdirector-sdk:instance-id\";\nconst RECORD_VERSION = 1;\nconst MAX_AGE_MS = 6 * 60 * 60 * 1_000;\nconst CHECKSUM_SALT = \"configdirector.instanceId.v1\";\nconst UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\ntype StoredInstanceId = {\n v: number;\n id: string;\n createdAt: number;\n checksum: string;\n};\n\nconst fnv1a = (input: string, offsetBasis: number): number => {\n let hash = offsetBasis;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n};\n\nconst checksumFor = (id: string, createdAt: number): string => {\n const payload = `${CHECKSUM_SALT}|${id}|${createdAt}`;\n const low = fnv1a(payload, 0x811c9dc5);\n const high = fnv1a(`${low}|${payload}`, 0x01000193);\n return high.toString(16).padStart(8, \"0\") + low.toString(16).padStart(8, \"0\");\n};\n\nconst getLocalStorage = (): Storage | undefined => {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage ?? undefined;\n } catch {\n return undefined;\n }\n};\n\nconst isUsableRecord = (record: unknown): record is StoredInstanceId => {\n if (!record || typeof record !== \"object\") {\n return false;\n }\n\n const { v, id, createdAt, checksum } = record as Partial<StoredInstanceId>;\n if (v !== RECORD_VERSION || typeof id !== \"string\" || typeof checksum !== \"string\") {\n return false;\n }\n\n if (typeof createdAt !== \"number\" || !Number.isInteger(createdAt) || createdAt <= 0) {\n return false;\n }\n\n if (!UUID_V4_PATTERN.test(id)) {\n return false;\n }\n\n return checksum === checksumFor(id, createdAt);\n};\n\nconst readStoredInstanceId = (storage: Storage, logger?: ConfigDirectorLogger): string | undefined => {\n let raw: string | null;\n try {\n raw = storage.getItem(STORAGE_KEY);\n } catch (error) {\n logger?.debug(\"[ConfigDirectorClient] Could not read the stored instance id, generating a new one\", error);\n return undefined;\n }\n\n if (!raw) {\n return undefined;\n }\n\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one\");\n return undefined;\n }\n\n if (!isUsableRecord(record)) {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id failed validation, generating a new one\");\n return undefined;\n }\n\n const age = Date.now() - record.createdAt;\n if (age < 0 || age >= MAX_AGE_MS) {\n logger?.debug(\"[ConfigDirectorClient] The stored instance id has expired, generating a new one\");\n return undefined;\n }\n\n return record.id;\n};\n\nconst storeInstanceId = (storage: Storage, id: string, logger?: ConfigDirectorLogger) => {\n const createdAt = Date.now();\n const record: StoredInstanceId = { v: RECORD_VERSION, id, createdAt, checksum: checksumFor(id, createdAt) };\n try {\n storage.setItem(STORAGE_KEY, JSON.stringify(record));\n } catch (error) {\n logger?.debug(\"[ConfigDirectorClient] Could not persist the instance id\", error);\n }\n};\n\nexport const resolveInstanceId = (logger?: ConfigDirectorLogger): string => {\n const storage = getLocalStorage();\n if (!storage) {\n return generateInstanceId();\n }\n\n const storedInstanceId = readStoredInstanceId(storage, logger);\n if (storedInstanceId) {\n return storedInstanceId;\n }\n\n const instanceId = generateInstanceId();\n storeInstanceId(storage, instanceId, logger);\n return instanceId;\n};\n","import { ConfigDirectorConnectionError } from \"../errors\";\n\nexport abstract class AbstractPollingTransport {\n protected fatalError = false;\n protected pollingInterval: ReturnType<typeof setInterval> | undefined;\n protected abstract pollingIntervalSeconds: number;\n\n protected clearPollingInterval() {\n clearInterval(this.pollingInterval);\n }\n\n protected schedulePollingInterval(callback: () => void) {\n clearInterval(this.pollingInterval);\n if (this.pollingIntervalSeconds <= 0) {\n return;\n }\n this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1_000);\n }\n\n protected async handleNonOkResponse(response: Response) {\n if (!response.ok) {\n if (this.isStatusFatal(response.status)) {\n this.fatalError = true;\n this.close();\n throw this.prepareFatalResponseStatusError(response.status, await response.text());\n } else {\n throw new ConfigDirectorConnectionError(\n `Connection failed with status: ${response.status}`,\n response.status,\n );\n }\n }\n }\n\n protected handleFetchError(fetchError: unknown) {\n if (this.isFetchErrorFatal(fetchError)) {\n this.fatalError = true;\n this.close();\n throw new ConfigDirectorConnectionError(\n `Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`,\n );\n } else if (fetchError instanceof SyntaxError) {\n throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);\n } else {\n throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);\n }\n }\n\n protected prepareFatalResponseStatusError(\n responseStatus: number,\n errorBody: string | undefined,\n ): ConfigDirectorConnectionError {\n const status = responseStatus ?? 0;\n const headline = `Connection failed with status: ${responseStatus ?? \"unknown\"}`;\n const serverBody = (errorBody?.trim()?.length ?? 0) > 0 ? ` (${errorBody})` : \"\";\n const message = `${headline}${serverBody}. This is an unrecoverable error, retry attempts will be ignored.`;\n return new ConfigDirectorConnectionError(message, status);\n }\n\n protected isStatusFatal(status: number | undefined): boolean {\n return !!status && status >= 400 && status < 500 && status != 429;\n }\n\n protected isFetchErrorFatal(fetchError: unknown): boolean {\n return (fetchError as any)?.name === \"NotAllowedError\";\n }\n\n public get isConnected(): boolean {\n return this.pollingInterval !== undefined;\n }\n\n public close() {\n clearInterval(this.pollingInterval);\n this.pollingInterval = undefined;\n }\n\n public abstract clear(): void;\n\n public dispose(): void {\n this.close();\n this.clear();\n }\n}\n","import { type ConfigDirectorLogger } from \"./types\";\nimport type { UrlLike } from \"./url\";\n\nexport const fetchWithTimeout = async (\n timeout: number,\n resource: string | UrlLike | Request,\n options: RequestInit | undefined,\n logger: ConfigDirectorLogger,\n) => {\n const abortController = new AbortController();\n const abortTimeoutId = setTimeout(() => {\n logger.debug(\"[fetchWithTimeout] Reached timeout, aborting request\");\n abortController.abort();\n }, timeout);\n\n try {\n const response = await fetch(typeof resource === \"string\" || resource instanceof Request ? resource : resource.toString(), {\n ...options,\n signal: abortController.signal,\n });\n clearTimeout(abortTimeoutId);\n return response;\n } catch (error) {\n logger.warn(\"[fetchWithTimeout] Fetch error: \", error);\n clearTimeout(abortTimeoutId);\n throw error;\n }\n};\n","import type {\n ConfigDirectorContext,\n ConfigDirectorLogger,\n Transport,\n TransportEvents,\n TransportOptions,\n} from \"./types\";\nimport { Emitter } from \"./Emitter\";\nimport { AbstractPollingTransport } from \"@shared/transport/AbstractPollingTransport\";\nimport { fetchWithTimeout } from \"@shared/fetchWithTimeout\";\nimport type { UrlLike } from \"@shared/url\";\nimport { CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS } from \"@shared/constants\";\n\nexport class PollingTransport extends AbstractPollingTransport implements Transport {\n protected pollingIntervalSeconds: number;\n private logger: ConfigDirectorLogger;\n private eventEmitter = new Emitter<TransportEvents>();\n private url: UrlLike;\n private lastUpdateTimestamp: string | undefined;\n\n constructor(private readonly options: TransportOptions) {\n super();\n this.options = options;\n this.logger = options.logger;\n this.url = options.resolveUrl(\"client/polling/v1\", options.baseUrl);\n this.pollingIntervalSeconds = options.pollingInterval ?? CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS;\n }\n\n public async connect(context: ConfigDirectorContext, timeout: number): Promise<this> {\n this.clearPollingInterval();\n\n try {\n await this.fetchConfigs(context, timeout);\n } finally {\n // A transient failure on the first fetch must not leave the client without a\n // connection, so polling is scheduled either way. An unrecoverable failure has\n // already closed the transport and must not be retried.\n if (!this.fatalError) {\n this.schedulePollingInterval(() => {\n void this.fetchConfigs(context, timeout).catch((error) => {\n this.logger.error(\"[PollingTransport] Error during polling:\", error);\n });\n });\n }\n }\n\n return this;\n }\n\n private async fetchConfigs(context: ConfigDirectorContext, timeout: number) {\n if (this.fatalError) {\n this.logger.warn(\n \"[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.\",\n );\n return;\n }\n\n try {\n const response = await fetchWithTimeout(\n timeout,\n this.url,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n givenContext: context,\n metaContext: this.options.metaContext,\n clientSdkKey: this.options.clientSdkKey,\n instanceId: this.options.instanceId,\n lastUpdateTimestamp: this.lastUpdateTimestamp,\n }),\n },\n this.logger,\n );\n\n await this.handleNonOkResponse(response);\n\n if (response.status == 200) {\n const json = JSON.parse(await response.text());\n this.lastUpdateTimestamp = json.timestamp;\n this.eventEmitter.emit(\"configSetReceived\", json);\n }\n } catch (fetchError) {\n try {\n this.handleFetchError(fetchError);\n } catch (handledError) {\n if (this.fatalError) {\n this.eventEmitter.emit(\"connectionError\", handledError as Error);\n }\n throw handledError;\n }\n }\n }\n\n public on<TName extends keyof TransportEvents>(\n name: TName,\n handler: (payload: TransportEvents[TName]) => void,\n ): void {\n this.eventEmitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(\n name: TName,\n handler?: ((payload: TransportEvents[TName]) => void) | undefined,\n ): void {\n this.eventEmitter.off(name, handler);\n }\n\n public clear(): void {\n this.eventEmitter.clear();\n }\n}\n","type BrowserGlobals = {\n navigator?: { userAgent?: string };\n location?: { host?: string };\n};\n\nconst read = (readValue: (globals: BrowserGlobals) => string | undefined): string | undefined => {\n try {\n return readValue(globalThis as BrowserGlobals);\n } catch {\n return undefined;\n }\n};\n\nexport const readUserAgent = (): string | undefined => read((globals) => globals.navigator?.userAgent);\n\nexport const readHost = (): string | undefined => read((globals) => globals.location?.host);\n","import { Emitter } from \"./Emitter\";\nimport { StreamingTransport } from \"./StreamingTransport\";\nimport { getRequestedType, parseConfigValue } from \"../../shared/src/value-parser\";\nimport type {\n ConfigSet,\n ConfigState,\n ConfigDirectorContext,\n ConfigDirectorClientOptions,\n ConfigDirectorClient,\n ClientEvents,\n WatchHandler,\n ConfigValueType,\n ConfigDirectorLogger,\n Transport,\n ClientConnectAction,\n IdentifyingSdkOptions,\n InternalClientOptions,\n ConnectionMode,\n ConfigEvaluation,\n HookHandler,\n} from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\nimport { ConfigDirectorValidationError } from \"./errors\";\nimport type { TelemetryClient } from \"./telemetry\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport type { UrlFactory, UrlLike } from \"@shared/url\";\nimport {\n CLIENT_BASE_URL,\n CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS,\n CLIENT_MIN_POLLING_INTERVAL_SECONDS,\n} from \"@shared/constants\";\nimport { resolvePollingInterval } from \"@shared/transport/pollingInterval\";\nimport { resolveInstanceId } from \"./instance-id\";\nimport { PollingTransport } from \"./PollingTransport\";\nimport { readHost, readUserAgent } from \"./browser-globals\";\nconst MAX_EXPONENTIAL_DELAY = 9; // 2^9 = 512 seconds, to cap it to under 10min\n\ntype WatchHandlerWithOptions<T extends ConfigValueType> = {\n handler: WatchHandler<T>;\n defaultValue: T;\n requestedType: string;\n};\n\nexport class DefaultConfigDirectorClient implements ConfigDirectorClient {\n private logger: ConfigDirectorLogger;\n private telemetryClient: TelemetryClient;\n private configSet: ConfigSet | undefined;\n private handlersMap: Map<string, WatchHandlerWithOptions<any>[]> = new Map();\n private transport: Transport;\n private eventEmitter = new Emitter<ClientEvents>();\n private timeout: number;\n private timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private ready = false;\n private initializing = false;\n private hasReceivedConfigSet = false;\n private readyPromise: Promise<void> | undefined;\n private readyResolve: ((cancelled?: boolean) => void) | undefined;\n private currentContext?: ConfigDirectorContext;\n private connectionMode: ConnectionMode;\n private instanceId: string;\n\n constructor(\n telemetryClient: TelemetryClient,\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n internalClientOptions?: InternalClientOptions,\n ) {\n this.logger = clientOptions?.logger ?? createDefaultLogger();\n this.instanceId = resolveInstanceId(this.logger);\n this.timeout = clientOptions?.connection?.timeout ?? 3_000;\n this.validateSdkKeyPresence(clientSdkKey);\n const urlFactory: UrlFactory = internalClientOptions?.urlFactory ?? defaultUrlFactory;\n const baseUrl = this.parseUrl(clientOptions?.connection?.url, urlFactory) ?? CLIENT_BASE_URL;\n this.connectionMode = clientOptions?.connection?.mode ?? \"streaming\";\n this.telemetryClient = telemetryClient;\n this.transport =\n internalClientOptions?.transport ??\n this.buildTransport(clientSdkKey, sdkOptions, baseUrl, urlFactory, clientOptions, internalClientOptions);\n\n this.transport.on(\"configSetReceived\", (configSet: ConfigSet) => {\n this.hasReceivedConfigSet = true;\n this.readyResolve?.();\n const removedKeys = this.findKeysRemovedBy(configSet);\n if (!this.configSet || configSet.kind == \"full\") {\n this.configSet = configSet;\n } else {\n this.configSet.configs = {\n ...this.configSet.configs,\n ...configSet.configs,\n };\n }\n const keys = Object.keys(configSet.configs);\n this.emit(\"configsUpdated\", { keys, removedKeys });\n this.updateWatchers([...keys, ...removedKeys]);\n this.logger.debug(\"[ConfigDirectorClient] ConfigSet updated from server:\", { keys, removedKeys });\n });\n\n this.transport.on(\"connectionError\", (error: Error) => {\n this.initializing = false;\n this.logger.error(\n \"[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.\",\n error,\n );\n this.emit(\"connectionError\", { error });\n });\n\n this.registerHandler(\"clientReady\", clientOptions?.hooks?.clientReady);\n this.registerHandler(\"configEvaluated\", clientOptions?.hooks?.configEvaluated);\n this.registerHandler(\"configsUpdated\", clientOptions?.hooks?.configsUpdated);\n this.registerHandler(\"contextUpdated\", clientOptions?.hooks?.contextUpdated);\n this.registerHandler(\"connectionError\", clientOptions?.hooks?.connectionError);\n }\n\n private registerHandler<T extends keyof ClientEvents>(\n event: T,\n handler: HookHandler<T> | HookHandler<T>[] | undefined,\n ) {\n if (!handler) {\n return;\n }\n\n const handlers = Array.isArray(handler) ? handler : [handler];\n for (const h of handlers) {\n if (typeof h === \"function\") {\n this.on(event, h);\n }\n }\n }\n\n private resolvePollingIntervalForMode(configuredSeconds: number | undefined): number | undefined {\n if (this.connectionMode !== \"polling\") {\n return undefined;\n }\n const resolved = resolvePollingInterval(configuredSeconds, {\n defaultSeconds: CLIENT_DEFAULT_POLLING_INTERVAL_SECONDS,\n minimumSeconds: CLIENT_MIN_POLLING_INTERVAL_SECONDS,\n });\n if (resolved.warning) {\n this.logger.warn(`[ConfigDirectorClient] ${resolved.warning}`);\n }\n return resolved.seconds;\n }\n\n private buildTransport(\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n baseUrl: UrlLike,\n urlFactory: UrlFactory,\n clientOptions: ConfigDirectorClientOptions | undefined,\n internalClientOptions: InternalClientOptions | undefined,\n ): Transport {\n const transportConstructor = this.getTransportConstructor(this.connectionMode);\n return new transportConstructor({\n instanceId: this.instanceId,\n clientSdkKey,\n baseUrl,\n resolveUrl: urlFactory,\n metaContext: {\n ...clientOptions?.metadata,\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n userAgent: readUserAgent(),\n host: readHost(),\n },\n logger: this.logger,\n fetch: internalClientOptions?.fetch,\n connectionRetryDelay:\n internalClientOptions?.connectionRetryDelay ??\n ((attempt: number) => {\n const seconds = Math.pow(2, Math.min(attempt, MAX_EXPONENTIAL_DELAY));\n return seconds * 1_000;\n }),\n pollingInterval: this.resolvePollingIntervalForMode(clientOptions?.connection?.pollingInterval),\n });\n }\n\n private getTransportConstructor(connectionMode?: ConnectionMode) {\n switch (connectionMode) {\n case \"polling\":\n return PollingTransport;\n default:\n return StreamingTransport;\n }\n }\n\n public async initialize(context?: ConfigDirectorContext) {\n if (!this.hasReceivedConfigSet) {\n this.initializing = true;\n }\n await this.connectToTransport(context, \"initialization\");\n }\n\n public async updateContext(context: ConfigDirectorContext) {\n await this.connectToTransport(context, \"context update\");\n }\n\n public get context(): ConfigDirectorContext | undefined {\n return this.currentContext;\n }\n\n private async connectToTransport(context: ConfigDirectorContext | undefined, caller: ClientConnectAction) {\n try {\n this.ready = false;\n this.readyPromise = new Promise<boolean | undefined>((resolve) => {\n this.readyResolve = resolve;\n }).then((cancelled) => {\n if (cancelled) {\n return;\n }\n this.ready = true;\n this.initializing = false;\n this.emit(\"clientReady\", { action: caller });\n this.logger.debug(\"[ConfigDirectorClient] Received initial payload from the server, client is ready\");\n });\n const startTime = new Date().getTime();\n await this.transport.connect(context ?? {}, this.timeout, caller);\n this.currentContext = context;\n this.telemetryClient\n .updateContext(context)\n .catch((error) =>\n this.logger.warn(\"[ConfigDirectorClient] Telemetry could not update the context: \", error),\n );\n this.emit(\"contextUpdated\", { context });\n\n const elapsedTime = new Date().getTime() - startTime;\n const remainingTimeout = this.timeout - elapsedTime;\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n if (remainingTimeout > 0) {\n await Promise.race([\n this.readyPromise,\n new Promise<void>((resolve) => {\n this.timeoutTimer = setTimeout(() => resolve(), remainingTimeout);\n }),\n ]).finally(() => clearTimeout(this.timeoutTimer));\n }\n\n if (!this.ready) {\n const warningDetails =\n \"The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.\";\n this.logger.warn(\n `[ConfigDirectorClient] Timed out waiting for ${caller} after ${this.timeout}ms. ${warningDetails}`,\n );\n }\n } catch (error) {\n this.logger.error(`[ConfigDirectorClient] An error occurred during ${caller}: `, error);\n }\n }\n\n private findKeysRemovedBy(configSet: ConfigSet): string[] {\n if (!this.configSet || configSet.kind != \"full\") {\n return [];\n }\n return Object.keys(this.configSet.configs).filter((key) => !Object.prototype.hasOwnProperty.call(configSet.configs, key));\n }\n\n private updateWatchers(configKeys: string[]) {\n configKeys.forEach((configKey) => this.updateWatchersForConfig(configKey));\n }\n\n private updateWatchersForConfig(configKey: string) {\n const configState = this.configSet?.configs[configKey];\n this.handlersMap.get(configKey)?.forEach((h) => {\n const value = this.getValueFromConfigState(configKey, configState, h.defaultValue);\n h.handler(value);\n });\n }\n\n public watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>) {\n this.validateDefaultValue(defaultValue);\n\n const handlers = this.handlersMap.get(configKey);\n const handlerWithOptions = { handler: callback, defaultValue, requestedType: typeof defaultValue };\n if (handlers) {\n handlers.push(handlerWithOptions);\n } else {\n this.handlersMap.set(configKey, [handlerWithOptions]);\n }\n\n return () => this.unwatch(configKey, callback);\n }\n\n public unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>) {\n const handlers = this.handlersMap.get(configKey);\n if (!handlers) {\n return;\n }\n\n if (callback) {\n const index = handlers.findIndex((h) => h.handler == callback);\n if (index >= 0) {\n handlers?.splice(index, 1);\n }\n } else {\n handlers.splice(0);\n }\n }\n\n public getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T {\n this.validateDefaultValue(defaultValue);\n\n const configState = this.configSet?.configs[configKey];\n return this.getValueFromConfigState(configKey, configState, defaultValue);\n }\n\n private getValueFromConfigState<T extends ConfigValueType>(\n configKey: string,\n configState: ConfigState | undefined,\n defaultValue: T,\n ): T {\n if (!configState) {\n this.logger.debug(\n `[ConfigDirectorClient] No config state found for '${configKey}', returning default value '${defaultValue}'`,\n );\n const reason = this.isReady ? \"config-state-missing\" : \"client-not-ready\";\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: getRequestedType(defaultValue),\n evaluatedValue: defaultValue,\n usedDefault: true,\n evaluationReason: reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: defaultValue,\n isDefaultValue: true,\n reason,\n context: this.context,\n });\n return defaultValue;\n }\n\n const parseResult = parseConfigValue<T>(configState, defaultValue);\n this.telemetryClient.evaluatedConfig({\n contextId: this.currentContext?.id,\n type: configState.type,\n key: configKey,\n defaultValue: defaultValue,\n requestedType: parseResult.requestedType,\n evaluatedValue: parseResult.parsedValue,\n evaluatedValueId: parseResult.parsedValueId,\n usedDefault: parseResult.usedDefault,\n evaluationReason: parseResult.reason,\n });\n this.dispatchEvaluationEvent({\n key: configKey,\n value: parseResult.parsedValue,\n valueId: parseResult.parsedValueId ?? undefined,\n isDefaultValue: parseResult.usedDefault,\n reason: parseResult.reason,\n context: this.context,\n });\n this.logger.debug(`[ConfigDirectorClient] Evaluated '${configKey}' to '${parseResult.parsedValue}'`);\n return parseResult.parsedValue;\n }\n\n private dispatchEvaluationEvent(event: ConfigEvaluation) {\n setTimeout(() => this.emit(\"configEvaluated\", { evaluation: event }), 0);\n }\n\n private emit<TName extends keyof ClientEvents>(name: TName, payload: ClientEvents[TName]) {\n try {\n this.eventEmitter.emit(name, payload);\n } catch (error) {\n this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${name}'`, error);\n }\n }\n\n private parseUrl(url: string | undefined, urlFactory: UrlFactory): UrlLike | undefined {\n if (!url) {\n return;\n }\n\n try {\n return urlFactory(url);\n } catch (error) {\n throw new ConfigDirectorValidationError(`Invalid base URL '${url}'. Parsing failed: ${error}`);\n }\n }\n\n private validateSdkKeyPresence(sdkKey: string | null | undefined) {\n if (!sdkKey || sdkKey.trim().length == 0) {\n throw new ConfigDirectorValidationError(\n \"No client SDK key was provided, the client cannot be instantiated without a valid client SDK key\",\n );\n }\n }\n\n private validateDefaultValue<T extends ConfigValueType>(defaultValue: T) {\n if (defaultValue === undefined || defaultValue === null) {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config must be defined and non-null.\",\n );\n }\n\n if (typeof defaultValue === \"function\") {\n throw new ConfigDirectorValidationError(\n \"Invalid default value. The default value for a config cannot be a function.\",\n );\n }\n }\n\n public get isReady(): boolean {\n return this.ready;\n }\n\n public get isInitializing(): boolean {\n return this.initializing;\n }\n\n public on<T extends keyof ClientEvents>(eventName: T, handler: (event: ClientEvents[T]) => void): void {\n this.eventEmitter.on(eventName, handler);\n }\n\n public off<T extends keyof ClientEvents>(eventName: T, handler?: (payload: ClientEvents[T]) => void) {\n this.eventEmitter.off(eventName, handler);\n }\n\n public clear() {\n this.logger.debug(\"[ConfigDirectorClient] clear() has been called, removing all observers\");\n this.eventEmitter.clear();\n this.handlersMap.clear();\n }\n\n public unwatchAll() {\n this.handlersMap.clear();\n }\n\n public pauseNetwork(): void {\n this.logger.debug(\"[ConfigDirectorClient] pauseNetwork() called, pausing transport connection\");\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = undefined;\n this.transport.close();\n this.ready = false;\n }\n\n public async resumeNetwork(): Promise<void> {\n await this.connectToTransport(this.currentContext, \"network resume\");\n }\n\n public async close() {\n this.logger.debug(\"[ConfigDirectorClient] close() has been called, closing connection to server\");\n clearTimeout(this.timeoutTimer);\n this.readyResolve?.(true);\n this.telemetryClient\n .close()\n .catch((error) => this.logger.warn(\"[ConfigDirectorClient] Telemetry could not close: \", error));\n this.transport.close();\n this.ready = false;\n this.initializing = false;\n }\n\n public dispose() {\n this.clear();\n this.close();\n }\n}\n","import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n return worker;\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n createDefaultLogger,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory, parseUrl } from \"@shared/url\";\nimport { CLIENT_BASE_URL } from \"@shared/constants\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\nexport const createBrowserClient = (\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n const logger = clientOptions?.logger ?? createDefaultLogger();\n const baseUrl = parseUrl(clientOptions?.connection?.url) ?? CLIENT_BASE_URL;\n const telemetryClient = new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: clientOptions?.metadata?.appName,\n appVersion: clientOptions?.metadata?.appVersion,\n },\n logger: logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n });\n\n return new DefaultConfigDirectorClient(telemetryClient, clientSdkKey, sdkOptions, {\n ...clientOptions,\n logger,\n });\n};\n","import type {\n EvaluationContext,\n JsonValue,\n Paradigm,\n Provider,\n ProviderMetadata,\n ResolutionDetails,\n} from \"@openfeature/web-sdk\";\nimport { OpenFeatureEventEmitter, ProviderEvents, ProviderNotReadyError } from \"@openfeature/web-sdk\";\nimport type {\n ConfigDirectorClient,\n ConfigDirectorClientOptions,\n ConfigDirectorContext,\n ConfigValueType,\n} from \"@js-client-core/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\n\nexport class ConfigDirectorProvider implements Provider {\n private readonly client: ConfigDirectorClient;\n private awaitingRecovery = false;\n\n readonly metadata: ProviderMetadata = {\n name: ConfigDirectorProvider.name,\n };\n readonly runsOn: Paradigm = \"client\";\n readonly events = new OpenFeatureEventEmitter();\n\n public constructor(clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions) {\n this.client = createBrowserClient(\n clientSdkKey,\n {\n sdkName: \"js-openfeature-web-provider\",\n sdkVersion: \"__VERSION__\",\n },\n clientOptions,\n );\n this.client.on(\"clientReady\", () => {\n if (!this.awaitingRecovery) {\n return;\n }\n this.awaitingRecovery = false;\n this.events.emit(ProviderEvents.Ready);\n });\n this.client.on(\"configsUpdated\", ({ keys, removedKeys }) => {\n this.events.emit(ProviderEvents.ConfigurationChanged, { flagsChanged: [...keys, ...removedKeys] });\n });\n }\n\n async initialize(context: EvaluationContext) {\n this.awaitingRecovery = false;\n await this.client.initialize(this.mapContext(context));\n this.requireReady(\n \"ConfigDirector did not become ready during initialization. Flags resolve to their default values \" +\n \"until the connection succeeds.\",\n );\n }\n\n async onContextChange?(_oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {\n this.awaitingRecovery = false;\n await this.client.updateContext(this.mapContext(newContext));\n this.requireReady(\n \"ConfigDirector did not become ready after the context changed. Flags resolve against the previous \" +\n \"context until the connection succeeds.\",\n );\n }\n\n resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number> {\n return this.evaluate(flagKey, defaultValue);\n }\n\n resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T> {\n return this.evaluate(flagKey, defaultValue as ConfigValueType) as ResolutionDetails<T>;\n }\n\n onClose?(): Promise<void> {\n this.client.dispose();\n return Promise.resolve();\n }\n\n private requireReady(message: string) {\n if (this.client.isReady) {\n return;\n }\n this.awaitingRecovery = true;\n throw new ProviderNotReadyError(message);\n }\n\n private evaluate<T extends ConfigValueType>(configKey: string, defaultValue: T): ResolutionDetails<T> {\n const value = this.client.getValue(configKey, defaultValue);\n return {\n value,\n };\n }\n\n private mapContext(openFeatureContext: EvaluationContext): ConfigDirectorContext {\n if (!openFeatureContext) {\n return {};\n }\n\n const id = (openFeatureContext.targetingKey ?? openFeatureContext[\"id\"])?.toString();\n const name = openFeatureContext[\"name\"]?.toString();\n const traits = (openFeatureContext?.[\"traits\"] as Record<string, unknown>) || {};\n const hasTraits = typeof traits === \"object\" && Object.keys(traits).length > 0;\n const anonymousProp = openFeatureContext[\"anonymous\"];\n\n return {\n id,\n name,\n traits: hasTraits ? traits : undefined,\n anonymous: typeof anonymousProp === \"boolean\" ? anonymousProp : undefined,\n };\n }\n}\n"],"mappings":"8GAaA,IAAa,EAAb,KAAiG,eAC/F,KAAQ,WAAsE,IAAI,IAElF,GAAsC,EAAa,EAAwC,CACzF,IAAM,EAAW,KAAK,WAAW,IAAI,EAAK,CACtC,EACF,EAAS,KAAK,EAAQ,CAEtB,KAAK,WAAW,IAAI,EAAM,CAAC,EAAQ,CAAC,CAI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BAAmB,GACxB,MAAM,EAAK,OAAO,cAAc,EAAK,WAAW,EAAW,CAAC,CAC5D,EAAK,aACH,2IAED,CAGH,yBAAyB,EAAiB,EAAmD,CAC3F,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAAwB,EAAiB,EAAiD,CACxF,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAAwB,EAAiB,EAAiD,CACxF,OAAO,KAAK,SAAS,EAAS,EAAa,CAG7C,wBAA6C,EAAiB,EAAuC,CACnG,OAAO,KAAK,SAAS,EAAS,EAAgC,CAGhE,SAA0B,CAExB,OADA,KAAK,OAAO,SAAS,CACd,QAAQ,SAAS,CAG1B,aAAqB,EAAiB,CAChC,SAAK,OAAO,QAIhB,KADA,MAAK,iBAAmB,GAClB,IAAI,EAAsB,EAAQ,CAG1C,SAA4C,EAAmB,EAAuC,CAEpG,MAAO,CACL,MAFY,KAAK,OAAO,SAAS,EAAW,EAAa,CAG1D,CAGH,WAAmB,EAA8D,WAC/E,GAAI,CAAC,EACH,MAAO,EAAE,CAGX,IAAM,GAAA,GAAA,EAAM,EAAmB,eAAA,KAAgB,EAAmB,GAAnC,IAAmC,KAAA,IAAA,GAAA,EAAQ,UAAU,CAC9E,GAAA,EAAO,EAAmB,OAAA,KAAA,IAAA,GAAA,EAAS,UAAU,CAC7C,GAAA,GAAA,KAAA,IAAA,GAAU,EAAqB,SAAyC,EAAE,CAC1E,EAAY,OAAO,GAAW,UAAY,OAAO,KAAK,EAAO,CAAC,OAAS,EACvE,EAAgB,EAAmB,UAEzC,MAAO,CACL,KACA,OACA,OAAQ,EAAY,EAAS,IAAA,GAC7B,UAAW,OAAO,GAAkB,UAAY,EAAgB,IAAA,GACjE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@configdirector/openfeature-web-provider",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.1",
|
|
4
4
|
"description": "OpenFeature web provider for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "ConfigDirector",
|