@configdirector/server-sdk 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,5 +2,5 @@ import e,{EventEmitter as t}from"node:events";import{createHash as n,randomUUID
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 f=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var ae=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 te(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new ie({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 ee(`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 re(`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 ne(`${n} must be a function`);return e}};const oe=e=>new ae(e),p=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}},m=9e4;var h=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=oe({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),m);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||p(m,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=r(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new l(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},se=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 l(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new l(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new l(`Failed to parse the response from the server: ${e}`):new l(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new l(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}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()}},ce=class extends se{constructor(e){super(),this.options=e,this.eventEmitter=new t,this._sessionId=r(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await p(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,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){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const le=(e,t)=>{if(e.trim().length==0)throw new u(`Invalid config key. The key of a value cannot be empty.`);return ue(e,t)},ue=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return de(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return g(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new u(`Invalid value for '${e}': ${v(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},de=(e,t)=>{if(!Number.isFinite(t))throw new u(`Invalid value for '${e}': ${v(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new u(`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:fe(t)}},fe=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}`},g=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw _(e,n,`${v(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>g(e,t,`${n}[${r}]`));return}if(pe(t)){for(let[r,i]of Object.entries(t))g(e,i,n?`${n}.${r}`:r);return}throw _(e,n,`${v(t)} cannot be encoded as JSON`)}},_=(e,t,n)=>new u(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),pe=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},v=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),y=(e,t,n)=>{let r=le(t,n);return{id:e,key:t,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},me={environmentId:`offline`,projectId:`offline`};var he=class{constructor(t){this.source=t,this.emitter=new e,this.connected=!1}async connect(){let e=await ge(this.source);return this.connected=!0,this.emitter.emit(`configBundleReceived`,{...me,kind:`full`,configs:e}),this}get isConnected(){return this.connected}on(e,t){this.emitter.on(e,t)}off(e,t){t?this.emitter.off(e,t):this.emitter.removeAllListeners(e)}close(){this.connected=!1}dispose(){this.close(),this.emitter.removeAllListeners()}};const ge=async e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return b(e.values,`The offline values`);case`file`:return b(await _e(e.path),`The offline values file '${e.path}'`);case`rejected`:throw new d(e.message)}},_e=async e=>{let t;try{t=await i(a(e),`utf8`)}catch(t){throw new d(`The offline values file '${e}' could not be read: ${x(t)}`)}let n;try{n=JSON.parse(t)}catch(t){throw new d(`The offline values file '${e}' is not valid JSON: ${x(t)}`)}if(!ve(n))throw new d(`The offline values file '${e}' must hold a JSON object with one value per config key, but holds ${ye(n)}.`);return n},b=(e,t)=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,y(`offline:${e}`,e,t)]))}catch(e){throw e instanceof u?new d(`${t} could not be loaded. ${e.message}`):e}},ve=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ye=e=>e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`,x=e=>e instanceof Error?e.message:String(e),be=new URL(`https://server-sdk-api.configdirector.com`),xe=(e,t)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:Ce(t)};let n=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new u(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`);return t?.file!==void 0||t?.values!==void 0?{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection options 'file' and 'values' apply only when the connection mode is 'offline', but the mode is '${n}'.`}}:{kind:`connect`,mode:n,serverSdkKey:e,baseUrl:Se(t?.url)}},Se=e=>{if(!e)return be;try{return new URL(e)}catch(t){throw new u(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},Ce=e=>e.file!==void 0&&e.values!==void 0?{kind:`rejected`,message:`An offline connection takes either 'file' or 'values', not both.`}:e.file===void 0?e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values}:{kind:`file`,path:e.file},we=/^(?:0|[1-9][0-9]*)$/,Te=/~(?![01])/,S=Object.prototype.propertyIsEnumerable,Ee=e=>{if(!Te.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},De=(e,t)=>{if(Array.isArray(e))return we.test(t)&&S.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return S.call(e,t)?e[t]:void 0},Oe=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=Ee(t);if(e===void 0||(n=De(n,e),n===void 0))return}return n},ke=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},Ae=(e,t,n)=>{let r=t.toLowerCase(),i=C(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=C(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},C=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!je(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},je=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Me=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=w(e),a=w(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},w=e=>{let t=o.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},Ne=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=s.coerce(e),a=n.map(e=>s.coerce(e)),o=a[0]??null;switch(r){case`=`:return T(i,o);case`<`:return E(i,o,s.lt);case`<=`:return E(i,o,s.lte);case`>`:return E(i,o,s.gt);case`>=`:return E(i,o,s.gte);case`is one of`:return a.some(e=>T(i,e));case`is not one of`:return!a.some(e=>T(i,e));default:return!1}},T=(e,t)=>e!==null&&t!==null&&s.eq(e,t),E=(e,t,n)=>e!==null&&t!==null&&n(e,t),D=Symbol(`absent`),O=Symbol(`unknown-attribute`),k=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,A=e=>e===D||e==null?``:k(e)?j(e):``,j=e=>typeof e==`string`?e:String(e),M=e=>e===D?void 0:e,Pe=e=>e===O?`unknown-attribute`:e===D?`absent`:k(e)?`scalar`:Array.isArray(e)?`array`:`object`,Fe=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(k).map(j);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}},N=e=>e?.context?.kind??`user`;var Ie=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=Pe(n),i=n===D||n===O?void 0:n;return n===O?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return ke(A(t),e.operator,n);case`number`:return Ae(M(t),e.operator,n);case`datetime`:return Me(A(t),e.operator,n);case`semver`:return Ne(A(t),e.operator,n);case`array`:return Fe(M(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return P(t?.context?.id);case`name`:return P(t?.context?.name);case`kind`:return N(t);case`appName`:return P(t?.metadata?.appName);case`appVersion`:return P(t?.metadata?.appVersion);case`traits`:return e.trait?P(Oe(e.trait,t?.context?.traits)):D;default:return O}}};const P=e=>e??D;var Le=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!Re(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const Re=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),ze=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number(c(r,{seed:15426857351n})%1000n)/10},F={kind:`not-matched`},Be={served:`matched`,"not-matched":`not-matched`,"rollout-skipped-no-identifier":`rollout-skipped-no-identifier`},Ve=(e,t)=>{if(t===void 0)return;let n=(e.variations??[]).find(e=>e.id===t);return n?{id:t,name:n.name}:void 0},I=(e,t)=>({id:e.id,key:e.key,type:e.type,value:t.value,valueId:t.valueId,variation:Ve(e,t.variationId),...t.rolloutShare});var He=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new Ie,this.segmentEvaluator=new Le(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return I(e,this.explain(e,t,n))}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[];for(let a of r){let r=this.explainRule(a,e,t,n);if(i.push(r),r.serving.kind!==`not-matched`)break}let a=[...i.map(e=>e.explanation),...r.slice(i.length).map(e=>({ruleId:e.id,outcome:`not-evaluated`,conditions:[],bucket:void 0}))],o=t=>({value:e.target?.defaultValue,valueId:e.target?.defaultValueId,variationId:e.target?.defaultVariationId,rolloutShare:void 0,reason:t,servedBy:{kind:`default`},rules:a}),s=i[i.length-1]?.serving??F;switch(s.kind){case`served`:return{...s.servedValue,reason:`found-match`,servedBy:{kind:`rule`,ruleId:s.ruleId},rules:a};case`rollout-skipped-no-identifier`:return o(`rollout-skipped-no-identifier`);case`not-matched`:return o(`found-match`)}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a=F;return e.type==`percentage`?a=this.explainRollout(e,t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),i.outcome=Be[a.kind],{explanation:i,serving:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},serving:F}}}explainRollout(e,t,n,r){if(e.percentages==null)return F;let i=n?.context?.id??void 0;if(i===void 0)return{kind:`rollout-skipped-no-identifier`};let a=ze({configId:t.id,contextIdentifier:i,contextKind:N(n)}),o=[],s=0,c;for(let t of e.percentages){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?F:{kind:`served`,ruleId:e.id,servedValue:{value:c.value.toString(),valueId:c.valueId,variationId:c.variationId,rolloutShare:{ruleId:e.id,shareId:c.id}}}}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}return a?F:e.target==`value`?e.value==null?F:{kind:`served`,ruleId:e.id,servedValue:{value:e.value.toString(),valueId:e.valueId,variationId:e.variationId,rolloutShare:void 0}}:e.target==`percentage`?this.explainRollout(e,t,n,i):F}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const Ue={variation:void 0,ruleId:void 0,shareId:void 0},We=e=>{let t=e.variation;if(t!=null)return t.name?{id:t.id,name:t.name}:{id:t.id}},Ge=e=>({variation:We(e),ruleId:e.ruleId??void 0,shareId:e.shareId??void 0}),L=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},R=e=>e===`number`||e===`bigint`,Ke=new Set([`boolean`,`integer`,`float`]),qe=(e,t)=>{let n=Je(e,t);return{...n,...n.usedDefault?Ue:Ge(e)}},Je=(e,t)=>{let n=e.value,r=L(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return $e(n,t,r,e.valueId);if(typeof t==`string`)return Ke.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=Ye(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(R(typeof t)&&e.type===`integer`){let i=Xe(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(R(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=Ze(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`}},Ye=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},Xe=e=>{let t=z(e);return t==null?void 0:Math.trunc(t)},Ze=e=>z(e),z=e=>{if(!e||!Qe(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},Qe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},$e=(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 et(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`}}},et=(e,t)=>e===null?!1:B(e)===B(t),B=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},V={off:-1,error:0,warn:1,info:2,debug:3},tt=()=>{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 nt=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=tt()}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)}},rt=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const H=(e,t)=>new nt(e??`warn`,t??new rt),it=(e,t)=>new URL(e,t?.toString()),at=(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.`},ot=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,st=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ot(t))return!1;return!0},ct=e=>e==null||typeof e==`string`&&st(e),lt=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},ut=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},dt=e=>{let t=e?.kind;return ct(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:ut(lt(t),128)}};var ft=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??(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}};const U=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,W=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}},G=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},pt=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};var mt=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return G(e.discreteEvents)&&G(e.aggregatedEvents)&&pt(e.droppedEvents)}async sendReport(e){try{let t=await p(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},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){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},ht=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}))}},gt=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||(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}};const _t=e=>e>=55296&&e<=56319,vt=e=>e>=56320&&e<=57343,yt=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:_t(r)&&n+1<e.length&&vt(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},K=e=>{let t=e?.anonymous?void 0:e?.id;return t===void 0?{}:{contextKind:e?.kind??`user`,contextIdentifier:t}},q=1024,J={"name-outside-the-character-limit":`[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to 150 characters.`,"value-not-a-finite-number":`[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.`,"details-not-reportable":`[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than 20 top-level keys, are larger than ${q} bytes as JSON, or cannot be written as JSON.`,"batch-already-full":`[ConfigDirectorClient] A tracked event was not reported because 1000 tracked events are already waiting for the next telemetry batch.`},bt=(e,t)=>{for(let n of t)e.warn(`${J[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)},Y=e=>e!=null,X=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xt=e=>typeof e==`string`&&e.length>=1&&e.length<=300&&Array.from(e).length<=150,St=e=>Y(e)?typeof e==`number`&&Number.isFinite(e)?{status:`reportable`,fields:{value:e}}:{status:`left-out`,warning:`value-not-a-finite-number`}:{status:`not-given`},Ct=e=>{if(X(e))try{let t=JSON.stringify(e);if(typeof t!=`string`||yt(t)>q)return;let n=JSON.parse(t);return X(n)&&Object.keys(n).length<=20?n:void 0}catch{return}},wt=e=>{if(!Y(e))return{status:`not-given`};let t=Ct(e);return t===void 0?{status:`left-out`,warning:`details-not-reportable`}:{status:`reportable`,fields:{details:t}}},Z=e=>e.status===`reportable`?e.fields:void 0,Tt=(...e)=>e.flatMap(e=>e.status===`left-out`?[e.warning]:[]),Et=e=>{if(!xt(e.name))return{outcome:`dropped`,warnings:[`name-outside-the-character-limit`]};let t=St(e.options?.value),n=wt(e.options?.details);return{outcome:`admitted`,entry:{name:e.name,...K(e.context),...Z(t),...Z(n),happenedAt:e.happenedAt.toISOString()},warnings:Tt(t,n)}};var Dt=class{constructor(){this.entries=[],this.warningsRaisedThisBatch=new Set}add(e){return this.warningsOfKeeping(e).filter(e=>this.isFirstThisBatch(e))}absorb(e){this.entries.push(...e)}takeBatch(){let e=this.entries;return this.clear(),e}clear(){this.entries=[],this.warningsRaisedThisBatch.clear()}warningsOfKeeping(e){switch(e.outcome){case`dropped`:return e.warnings;case`admitted`:return this.entries.length>=1e3?[`batch-already-full`]:(this.entries.push(e.entry),e.warnings)}}isFirstThisBatch(e){return this.warningsRaisedThisBatch.has(e)?!1:(this.warningsRaisedThisBatch.add(e),!0)}},Q=class{constructor(e){this.aggregator=new ht,this.trackedEventQueue=new Dt,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new gt(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))}trackedEvent(e){this.collectEvents&&bt(this.logger,this.trackedEventQueue.add(e))}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(),this.trackedEventQueue.clear()}dispose(){this.close()}},Ot=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},kt=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await U(e.defaultValue,this.valueIdGenerator),evaluatedValue:await U(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},At=class extends Q{constructor(e){super(e),this.invalidContextSubmissions=new ft,this.reporter=new mt(e),this.contexts=new Ot(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new kt(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,{contextKind:n,contextIdentifier:r}=K(t);r&&this.contexts.set(`${n}:${r}`,{...t,kind:n});let i={...e.evaluation,contextId:r,contextKind:n};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(i))}recordInvalidContext(e){return this.invalidContextSubmissions.record(e)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:W({value:e.defaultValue,type:e.type}),evaluatedValue:W({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts,trackedEvents:this.trackedEventQueue.takeBatch()},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const $={start:()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>`new-kind-sample`,trackedEvent:()=>{},close:async()=>{}},jt=(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`)},Mt=Math.ceil(128/Math.log2(62)),Nt=async e=>jt(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Mt),Pt={streaming:`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`,polling:`Since the client was configured without streaming, configs may not update and always return the default value.`},Ft={"new-kind-sample":(e,t)=>e.error(`[ConfigDirectorClient] Ignored a context with the invalid kind '${t}' and evaluated as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),"known-kind-sample":()=>{},"first-beyond-sample-limit":e=>e.error(`[ConfigDirectorClient] Ignored a context with another invalid kind and evaluated as if no context was supplied. 20 different invalid kinds were logged recently, so further invalid kinds are not logged individually.`),"beyond-sample-limit":()=>{}},It=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Lt=class t{static from(e,n,r){return typeof e==`object`?new t(void 0,n,e):new t(e,n,r)}constructor(t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??H(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.connectionPlan=xe(t,r?.connection),this.configEvaluator=new He(this.logger),this.usageEventCollector=i?.telemetry??this.buildTelemetryClient(n,r),this.transport=i?.transport??this.buildTransport(n,r),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),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)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof d)throw e;this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return Pt[this.connectionPlan.mode];case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=at(t,{defaultSeconds:300,minimumSeconds:60});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 $;case`connect`:{let r=t?.telemetry?.eventQueueLimit??5e3;return new At({sdkKey:n.serverSdkKey,sdkIdentity:e,metaContext:t?.metadata??{},logger:this.logger,baseUrl:n.baseUrl,flushIntervalDelay:t?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(r*.7),contextLimit:Math.floor(r*.3),urlFactory:it,valueIdGenerator:Nt})}}}buildTransport(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return new he(n.source);case`connect`:return new(this.getTransportConstructor(n.mode))({serverSdkKey:n.serverSdkKey,baseUrl:n.baseUrl,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion},logger:this.logger,pollingInterval:this.pollingIntervalFor(n.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return ce;case`streaming`:return h}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>It(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}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.evaluationOf(e,t,n.defaultValue,n.context).value;n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>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,n){return this.evaluate(e,t,n).value}evaluate(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.evaluationOf(e,r,t,n)}evaluationOf(e,t,n,r){let i=this.contextToEvaluate(r);if(t){let r=this.configEvaluator.explain(t,{context:i,metadata:this.metaContext},this.configSet?.segments),a=I(t,r),o=qe(a,n),s=o.usedDefault?o.reason:r.reason;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,type:a.type,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:s,ruleId:o.ruleId,shareId:o.shareId,variationId:o.variation?.id}});let c={key:e,value:o.parsedValue,valueId:o.parsedValueId??void 0,variation:o.variation,isDefaultValue:o.usedDefault,reason:s,context:i};return this.dispatchEvaluationEvent(c),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),c}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,defaultValue:n,requestedType:L(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:i};return this.dispatchEvaluationEvent(r),r}}track(e,t,n){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:try{let r=this.contextToEvaluate(t);this.usageEventCollector.trackedEvent(Et({name:e,context:r,options:n,happenedAt:new Date}),r)}catch(e){this.logger.warn(`[ConfigDirectorClient] A tracked event was not reported because it could not be read: `,e)}return}}contextToEvaluate(e){let t=dt(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:Ft[this.usageEventCollector.recordInvalidContext(t.kindSample)](this.logger,t.kindSample);return}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}validateDefaultValue(e){if(e==null)throw new u(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new u(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){let t=this.contextToEvaluate(e?.context);if(!this.configSet)return{};let n=Object.entries(this.configSet.configs),r=e?.configKeys?n.filter(([t])=>e.configKeys?.includes(t)):n;return Object.fromEntries(r.map(([e,n])=>[e,this.configEvaluator.evaluate(n,{context:t,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{y as a,u as c,H as i,$ as n,l as o,J as r,d as s,Lt as t};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-BWenvqJ5.mjs.map
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 ae=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 te(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new ie({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 ee(`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 re(`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 ne(`${n} must be a function`);return e}};const oe=e=>new ae(e),p=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}},m=9e4;var h=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=oe({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),m);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||p(m,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=r(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new l(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},se=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 l(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new l(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new l(`Failed to parse the response from the server: ${e}`):new l(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new l(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}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()}},ce=class extends se{constructor(e){super(),this.options=e,this.eventEmitter=new t,this._sessionId=r(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await p(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,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){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const le=(e,t)=>{if(e.trim().length==0)throw new u(`Invalid config key. The key of a value cannot be empty.`);return ue(e,t)},ue=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return de(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return g(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new u(`Invalid value for '${e}': ${v(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},de=(e,t)=>{if(!Number.isFinite(t))throw new u(`Invalid value for '${e}': ${v(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new u(`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:fe(t)}},fe=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}`},g=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw _(e,n,`${v(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>g(e,t,`${n}[${r}]`));return}if(pe(t)){for(let[r,i]of Object.entries(t))g(e,i,n?`${n}.${r}`:r);return}throw _(e,n,`${v(t)} cannot be encoded as JSON`)}},_=(e,t,n)=>new u(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),pe=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},v=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),y=(e,t,n)=>{let r=le(t,n);return{id:e,key:t,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},me={environmentId:`offline`,projectId:`offline`};var he=class{constructor(t){this.source=t,this.emitter=new e,this.connected=!1}async connect(){let e=await ge(this.source);return this.connected=!0,this.emitter.emit(`configBundleReceived`,{...me,kind:`full`,configs:e}),this}get isConnected(){return this.connected}on(e,t){this.emitter.on(e,t)}off(e,t){t?this.emitter.off(e,t):this.emitter.removeAllListeners(e)}close(){this.connected=!1}dispose(){this.close(),this.emitter.removeAllListeners()}};const ge=async e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return b(e.values,`The offline values`);case`file`:return b(await _e(e.path),`The offline values file '${e.path}'`);case`rejected`:throw new d(e.message)}},_e=async e=>{let t;try{t=await i(a(e),`utf8`)}catch(t){throw new d(`The offline values file '${e}' could not be read: ${x(t)}`)}let n;try{n=JSON.parse(t)}catch(t){throw new d(`The offline values file '${e}' is not valid JSON: ${x(t)}`)}if(!ve(n))throw new d(`The offline values file '${e}' must hold a JSON object with one value per config key, but holds ${ye(n)}.`);return n},b=(e,t)=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,y(`offline:${e}`,e,t)]))}catch(e){throw e instanceof u?new d(`${t} could not be loaded. ${e.message}`):e}},ve=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ye=e=>e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`,x=e=>e instanceof Error?e.message:String(e),be=new URL(`https://server-sdk-api.configdirector.com`),xe=(e,t)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:Ce(t)};let n=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new u(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`);return t?.file!==void 0||t?.values!==void 0?{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection options 'file' and 'values' apply only when the connection mode is 'offline', but the mode is '${n}'.`}}:{kind:`connect`,mode:n,serverSdkKey:e,baseUrl:Se(t?.url)}},Se=e=>{if(!e)return be;try{return new URL(e)}catch(t){throw new u(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},Ce=e=>e.file!==void 0&&e.values!==void 0?{kind:`rejected`,message:`An offline connection takes either 'file' or 'values', not both.`}:e.file===void 0?e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values}:{kind:`file`,path:e.file},we=/^(?:0|[1-9][0-9]*)$/,Te=/~(?![01])/,S=Object.prototype.propertyIsEnumerable,Ee=e=>{if(!Te.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},De=(e,t)=>{if(Array.isArray(e))return we.test(t)&&S.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return S.call(e,t)?e[t]:void 0},Oe=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=Ee(t);if(e===void 0||(n=De(n,e),n===void 0))return}return n},ke=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},Ae=(e,t,n)=>{let r=t.toLowerCase(),i=C(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=C(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},C=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!je(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},je=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Me=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=w(e),a=w(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},w=e=>{let t=o.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},Ne=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=s.coerce(e),a=n.map(e=>s.coerce(e)),o=a[0]??null;switch(r){case`=`:return T(i,o);case`<`:return E(i,o,s.lt);case`<=`:return E(i,o,s.lte);case`>`:return E(i,o,s.gt);case`>=`:return E(i,o,s.gte);case`is one of`:return a.some(e=>T(i,e));case`is not one of`:return!a.some(e=>T(i,e));default:return!1}},T=(e,t)=>e!==null&&t!==null&&s.eq(e,t),E=(e,t,n)=>e!==null&&t!==null&&n(e,t),D=Symbol(`absent`),O=Symbol(`unknown-attribute`),k=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,A=e=>e===D||e==null?``:k(e)?j(e):``,j=e=>typeof e==`string`?e:String(e),M=e=>e===D?void 0:e,Pe=e=>e===O?`unknown-attribute`:e===D?`absent`:k(e)?`scalar`:Array.isArray(e)?`array`:`object`,Fe=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(k).map(j);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}},N=e=>e?.context?.kind??`user`;var Ie=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=Pe(n),i=n===D||n===O?void 0:n;return n===O?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return ke(A(t),e.operator,n);case`number`:return Ae(M(t),e.operator,n);case`datetime`:return Me(A(t),e.operator,n);case`semver`:return Ne(A(t),e.operator,n);case`array`:return Fe(M(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return P(t?.context?.id);case`name`:return P(t?.context?.name);case`kind`:return N(t);case`appName`:return P(t?.metadata?.appName);case`appVersion`:return P(t?.metadata?.appVersion);case`traits`:return e.trait?P(Oe(e.trait,t?.context?.traits)):D;default:return O}}};const P=e=>e??D;var Le=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!Re(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const Re=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),ze=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number(c(r,{seed:15426857351n})%1000n)/10},F={kind:`not-matched`},Be={served:`matched`,"not-matched":`not-matched`,"rollout-skipped-no-identifier":`rollout-skipped-no-identifier`},Ve=(e,t)=>{if(t===void 0)return;let n=(e.variations??[]).find(e=>e.id===t);return n?{id:t,name:n.name}:void 0},I=(e,t)=>({id:e.id,key:e.key,type:e.type,value:t.value,valueId:t.valueId,variation:Ve(e,t.variationId),...t.rolloutShare});var He=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new Ie,this.segmentEvaluator=new Le(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return I(e,this.explain(e,t,n))}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[];for(let a of r){let r=this.explainRule(a,e,t,n);if(i.push(r),r.serving.kind!==`not-matched`)break}let a=[...i.map(e=>e.explanation),...r.slice(i.length).map(e=>({ruleId:e.id,outcome:`not-evaluated`,conditions:[],bucket:void 0}))],o=t=>({value:e.target?.defaultValue,valueId:e.target?.defaultValueId,variationId:e.target?.defaultVariationId,rolloutShare:void 0,reason:t,servedBy:{kind:`default`},rules:a}),s=i[i.length-1]?.serving??F;switch(s.kind){case`served`:return{...s.servedValue,reason:`found-match`,servedBy:{kind:`rule`,ruleId:s.ruleId},rules:a};case`rollout-skipped-no-identifier`:return o(`rollout-skipped-no-identifier`);case`not-matched`:return o(`found-match`)}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a=F;return e.type==`percentage`?a=this.explainRollout(e,t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),i.outcome=Be[a.kind],{explanation:i,serving:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},serving:F}}}explainRollout(e,t,n,r){if(e.percentages==null)return F;let i=n?.context?.id??void 0;if(i===void 0)return{kind:`rollout-skipped-no-identifier`};let a=ze({configId:t.id,contextIdentifier:i,contextKind:N(n)}),o=[],s=0,c;for(let t of e.percentages){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?F:{kind:`served`,ruleId:e.id,servedValue:{value:c.value.toString(),valueId:c.valueId,variationId:c.variationId,rolloutShare:{ruleId:e.id,shareId:c.id}}}}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}return a?F:e.target==`value`?e.value==null?F:{kind:`served`,ruleId:e.id,servedValue:{value:e.value.toString(),valueId:e.valueId,variationId:e.variationId,rolloutShare:void 0}}:e.target==`percentage`?this.explainRollout(e,t,n,i):F}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const Ue={variation:void 0,ruleId:void 0,shareId:void 0},We=e=>{let t=e.variation;if(t!=null)return t.name?{id:t.id,name:t.name}:{id:t.id}},Ge=e=>({variation:We(e),ruleId:e.ruleId??void 0,shareId:e.shareId??void 0}),L=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},R=e=>e===`number`||e===`bigint`,Ke=new Set([`boolean`,`integer`,`float`]),qe=(e,t)=>{let n=Je(e,t);return{...n,...n.usedDefault?Ue:Ge(e)}},Je=(e,t)=>{let n=e.value,r=L(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return $e(n,t,r,e.valueId);if(typeof t==`string`)return Ke.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=Ye(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(R(typeof t)&&e.type===`integer`){let i=Xe(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(R(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=Ze(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`}},Ye=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},Xe=e=>{let t=z(e);return t==null?void 0:Math.trunc(t)},Ze=e=>z(e),z=e=>{if(!e||!Qe(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},Qe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},$e=(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 et(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`}}},et=(e,t)=>e===null?!1:B(e)===B(t),B=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},V={off:-1,error:0,warn:1,info:2,debug:3},tt=()=>{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 nt=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=tt()}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)}},rt=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const H=(e,t)=>new nt(e??`warn`,t??new rt),it=(e,t)=>new URL(e,t?.toString()),at=(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.`},ot=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,st=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ot(t))return!1;return!0},ct=e=>e==null||typeof e==`string`&&st(e),lt=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},ut=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},dt=e=>{let t=e?.kind;return ct(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:ut(lt(t),128)}};var ft=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??(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}};const U=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,W=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}},G=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},pt=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};var mt=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return G(e.discreteEvents)&&G(e.aggregatedEvents)&&pt(e.droppedEvents)}async sendReport(e){try{let t=await p(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},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.`):t.status===413&&this.logger.warn(`[EventReporter] The telemetry endpoint responded with status ${t.status}. The events in this report were discarded.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429&&e!=413}},ht=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}))}},gt=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||(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}};const _t=e=>e>=55296&&e<=56319,vt=e=>e>=56320&&e<=57343,yt=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:_t(r)&&n+1<e.length&&vt(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},K=e=>{let t=e?.anonymous?void 0:e?.id;return t===void 0?{}:{contextKind:e?.kind??`user`,contextIdentifier:t}},q=1024,J={"name-outside-the-character-limit":`[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to 150 characters.`,"value-not-a-finite-number":`[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.`,"details-not-reportable":`[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than 20 top-level keys, are larger than ${q} bytes as JSON, or cannot be written as JSON.`,"batch-already-full":`[ConfigDirectorClient] A tracked event was not reported because 1000 tracked events are already waiting for the next telemetry batch.`},bt=(e,t)=>{for(let n of t)e.warn(`${J[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)},Y=e=>e!=null,X=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xt=e=>typeof e==`string`&&e.length>=1&&e.length<=300&&Array.from(e).length<=150,St=e=>Y(e)?typeof e==`number`&&Number.isFinite(e)?{status:`reportable`,fields:{value:e}}:{status:`left-out`,warning:`value-not-a-finite-number`}:{status:`not-given`},Ct=e=>{if(X(e))try{let t=JSON.stringify(e);if(typeof t!=`string`||yt(t)>q)return;let n=JSON.parse(t);return X(n)&&Object.keys(n).length<=20?n:void 0}catch{return}},wt=e=>{if(!Y(e))return{status:`not-given`};let t=Ct(e);return t===void 0?{status:`left-out`,warning:`details-not-reportable`}:{status:`reportable`,fields:{details:t}}},Z=e=>e.status===`reportable`?e.fields:void 0,Tt=(...e)=>e.flatMap(e=>e.status===`left-out`?[e.warning]:[]),Et=e=>{if(!xt(e.name))return{outcome:`dropped`,warnings:[`name-outside-the-character-limit`]};let t=St(e.options?.value),n=wt(e.options?.details);return{outcome:`admitted`,entry:{name:e.name,...K(e.context),...Z(t),...Z(n),happenedAt:e.happenedAt.toISOString()},warnings:Tt(t,n)}};var Dt=class{constructor(){this.entries=[],this.warningsRaisedThisBatch=new Set}add(e){return this.warningsOfKeeping(e).filter(e=>this.isFirstThisBatch(e))}absorb(e){this.entries.push(...e)}takeBatch(){let e=this.entries;return this.clear(),e}clear(){this.entries=[],this.warningsRaisedThisBatch.clear()}warningsOfKeeping(e){switch(e.outcome){case`dropped`:return e.warnings;case`admitted`:return this.entries.length>=1e3?[`batch-already-full`]:(this.entries.push(e.entry),e.warnings)}}isFirstThisBatch(e){return this.warningsRaisedThisBatch.has(e)?!1:(this.warningsRaisedThisBatch.add(e),!0)}},Q=class{constructor(e){this.aggregator=new ht,this.trackedEventQueue=new Dt,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new gt(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))}trackedEvent(e){this.collectEvents&&bt(this.logger,this.trackedEventQueue.add(e))}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(),this.trackedEventQueue.clear()}dispose(){this.close()}},Ot=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},kt=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await U(e.defaultValue,this.valueIdGenerator),evaluatedValue:await U(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},At=class extends Q{constructor(e){super(e),this.invalidContextSubmissions=new ft,this.reporter=new mt(e),this.contexts=new Ot(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new kt(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,{contextKind:n,contextIdentifier:r}=K(t);r&&this.contexts.set(`${n}:${r}`,{...t,kind:n});let i={...e.evaluation,contextId:r,contextKind:n};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(i))}recordInvalidContext(e){return this.invalidContextSubmissions.record(e)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:W({value:e.defaultValue,type:e.type}),evaluatedValue:W({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts,trackedEvents:this.trackedEventQueue.takeBatch()},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const $={start:()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>`new-kind-sample`,trackedEvent:()=>{},close:async()=>{}},jt=(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`)},Mt=Math.ceil(128/Math.log2(62)),Nt=async e=>jt(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Mt),Pt={streaming:`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`,polling:`Since the client was configured without streaming, configs may not update and always return the default value.`},Ft={"new-kind-sample":(e,t)=>e.error(`[ConfigDirectorClient] Ignored a context with the invalid kind '${t}' and evaluated as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),"known-kind-sample":()=>{},"first-beyond-sample-limit":e=>e.error(`[ConfigDirectorClient] Ignored a context with another invalid kind and evaluated as if no context was supplied. 20 different invalid kinds were logged recently, so further invalid kinds are not logged individually.`),"beyond-sample-limit":()=>{}},It=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Lt=class t{static from(e,n,r){return typeof e==`object`?new t(void 0,n,e):new t(e,n,r)}constructor(t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??H(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.connectionPlan=xe(t,r?.connection),this.configEvaluator=new He(this.logger),this.usageEventCollector=i?.telemetry??this.buildTelemetryClient(n,r),this.transport=i?.transport??this.buildTransport(n,r),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),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)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof d)throw e;this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return Pt[this.connectionPlan.mode];case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=at(t,{defaultSeconds:300,minimumSeconds:60});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 $;case`connect`:{let r=t?.telemetry?.eventQueueLimit??5e3;return new At({sdkKey:n.serverSdkKey,sdkIdentity:e,metaContext:t?.metadata??{},logger:this.logger,baseUrl:n.baseUrl,flushIntervalDelay:t?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(r*.7),contextLimit:Math.floor(r*.3),urlFactory:it,valueIdGenerator:Nt})}}}buildTransport(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return new he(n.source);case`connect`:return new(this.getTransportConstructor(n.mode))({serverSdkKey:n.serverSdkKey,baseUrl:n.baseUrl,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion},logger:this.logger,pollingInterval:this.pollingIntervalFor(n.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return ce;case`streaming`:return h}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>It(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}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.evaluationOf(e,t,n.defaultValue,n.context).value;n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>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,n){return this.evaluate(e,t,n).value}evaluate(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.evaluationOf(e,r,t,n)}evaluationOf(e,t,n,r){let i=this.contextToEvaluate(r);if(t){let r=this.configEvaluator.explain(t,{context:i,metadata:this.metaContext},this.configSet?.segments),a=I(t,r),o=qe(a,n),s=o.usedDefault?o.reason:r.reason;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,type:a.type,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:s,ruleId:o.ruleId,shareId:o.shareId,variationId:o.variation?.id}});let c={key:e,value:o.parsedValue,valueId:o.parsedValueId??void 0,variation:o.variation,isDefaultValue:o.usedDefault,reason:s,context:i};return this.dispatchEvaluationEvent(c),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),c}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,defaultValue:n,requestedType:L(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:i};return this.dispatchEvaluationEvent(r),r}}track(e,t,n){switch(this.connectionPlan.kind){case`stay-offline`:return;case`connect`:try{let r=this.contextToEvaluate(t);this.usageEventCollector.trackedEvent(Et({name:e,context:r,options:n,happenedAt:new Date}),r)}catch(e){this.logger.warn(`[ConfigDirectorClient] A tracked event was not reported because it could not be read: `,e)}return}}contextToEvaluate(e){let t=dt(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:Ft[this.usageEventCollector.recordInvalidContext(t.kindSample)](this.logger,t.kindSample);return}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}validateDefaultValue(e){if(e==null)throw new u(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new u(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){let t=this.contextToEvaluate(e?.context);if(!this.configSet)return{};let n=Object.entries(this.configSet.configs),r=e?.configKeys?n.filter(([t])=>e.configKeys?.includes(t)):n;return Object.fromEntries(r.map(([e,n])=>[e,this.configEvaluator.evaluate(n,{context:t,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{y as a,u as c,H as i,$ as n,l as o,J as r,d as s,Lt as t};
6
+ //# sourceMappingURL=DefaultConfigDirectorClient-BaDqRkjV.mjs.map