@configdirector/openfeature-web-provider 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/configdirector-openfeature-web-provider.cjs +2 -2
- package/dist/configdirector-openfeature-web-provider.d.cts +92 -35
- package/dist/configdirector-openfeature-web-provider.d.cts.map +1 -1
- package/dist/configdirector-openfeature-web-provider.d.mts +92 -35
- package/dist/configdirector-openfeature-web-provider.d.mts.map +1 -1
- package/dist/configdirector-openfeature-web-provider.mjs +3 -3
- package/dist/configdirector-openfeature-web-provider.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@openfeature/web-sdk`);var t=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},n=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},c=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@openfeature/web-sdk`);var t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}};const i=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 a=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},o=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new a,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{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,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)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(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),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.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,this.forwardInvalidContextSubmissions(e),e}}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}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)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:i({value:e.defaultValue,type:e.type}),evaluatedValue:i({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?.()}},s=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},c=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},d=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
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 ee=e=>new u(e);var d=class{constructor(e){this.options=e,this.eventEmitter=new t,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){let n=++this.connectionGeneration,r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;this.eventSource&&this.close();let i=new Promise((t,n)=>{this.eventSource=ee({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:r.instanceId,ephemeral:r.ephemeral}),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([i,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.connectionGeneration++,this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const f=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},p=e=>e===`number`||e===`bigint`,m=new Set([`boolean`,`integer`,`float`]),h=(e,t)=>{let n=e.value,r=f(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return b(n,t,r,e.valueId);if(typeof t==`string`)return m.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=g(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(p(typeof t)&&e.type===`integer`){let i=_(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(p(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){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`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},g=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},_=e=>{let t=y(e);return t==null?void 0:Math.trunc(t)},v=e=>y(e),y=e=>{if(!e||!te(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},te=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},b=(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 x(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`}}},x=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},S={off:-1,error:0,warn:1,info:2,debug:3},C=()=>{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 w=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=C()}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){S[this.level]>=S[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},T=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const E=(e,t)=>new w(e??`warn`,t??new T),D=(e,t)=>new URL(e,t?.toString()),O=e=>{if(e)try{return new URL(e)}catch(t){throw new r(`Invalid URL '${e}'. Parsing failed: ${t}`)}},k=(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.`},A=()=>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)}),j=`configdirector-sdk:instance-id`,M=1e3,N=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,P=(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},F=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=P(n,2166136261);return P(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},I=()=>{try{return globalThis.localStorage??void 0}catch{return}},L=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||!N.test(n)?!1:i===F(n,r)},R=async(e,t)=>{let n;try{n=await e.getItem(j)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch{return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!L(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},z=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:F(t,r)};try{return await e.setItem(j,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},ne=async(e,t,n,r)=>{let i=await R(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await z(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},B=(e,t=I())=>{let n=A();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${M}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},M)});return Promise.race([ne(t,n,r,e),a]).finally(()=>clearTimeout(i))};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.connectionGeneration=0,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){let n=++this.connectionGeneration;this.clearPollingInterval();let r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;try{await this.fetchConfigs(e,t,r)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t,r).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=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:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.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),q=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,J=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!q(t))return!1;return!0},Y=e=>e==null||typeof e==`string`&&J(e),X=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},Z=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},re=e=>{let t=e?.kind;return Y(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:Z(X(t),128)}};var ie=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??E(),this.clientSession=B(this.logger,a?.instanceIdStorage),this.timeout=i?.connection?.timeout??3e3,this.validateSdkKeyPresence(n);let o=a?.urlFactory??D,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=k(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))({clientSession:this.clientSession,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 d}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.submitContext(e,`initialization`)}async updateContext(e){await this.submitContext(e,`context update`)}async submitContext(e,t){await this.connectToTransport(this.contextToConnectWith(e,t),t)}contextToConnectWith(e,t){let n=re(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; connecting as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){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:f(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=h(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 Q=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 ae=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},oe=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new ae,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{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,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)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(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),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.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,this.forwardInvalidContextSubmissions(e),e}}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}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)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({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 $=(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=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,ce.encode(e?.toString()??``));return $(new Uint8Array(t,0,16),se)},ue=(e,t,n)=>{let r=n?.logger??E(),i=O(n?.connection?.url)??`https://client-sdk-api.configdirector.com`;return new ie(new oe({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n?.metadata?.appName,appVersion:n?.metadata?.appVersion},logger:r,baseUrl:i,urlFactory:D,valueIdGenerator:le}),e,t,{...n,logger:r})};var de=class t{constructor(n,r){this.awaitingRecovery=!1,this.metadata={name:t.name},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=ue(n,{sdkName:`js-openfeature-web-provider`,sdkVersion:`1.7.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.kind,r=e.name?.toString(),i=e?.traits||{},a=typeof i==`object`&&Object.keys(i).length>0,o=e.anonymous;return{id:t,kind:n,name:r,traits:a?i:void 0,anonymous:typeof o==`boolean`?o:void 0}}};exports.ConfigDirectorProvider=de;
|
|
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 f=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var te=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=f.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===f.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=f.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 ee(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new d({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 c(`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=f.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=f.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new u(`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 l(`${n} must be a function`);return e}};const p=e=>new te(e);var m=class{constructor(e){this.options=e,this.eventEmitter=new s,this.connectionGeneration=0,this.options=e,this.logger=e.logger,this.url=e.resolveUrl(`client/sse/v1`,e.baseUrl)}async connect(e,t){let n=++this.connectionGeneration,r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;this.eventSource&&this.close();let i=new Promise((t,n)=>{this.eventSource=p({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:r.instanceId,ephemeral:r.ephemeral}),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([i,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,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.connectionGeneration++,this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const h=(e,t)=>{if(e.trim().length==0)throw new n(`Invalid config key. The key of a value cannot be empty.`);return g(e,t)},g=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return _(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return y(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new n(`Invalid value for '${e}': ${x(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},_=(e,t)=>{if(!Number.isFinite(t))throw new n(`Invalid value for '${e}': ${x(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new n(`Invalid value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:v(t)}},v=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},y=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw b(e,n,`${x(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>y(e,t,`${n}[${r}]`));return}if(ne(t)){for(let[r,i]of Object.entries(t))y(e,i,n?`${n}.${r}`:r);return}throw b(e,n,`${x(t)} cannot be encoded as JSON`)}},b=(e,t,r)=>new n(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),ne=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},x=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),S=(e,t,n,r)=>{let i=h(t,n);return{id:e,key:t,type:i.type,value:i.value,valueId:r}},C={environmentId:`offline`,projectId:`offline`};var w=class{constructor(e){this.source=e,this.emitter=new s,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t)}async connect(){let e=T(this.source);return this.emitter.emit(`configSetReceived`,{...C,kind:`full`,configs:e}),this}clear(){this.emitter.clear()}close(){}dispose(){this.clear()}};const T=e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return E(e.values);case`rejected`:throw new r(e.message)}},E=e=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,S(`offline:${e}`,e,t,void 0)]))}catch(e){throw e instanceof n?new r(`The offline values could not be loaded. ${e.message}`):e}},D=(e,t,r)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:k(t)};let i=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`);return t?.values===void 0?{kind:`connect`,mode:i,clientSdkKey:e,baseUrl:O(t?.url,r)}:{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection option 'values' applies only when the connection mode is 'offline', but the mode is '${i}'.`}}},O=(e,t)=>{if(!e)return`https://client-sdk-api.configdirector.com`;try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},k=e=>e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values},A=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},j=e=>e===`number`||e===`bigint`,M=new Set([`boolean`,`integer`,`float`]),N=(e,t)=>{let n=e.value,r=A(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return z(n,t,r,e.valueId);if(typeof t==`string`)return M.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=P(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(j(typeof t)&&e.type===`integer`){let i=F(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(j(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=I(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`}},P=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},F=e=>{let t=L(e);return t==null?void 0:Math.trunc(t)},I=e=>L(e),L=e=>{if(!e||!R(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},R=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},z=(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 B(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`}}},B=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},V={off:-1,error:0,warn:1,info:2,debug:3},H=()=>{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 U=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=H()}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){V[this.level]>=V[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},W=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const G=(e,t)=>new U(e??`warn`,t??new W),K={updateContext:async()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>{},close:async()=>{}},q=(e,t)=>new URL(e,t?.toString()),re=(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.`},J=()=>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)}),Y=`configdirector-sdk:instance-id`,X=1e3,ie=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Z=(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},Q=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=Z(n,2166136261);return Z(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},ae=()=>{try{return globalThis.localStorage??void 0}catch{return}},oe=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||!ie.test(n)?!1:i===Q(n,r)},se=async(e,t)=>{let n;try{n=await e.getItem(Y)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch{return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!oe(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},ce=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:Q(t,r)};try{return await e.setItem(Y,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},le=async(e,t,n,r)=>{let i=await se(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await ce(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},ue=(e,t=ae())=>{let n=J();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${X}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},X)});return Promise.race([le(t,n,r,e),a]).finally(()=>clearTimeout(i))};var de=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 t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}`}${(n?.trim()?.length??0)>0?` (${n})`:``}. 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 fe=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 pe=class extends de{constructor(e){super(),this.options=e,this.eventEmitter=new s,this.connectionGeneration=0,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){let n=++this.connectionGeneration;this.clearPollingInterval();let r=await this.options.clientSession;if(n!==this.connectionGeneration)return this;try{await this.fetchConfigs(e,t,r)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t,r).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await fe(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.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 $=e=>{try{return e(globalThis)}catch{return}},me=()=>$(e=>e.navigator?.userAgent),he=()=>$(e=>e.location?.host),ge=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,_e=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ge(t))return!1;return!0},ve=e=>e==null||typeof e==`string`&&_e(e),ye=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},be=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},xe=e=>{let t=e?.kind;return ve(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:be(ye(t),128)}};var Se=class e{static from(t,n,r,i){return typeof n==`object`?new e(t,void 0,r,n):new e(t,n,r,i)}constructor(e,t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new s,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=r?.logger??G(),this.clientSession=ue(this.logger,i?.instanceIdStorage),this.timeout=r?.connection?.timeout??3e3;let a=i?.urlFactory??q;this.connectionPlan=D(t,r?.connection,a),this.telemetryClient=this.buildTelemetryClient(e,r),this.transport=i?.transport??this.buildTransport(n,r,a,i),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`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,r?.hooks?.contextUpdated),this.registerHandler(`connectionError`,r?.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)}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=re(t,{defaultSeconds:60,minimumSeconds:30});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return K;case`connect`:return e({clientSdkKey:n.clientSdkKey,baseUrl:n.baseUrl,logger:this.logger,metadata:t?.metadata})}}buildTransport(e,t,n,r){let i=this.connectionPlan;switch(i.kind){case`stay-offline`:return new w(i.source);case`connect`:return new(this.getTransportConstructor(i.mode))({clientSession:this.clientSession,clientSdkKey:i.clientSdkKey,baseUrl:i.baseUrl,resolveUrl:n,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion,userAgent:me(),host:he()},logger:this.logger,fetch:r?.fetch,connectionRetryDelay:r?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.pollingIntervalFor(i.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return pe;case`streaming`:return m}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.submitContext(e,`initialization`)}async updateContext(e){switch(this.connectionPlan.kind){case`connect`:await this.submitContext(e,`context update`);return;case`stay-offline`:this.storeContext(this.admittedContextFor(e,`context update`));return}}storeContext(e){this.currentContext=e,this.emit(`contextUpdated`,{context:e})}async submitContext(e,t){await this.connectToTransport(this.admittedContextFor(e,t),t)}admittedContextFor(e,t){let n=xe(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; continuing as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){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. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof r)throw this.initializing=!1,e;this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`;case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){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:A(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=N(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)}}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1;return}}async resumeNetwork(){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:await this.connectToTransport(this.currentContext,`network resume`);return}}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 Ce=(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`)},we=Math.ceil(128/Math.log2(62)),Te=new TextEncoder,Ee=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,Te.encode(e?.toString()??``));return Ce(new Uint8Array(t,0,16),we)},De=(e,t,n)=>Se.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i})=>new o({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:q,valueIdGenerator:Ee}),e,t,n),Oe={sdkName:`js-openfeature-web-provider`,sdkVersion:`1.8.0`};var ke=class t{constructor(n,r){this.awaitingRecovery=!1,this.metadata={name:t.name},this.runsOn=`client`,this.events=new e.OpenFeatureEventEmitter,this.client=De(n,Oe,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.kind,r=e.name?.toString(),i=e?.traits||{},a=typeof i==`object`&&Object.keys(i).length>0,o=e.anonymous;return{id:t,kind:n,name:r,traits:a?i:void 0,anonymous:typeof o==`boolean`?o:void 0}}};exports.ConfigDirectorInitializationError=r,exports.ConfigDirectorProvider=ke;
|
|
@@ -90,9 +90,76 @@ type ConfigDirectorMetaContext = {
|
|
|
90
90
|
appVersion?: string;
|
|
91
91
|
appName?: string;
|
|
92
92
|
};
|
|
93
|
-
type ConnectionMode = "streaming" | "polling";
|
|
93
|
+
type ConnectionMode = "streaming" | "polling" | "offline";
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region ../shared/src/native-values.d.ts
|
|
96
|
+
type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
|
|
97
|
+
[key: string]: NativeJsonValue;
|
|
98
|
+
};
|
|
99
|
+
type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
100
|
+
[key: string]: NativeJsonValue;
|
|
101
|
+
};
|
|
102
|
+
type NativeValues = Record<string, NativeValue>;
|
|
94
103
|
//#endregion
|
|
95
104
|
//#region ../js-client-core/src/types.d.ts
|
|
105
|
+
/**
|
|
106
|
+
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
107
|
+
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
108
|
+
* or array (`json`).
|
|
109
|
+
*/
|
|
110
|
+
type OfflineValue = NativeValue;
|
|
111
|
+
/**
|
|
112
|
+
* The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
|
|
113
|
+
* value's config type is decided. Every context receives the same value.
|
|
114
|
+
*/
|
|
115
|
+
type OfflineValues = NativeValues;
|
|
116
|
+
/**
|
|
117
|
+
* Connection options of the {@link ConfigDirectorClient}
|
|
118
|
+
*/
|
|
119
|
+
type ConnectionOptions = {
|
|
120
|
+
/**
|
|
121
|
+
* The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
|
|
122
|
+
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
123
|
+
* config state is updated on the ConfigDirector dashboard.
|
|
124
|
+
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
125
|
+
* initialization, and additional requests on a `pollingInterval`.
|
|
126
|
+
* When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
|
|
127
|
+
* the values given in {@link values} to every context, or the in-code default values when none
|
|
128
|
+
* are given. No SDK key is needed.
|
|
129
|
+
*
|
|
130
|
+
* Defaults to `streaming`
|
|
131
|
+
*/
|
|
132
|
+
mode?: ConnectionMode;
|
|
133
|
+
/**
|
|
134
|
+
* The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
|
|
135
|
+
* `initialize` reject with a `ConfigDirectorInitializationError`.
|
|
136
|
+
*
|
|
137
|
+
* Can be given only in `offline` mode; otherwise `initialize` rejects.
|
|
138
|
+
*/
|
|
139
|
+
values?: OfflineValues;
|
|
140
|
+
/**
|
|
141
|
+
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
142
|
+
* effect in the other modes.
|
|
143
|
+
*
|
|
144
|
+
* Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
|
|
145
|
+
* minimum and a warning is logged.
|
|
146
|
+
*/
|
|
147
|
+
pollingInterval?: number;
|
|
148
|
+
/**
|
|
149
|
+
* The timeout, in _milliseconds_, to be used in initialization and when updating the context.
|
|
150
|
+
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
151
|
+
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
152
|
+
* If streaming is disabled, if the operation times out, it will not be retried. This option has
|
|
153
|
+
* no effect in `offline` mode.
|
|
154
|
+
*/
|
|
155
|
+
timeout?: number;
|
|
156
|
+
/**
|
|
157
|
+
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
158
|
+
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
159
|
+
* a proxy for the client SDK. This option has no effect in `offline` mode.
|
|
160
|
+
*/
|
|
161
|
+
url?: string;
|
|
162
|
+
};
|
|
96
163
|
/**
|
|
97
164
|
* Configuration options for the {@link ConfigDirectorClient}
|
|
98
165
|
*/
|
|
@@ -104,39 +171,7 @@ type ConfigDirectorClientOptions = {
|
|
|
104
171
|
/**
|
|
105
172
|
* Connection options
|
|
106
173
|
*/
|
|
107
|
-
connection?:
|
|
108
|
-
/**
|
|
109
|
-
* The connection mode to be used, one of `streaming` (default) or `polling`.
|
|
110
|
-
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
111
|
-
* config state is updated on the ConfigDirector dashboard.
|
|
112
|
-
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
113
|
-
* initialization, and additional requests on a `pollingInterval`.
|
|
114
|
-
*
|
|
115
|
-
* Defaults to `streaming`
|
|
116
|
-
*/
|
|
117
|
-
mode?: ConnectionMode;
|
|
118
|
-
/**
|
|
119
|
-
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
120
|
-
* effect when the `mode` is set to `streaming`.
|
|
121
|
-
*
|
|
122
|
-
* Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
|
|
123
|
-
* minimum and a warning is logged.
|
|
124
|
-
*/
|
|
125
|
-
pollingInterval?: number;
|
|
126
|
-
/**
|
|
127
|
-
* The timeout, in _milliseconds_, to be used in initialization and when updating the context.
|
|
128
|
-
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
129
|
-
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
130
|
-
* If streaming is disabled, if the operation times out, it will not be retried.
|
|
131
|
-
*/
|
|
132
|
-
timeout?: number;
|
|
133
|
-
/**
|
|
134
|
-
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
135
|
-
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
136
|
-
* a proxy for the client SDK.
|
|
137
|
-
*/
|
|
138
|
-
url?: string;
|
|
139
|
-
};
|
|
174
|
+
connection?: ConnectionOptions;
|
|
140
175
|
/**
|
|
141
176
|
* A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
|
|
142
177
|
* logger set to 'warn' level.
|
|
@@ -168,6 +203,14 @@ type ConfigDirectorClientOptions = {
|
|
|
168
203
|
*/
|
|
169
204
|
hooks?: ClientHooks;
|
|
170
205
|
};
|
|
206
|
+
/**
|
|
207
|
+
* The options of a client created without a client SDK key: the connection mode is `offline`.
|
|
208
|
+
*/
|
|
209
|
+
type OfflineClientOptions = ConfigDirectorClientOptions & {
|
|
210
|
+
connection: ConnectionOptions & {
|
|
211
|
+
mode: "offline";
|
|
212
|
+
};
|
|
213
|
+
};
|
|
171
214
|
type ClientHooks = {
|
|
172
215
|
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
173
216
|
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
@@ -315,6 +358,12 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
|
315
358
|
dispose(): void;
|
|
316
359
|
}
|
|
317
360
|
//#endregion
|
|
361
|
+
//#region ../shared/src/errors.d.ts
|
|
362
|
+
declare class ConfigDirectorInitializationError extends Error {
|
|
363
|
+
readonly name: string;
|
|
364
|
+
constructor(message: string);
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
318
367
|
//#region src/ConfigDirectorProvider.d.ts
|
|
319
368
|
declare class ConfigDirectorProvider implements Provider {
|
|
320
369
|
private readonly client;
|
|
@@ -322,7 +371,15 @@ declare class ConfigDirectorProvider implements Provider {
|
|
|
322
371
|
readonly metadata: ProviderMetadata;
|
|
323
372
|
readonly runsOn: Paradigm;
|
|
324
373
|
readonly events: OpenFeatureEventEmitter;
|
|
374
|
+
/**
|
|
375
|
+
* Creates a provider connected to ConfigDirector with the given client SDK key.
|
|
376
|
+
*/
|
|
325
377
|
constructor(clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions);
|
|
378
|
+
/**
|
|
379
|
+
* Creates a provider in `offline` mode, which needs no client SDK key: it never connects to
|
|
380
|
+
* ConfigDirector and serves `connection.values` to every evaluation.
|
|
381
|
+
*/
|
|
382
|
+
constructor(clientOptions: OfflineClientOptions);
|
|
326
383
|
initialize(context: EvaluationContext): Promise<void>;
|
|
327
384
|
onContextChange?(_oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void>;
|
|
328
385
|
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean>;
|
|
@@ -335,5 +392,5 @@ declare class ConfigDirectorProvider implements Provider {
|
|
|
335
392
|
private mapContext;
|
|
336
393
|
}
|
|
337
394
|
//#endregion
|
|
338
|
-
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorProvider, type ConfigValueType };
|
|
395
|
+
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorProvider, type ConfigValueType, type OfflineClientOptions, type OfflineValue, type OfflineValues };
|
|
339
396
|
//# sourceMappingURL=configdirector-openfeature-web-provider.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-openfeature-web-provider.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../js-client-core/src/types.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED3D4D;;;;;;;;ECoEtE,EAAA;EDrEuB;;;;;;;;;;;ECkFvB,IAAA;EDjF8D;;;;ECuF9D,IAAA;EDtFK;;;;EC4FL,MAAA;IAAA,CAAY,GAAA;EAAA;;;;AAxFd;;;;EAiGE,SAAA;AAAA;;;;;KAOU,yBAAA;EACV,UAAA;EACA,OAAA;AAAA;AAAA,KAGU,cAAA
|
|
1
|
+
{"version":3,"file":"configdirector-openfeature-web-provider.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":"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"}
|
|
@@ -90,9 +90,76 @@ type ConfigDirectorMetaContext = {
|
|
|
90
90
|
appVersion?: string;
|
|
91
91
|
appName?: string;
|
|
92
92
|
};
|
|
93
|
-
type ConnectionMode = "streaming" | "polling";
|
|
93
|
+
type ConnectionMode = "streaming" | "polling" | "offline";
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region ../shared/src/native-values.d.ts
|
|
96
|
+
type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
|
|
97
|
+
[key: string]: NativeJsonValue;
|
|
98
|
+
};
|
|
99
|
+
type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
100
|
+
[key: string]: NativeJsonValue;
|
|
101
|
+
};
|
|
102
|
+
type NativeValues = Record<string, NativeValue>;
|
|
94
103
|
//#endregion
|
|
95
104
|
//#region ../js-client-core/src/types.d.ts
|
|
105
|
+
/**
|
|
106
|
+
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
107
|
+
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
108
|
+
* or array (`json`).
|
|
109
|
+
*/
|
|
110
|
+
type OfflineValue = NativeValue;
|
|
111
|
+
/**
|
|
112
|
+
* The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
|
|
113
|
+
* value's config type is decided. Every context receives the same value.
|
|
114
|
+
*/
|
|
115
|
+
type OfflineValues = NativeValues;
|
|
116
|
+
/**
|
|
117
|
+
* Connection options of the {@link ConfigDirectorClient}
|
|
118
|
+
*/
|
|
119
|
+
type ConnectionOptions = {
|
|
120
|
+
/**
|
|
121
|
+
* The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
|
|
122
|
+
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
123
|
+
* config state is updated on the ConfigDirector dashboard.
|
|
124
|
+
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
125
|
+
* initialization, and additional requests on a `pollingInterval`.
|
|
126
|
+
* When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
|
|
127
|
+
* the values given in {@link values} to every context, or the in-code default values when none
|
|
128
|
+
* are given. No SDK key is needed.
|
|
129
|
+
*
|
|
130
|
+
* Defaults to `streaming`
|
|
131
|
+
*/
|
|
132
|
+
mode?: ConnectionMode;
|
|
133
|
+
/**
|
|
134
|
+
* The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
|
|
135
|
+
* `initialize` reject with a `ConfigDirectorInitializationError`.
|
|
136
|
+
*
|
|
137
|
+
* Can be given only in `offline` mode; otherwise `initialize` rejects.
|
|
138
|
+
*/
|
|
139
|
+
values?: OfflineValues;
|
|
140
|
+
/**
|
|
141
|
+
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
142
|
+
* effect in the other modes.
|
|
143
|
+
*
|
|
144
|
+
* Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
|
|
145
|
+
* minimum and a warning is logged.
|
|
146
|
+
*/
|
|
147
|
+
pollingInterval?: number;
|
|
148
|
+
/**
|
|
149
|
+
* The timeout, in _milliseconds_, to be used in initialization and when updating the context.
|
|
150
|
+
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
151
|
+
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
152
|
+
* If streaming is disabled, if the operation times out, it will not be retried. This option has
|
|
153
|
+
* no effect in `offline` mode.
|
|
154
|
+
*/
|
|
155
|
+
timeout?: number;
|
|
156
|
+
/**
|
|
157
|
+
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
158
|
+
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
159
|
+
* a proxy for the client SDK. This option has no effect in `offline` mode.
|
|
160
|
+
*/
|
|
161
|
+
url?: string;
|
|
162
|
+
};
|
|
96
163
|
/**
|
|
97
164
|
* Configuration options for the {@link ConfigDirectorClient}
|
|
98
165
|
*/
|
|
@@ -104,39 +171,7 @@ type ConfigDirectorClientOptions = {
|
|
|
104
171
|
/**
|
|
105
172
|
* Connection options
|
|
106
173
|
*/
|
|
107
|
-
connection?:
|
|
108
|
-
/**
|
|
109
|
-
* The connection mode to be used, one of `streaming` (default) or `polling`.
|
|
110
|
-
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
111
|
-
* config state is updated on the ConfigDirector dashboard.
|
|
112
|
-
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
113
|
-
* initialization, and additional requests on a `pollingInterval`.
|
|
114
|
-
*
|
|
115
|
-
* Defaults to `streaming`
|
|
116
|
-
*/
|
|
117
|
-
mode?: ConnectionMode;
|
|
118
|
-
/**
|
|
119
|
-
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
120
|
-
* effect when the `mode` is set to `streaming`.
|
|
121
|
-
*
|
|
122
|
-
* Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
|
|
123
|
-
* minimum and a warning is logged.
|
|
124
|
-
*/
|
|
125
|
-
pollingInterval?: number;
|
|
126
|
-
/**
|
|
127
|
-
* The timeout, in _milliseconds_, to be used in initialization and when updating the context.
|
|
128
|
-
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
129
|
-
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
130
|
-
* If streaming is disabled, if the operation times out, it will not be retried.
|
|
131
|
-
*/
|
|
132
|
-
timeout?: number;
|
|
133
|
-
/**
|
|
134
|
-
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
135
|
-
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
136
|
-
* a proxy for the client SDK.
|
|
137
|
-
*/
|
|
138
|
-
url?: string;
|
|
139
|
-
};
|
|
174
|
+
connection?: ConnectionOptions;
|
|
140
175
|
/**
|
|
141
176
|
* A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
|
|
142
177
|
* logger set to 'warn' level.
|
|
@@ -168,6 +203,14 @@ type ConfigDirectorClientOptions = {
|
|
|
168
203
|
*/
|
|
169
204
|
hooks?: ClientHooks;
|
|
170
205
|
};
|
|
206
|
+
/**
|
|
207
|
+
* The options of a client created without a client SDK key: the connection mode is `offline`.
|
|
208
|
+
*/
|
|
209
|
+
type OfflineClientOptions = ConfigDirectorClientOptions & {
|
|
210
|
+
connection: ConnectionOptions & {
|
|
211
|
+
mode: "offline";
|
|
212
|
+
};
|
|
213
|
+
};
|
|
171
214
|
type ClientHooks = {
|
|
172
215
|
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
173
216
|
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
@@ -315,6 +358,12 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
|
315
358
|
dispose(): void;
|
|
316
359
|
}
|
|
317
360
|
//#endregion
|
|
361
|
+
//#region ../shared/src/errors.d.ts
|
|
362
|
+
declare class ConfigDirectorInitializationError extends Error {
|
|
363
|
+
readonly name: string;
|
|
364
|
+
constructor(message: string);
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
318
367
|
//#region src/ConfigDirectorProvider.d.ts
|
|
319
368
|
declare class ConfigDirectorProvider implements Provider {
|
|
320
369
|
private readonly client;
|
|
@@ -322,7 +371,15 @@ declare class ConfigDirectorProvider implements Provider {
|
|
|
322
371
|
readonly metadata: ProviderMetadata;
|
|
323
372
|
readonly runsOn: Paradigm;
|
|
324
373
|
readonly events: OpenFeatureEventEmitter;
|
|
374
|
+
/**
|
|
375
|
+
* Creates a provider connected to ConfigDirector with the given client SDK key.
|
|
376
|
+
*/
|
|
325
377
|
constructor(clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions);
|
|
378
|
+
/**
|
|
379
|
+
* Creates a provider in `offline` mode, which needs no client SDK key: it never connects to
|
|
380
|
+
* ConfigDirector and serves `connection.values` to every evaluation.
|
|
381
|
+
*/
|
|
382
|
+
constructor(clientOptions: OfflineClientOptions);
|
|
326
383
|
initialize(context: EvaluationContext): Promise<void>;
|
|
327
384
|
onContextChange?(_oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void>;
|
|
328
385
|
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean>;
|
|
@@ -335,5 +392,5 @@ declare class ConfigDirectorProvider implements Provider {
|
|
|
335
392
|
private mapContext;
|
|
336
393
|
}
|
|
337
394
|
//#endregion
|
|
338
|
-
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorProvider, type ConfigValueType };
|
|
395
|
+
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, ConfigDirectorProvider, type ConfigValueType, type OfflineClientOptions, type OfflineValue, type OfflineValues };
|
|
339
396
|
//# sourceMappingURL=configdirector-openfeature-web-provider.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-openfeature-web-provider.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../js-client-core/src/types.ts","../src/ConfigDirectorProvider.ts"],"mappings":";;;KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED3D4D;;;;;;;;ECoEtE,EAAA;EDrEuB;;;;;;;;;;;ECkFvB,IAAA;EDjF8D;;;;ECuF9D,IAAA;EDtFK;;;;EC4FL,MAAA;IAAA,CAAY,GAAA;EAAA;;;;AAxFd;;;;EAiGE,SAAA;AAAA;;;;;KAOU,yBAAA;EACV,UAAA;EACA,OAAA;AAAA;AAAA,KAGU,cAAA
|
|
1
|
+
{"version":3,"file":"configdirector-openfeature-web-provider.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts","../src/ConfigDirectorProvider.ts"],"mappings":"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"}
|