@configdirector/server-sdk 1.12.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.
- package/dist/DefaultConfigDirectorClient-BaDqRkjV.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-BaDqRkjV.mjs.map +1 -0
- package/dist/DefaultConfigDirectorClient-fROPEpwq.cjs +5 -0
- package/dist/configdirector-server-testing.cjs +1 -1
- package/dist/configdirector-server-testing.d.cts +12 -3
- package/dist/configdirector-server-testing.d.cts.map +1 -1
- package/dist/configdirector-server-testing.d.mts +12 -3
- package/dist/configdirector-server-testing.d.mts.map +1 -1
- package/dist/configdirector-server-testing.mjs +1 -1
- package/dist/configdirector-server-testing.mjs.map +1 -1
- package/dist/configdirector-server.cjs +1 -1
- package/dist/configdirector-server.d.cts +2 -2
- package/dist/configdirector-server.d.mts +2 -2
- package/dist/configdirector-server.mjs +1 -1
- package/dist/{errors-D1cUkGGT.d.cts → errors-BKtOuEGy.d.cts} +76 -7
- package/dist/errors-BKtOuEGy.d.cts.map +1 -0
- package/dist/{errors-BdOy58jI.d.mts → errors-Dk_CsOtN.d.mts} +76 -7
- package/dist/errors-Dk_CsOtN.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/DefaultConfigDirectorClient-BORbruxY.cjs +0 -5
- package/dist/DefaultConfigDirectorClient-ZR0xPXNQ.mjs +0 -6
- package/dist/DefaultConfigDirectorClient-ZR0xPXNQ.mjs.map +0 -1
- package/dist/errors-BdOy58jI.d.mts.map +0 -1
- package/dist/errors-D1cUkGGT.d.cts.map +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:events`);c=s(c);let l=require(`node:crypto`),u=require(`node:fs/promises`),d=require(`node:path`),ee=require(`luxon`),f=require(`semver`);f=s(f);let te=require(`rapidhash-js`);var p=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},ne=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},re=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},ie=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},ae=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},oe=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
+
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
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
|
+
`)?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 g=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var se=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=g.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===g.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=g.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=g.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 re(`The server response did not have a body`);this._readyState=g.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new oe({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 ne(`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=g.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=g.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new ae(`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 ie(`${n} must be a function`);return e}};const ce=e=>new se(e),_=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}},v=9e4;var le=class{constructor(e){this.options=e,this.eventEmitter=new c.EventEmitter,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=ce({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(),v);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||_(v,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=(0,l.randomUUID)(),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 p(`${`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()}},ue=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 p(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new p(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new p(`Failed to parse the response from the server: ${e}`):new p(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new p(`${`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()}},de=class extends ue{constructor(e){super(),this.options=e,this.eventEmitter=new c.EventEmitter,this._sessionId=(0,l.randomUUID)(),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 _(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 fe=(e,t)=>{if(e.trim().length==0)throw new m(`Invalid config key. The key of a value cannot be empty.`);return pe(e,t)},pe=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return me(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return y(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new m(`Invalid value for '${e}': ${x(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},me=(e,t)=>{if(!Number.isFinite(t))throw new m(`Invalid value for '${e}': ${x(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new m(`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:he(t)}},he=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},y=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw b(e,n,`${x(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>y(e,t,`${n}[${r}]`));return}if(ge(t)){for(let[r,i]of Object.entries(t))y(e,i,n?`${n}.${r}`:r);return}throw b(e,n,`${x(t)} cannot be encoded as JSON`)}},b=(e,t,n)=>new m(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),ge=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},x=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),S=(e,t,n)=>{let r=fe(t,n);return{id:e,key:t,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},_e={environmentId:`offline`,projectId:`offline`};var ve=class{constructor(e){this.source=e,this.emitter=new c.default,this.connected=!1}async connect(){let e=await ye(this.source);return this.connected=!0,this.emitter.emit(`configBundleReceived`,{..._e,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 ye=async e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return C(e.values,`The offline values`);case`file`:return C(await be(e.path),`The offline values file '${e.path}'`);case`rejected`:throw new h(e.message)}},be=async e=>{let t;try{t=await(0,u.readFile)((0,d.resolve)(e),`utf8`)}catch(t){throw new h(`The offline values file '${e}' could not be read: ${w(t)}`)}let n;try{n=JSON.parse(t)}catch(t){throw new h(`The offline values file '${e}' is not valid JSON: ${w(t)}`)}if(!xe(n))throw new h(`The offline values file '${e}' must hold a JSON object with one value per config key, but holds ${Se(n)}.`);return n},C=(e,t)=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,S(`offline:${e}`,e,t)]))}catch(e){throw e instanceof m?new h(`${t} could not be loaded. ${e.message}`):e}},xe=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Se=e=>e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`,w=e=>e instanceof Error?e.message:String(e),Ce=new URL(`https://server-sdk-api.configdirector.com`),we=(e,t)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:Ee(t)};let n=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new m(`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:Te(t?.url)}},Te=e=>{if(!e)return Ce;try{return new URL(e)}catch(t){throw new m(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},Ee=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},De=/^(?:0|[1-9][0-9]*)$/,Oe=/~(?![01])/,T=Object.prototype.propertyIsEnumerable,ke=e=>{if(!Oe.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},Ae=(e,t)=>{if(Array.isArray(e))return De.test(t)&&T.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return T.call(e,t)?e[t]:void 0},je=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=ke(t);if(e===void 0||(n=Ae(n,e),n===void 0))return}return n},Me=(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}},Ne=(e,t,n)=>{let r=t.toLowerCase(),i=E(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=E(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}},E=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!Pe(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},Pe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Fe=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=D(e),a=D(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}},D=e=>{let t=ee.DateTime.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},Ie=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=f.coerce(e),a=n.map(e=>f.coerce(e)),o=a[0]??null;switch(r){case`=`:return O(i,o);case`<`:return k(i,o,f.lt);case`<=`:return k(i,o,f.lte);case`>`:return k(i,o,f.gt);case`>=`:return k(i,o,f.gte);case`is one of`:return a.some(e=>O(i,e));case`is not one of`:return!a.some(e=>O(i,e));default:return!1}},O=(e,t)=>e!==null&&t!==null&&f.eq(e,t),k=(e,t,n)=>e!==null&&t!==null&&n(e,t),A=Symbol(`absent`),j=Symbol(`unknown-attribute`),M=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,N=e=>e===A||e==null?``:M(e)?P(e):``,P=e=>typeof e==`string`?e:String(e),F=e=>e===A?void 0:e,Le=e=>e===j?`unknown-attribute`:e===A?`absent`:M(e)?`scalar`:Array.isArray(e)?`array`:`object`,Re=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(M).map(P);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}},I=e=>e?.context?.kind??`user`;var ze=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=Le(n),i=n===A||n===j?void 0:n;return n===j?{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 Me(N(t),e.operator,n);case`number`:return Ne(F(t),e.operator,n);case`datetime`:return Fe(N(t),e.operator,n);case`semver`:return Ie(N(t),e.operator,n);case`array`:return Re(F(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return L(t?.context?.id);case`name`:return L(t?.context?.name);case`kind`:return I(t);case`appName`:return L(t?.metadata?.appName);case`appVersion`:return L(t?.metadata?.appVersion);case`traits`:return e.trait?L(je(e.trait,t?.context?.traits)):A;default:return j}}};const L=e=>e??A;var Be=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!Ve(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 Ve=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),He=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number((0,te.rapidhash)(r,{seed:15426857351n})%1000n)/10},R={kind:`not-matched`},Ue={served:`matched`,"not-matched":`not-matched`,"rollout-skipped-no-identifier":`rollout-skipped-no-identifier`},We=(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},z=(e,t)=>({id:e.id,key:e.key,type:e.type,value:t.value,valueId:t.valueId,variation:We(e,t.variationId),...t.rolloutShare});var Ge=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new ze,this.segmentEvaluator=new Be(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 z(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??R;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=R;return e.type==`percentage`?a=this.explainRollout(e,t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),i.outcome=Ue[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:R}}}explainRollout(e,t,n,r){if(e.percentages==null)return R;let i=n?.context?.id??void 0;if(i===void 0)return{kind:`rollout-skipped-no-identifier`};let a=He({configId:t.id,contextIdentifier:i,contextKind:I(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?R:{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?R:e.target==`value`?e.value==null?R:{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):R}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 Ke={variation:void 0,ruleId:void 0,shareId:void 0},qe=e=>{let t=e.variation;if(t!=null)return t.name?{id:t.id,name:t.name}:{id:t.id}},Je=e=>({variation:qe(e),ruleId:e.ruleId??void 0,shareId:e.shareId??void 0}),B=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},V=e=>e===`number`||e===`bigint`,Ye=new Set([`boolean`,`integer`,`float`]),Xe=(e,t)=>{let n=Ze(e,t);return{...n,...n.usedDefault?Ke:Je(e)}},Ze=(e,t)=>{let n=e.value,r=B(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return nt(n,t,r,e.valueId);if(typeof t==`string`)return Ye.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=Qe(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(V(typeof t)&&e.type===`integer`){let i=$e(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(V(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=et(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`}},Qe=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},$e=e=>{let t=H(e);return t==null?void 0:Math.trunc(t)},et=e=>H(e),H=e=>{if(!e||!tt(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},tt=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},nt=(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 rt(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`}}},rt=(e,t)=>e===null?!1:U(e)===U(t),U=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},W={off:-1,error:0,warn:1,info:2,debug:3},it=()=>{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 at=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=it()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){W[this.level]>=W[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},ot=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const G=(e,t)=>new at(e??`warn`,t??new ot),st=(e,t)=>new URL(e,t?.toString()),ct=(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.`},lt=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,ut=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!lt(t))return!1;return!0},dt=e=>e==null||typeof e==`string`&&ut(e),ft=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},pt=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},mt=e=>{let t=e?.kind;return dt(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:pt(ft(t),128)}};var ht=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}};const K=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,q=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},J=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},gt=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 _t=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 J(e.discreteEvents)&&J(e.aggregatedEvents)&>(e.droppedEvents)}async sendReport(e){try{let t=await _(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}},vt=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}))}},yt=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}};const bt=e=>e>=55296&&e<=56319,xt=e=>e>=56320&&e<=57343,St=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:bt(r)&&n+1<e.length&&xt(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t},Y=e=>{let t=e?.anonymous?void 0:e?.id;return t===void 0?{}:{contextKind:e?.kind??`user`,contextIdentifier:t}},X=1024,Z={"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 ${X} 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.`},Ct=(e,t)=>{for(let n of t)e.warn(`${Z[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)},Q=e=>e!=null,wt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Tt=e=>typeof e==`string`&&e.length>=1&&e.length<=300&&Array.from(e).length<=150,Et=e=>Q(e)?typeof e==`number`&&Number.isFinite(e)?{status:`reportable`,fields:{value:e}}:{status:`left-out`,warning:`value-not-a-finite-number`}:{status:`not-given`},Dt=e=>{if(wt(e))try{let t=JSON.stringify(e);if(typeof t!=`string`||St(t)>X)return;let n=JSON.parse(t);return wt(n)&&Object.keys(n).length<=20?n:void 0}catch{return}},Ot=e=>{if(!Q(e))return{status:`not-given`};let t=Dt(e);return t===void 0?{status:`left-out`,warning:`details-not-reportable`}:{status:`reportable`,fields:{details:t}}},kt=e=>e.status===`reportable`?e.fields:void 0,At=(...e)=>e.flatMap(e=>e.status===`left-out`?[e.warning]:[]),jt=e=>{if(!Tt(e.name))return{outcome:`dropped`,warnings:[`name-outside-the-character-limit`]};let t=Et(e.options?.value),n=Ot(e.options?.details);return{outcome:`admitted`,entry:{name:e.name,...Y(e.context),...kt(t),...kt(n),happenedAt:e.happenedAt.toISOString()},warnings:At(t,n)}};var Mt=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)}},Nt=class{constructor(e){this.aggregator=new vt,this.trackedEventQueue=new Mt,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new yt(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&&Ct(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()}},Pt=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)}}},Ft=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 K(e.defaultValue,this.valueIdGenerator),evaluatedValue:await K(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},It=class extends Nt{constructor(e){super(e),this.invalidContextSubmissions=new ht,this.reporter=new _t(e),this.contexts=new Pt(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new Ft(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,{contextKind:n,contextIdentifier:r}=Y(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:q({value:e.defaultValue,type:e.type}),evaluatedValue:q({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()=>{}},Lt=(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`)},Rt=Math.ceil(128/Math.log2(62)),zt=async e=>Lt((0,l.createHash)(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Rt),Bt={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.`},Vt={"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":()=>{}},Ht=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Ut=class e{static from(t,n,r){return typeof t==`object`?new e(void 0,n,t):new e(t,n,r)}constructor(e,t,n,r){this.handlersMap=new Map,this.eventEmitter=new c.default,this.ready=!1,this.logger=n?.logger??G(),this.timeout=n?.connection?.timeout??3e3,this.metaContext=n?.metadata??{},this.connectionPlan=we(e,n?.connection),this.configEvaluator=new Ge(this.logger),this.usageEventCollector=r?.telemetry??this.buildTelemetryClient(t,n),this.transport=r?.transport??this.buildTransport(t,n),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`,n?.hooks?.clientReady),this.registerHandler(`configEvaluated`,n?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,n?.hooks?.configsUpdated),this.registerHandler(`connectionError`,n?.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 h)throw e;this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return Bt[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=ct(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 It({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:st,valueIdGenerator:zt})}}}buildTransport(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return new ve(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 de;case`streaming`:return le}}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])=>Ht(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=z(t,r),o=Xe(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:B(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(jt({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=mt(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:Vt[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 m(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new m(`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)})}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Ut}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-fROPEpwq.cjs`);let t=require(`node:events`);t=e.l(t);const n=(e,t)=>({name:e.name,...t===void 0?{}:{context:t},...e.value===void 0?{}:{value:e.value},...e.details===void 0?{}:{details:e.details}});var r=class{constructor(e){this.logger=e,this.events=[]}record(t,r){switch(t.warnings.forEach(t=>this.logger.warn(e.r[t])),t.outcome){case`dropped`:return;case`admitted`:this.events.push(n(t.entry,r));return}}};const i={environmentId:`test-environment`,projectId:`test-project`};var a=class{constructor(e,n){this.logger=e,this.emitter=new t.default,this.configs=new Map,this.pendingDeliveries=[],this.armed=`nothing`,this.connected=!1,this.delivering=!1,this.encodeAll(n).forEach((e,t)=>this.configs.set(t,e))}setValue(e,t){let n=this.encode(e,t);this.configs.set(e,n),this.deliverIfConnected({...i,kind:`delta`,configs:{[e]:n}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(){this.armed=`hold`}complete(){this.pendingHold?this.pendingHold.complete():this.armed===`hold`&&(this.armed=`nothing`)}fail(){this.pendingHold?this.pendingHold.fail():this.armed=`failure`}connect(e){this.endAttempt();let t=this.armed;switch(this.armed=`nothing`,t){case`failure`:return this.failNow();case`hold`:return this.holdNow(e);default:return this.connectNow(),Promise.resolve(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.endAttempt()}dispose(){this.close(),this.emitter.removeAllListeners()}endAttempt(){this.connected=!1,this.pendingHold?.end()}connectNow(){this.connected=!0,this.deliver(this.fullUpdate())}holdNow(e){return new Promise((t,n)=>{let r=setTimeout(()=>this.pendingHold?.end(),e),i=()=>{clearTimeout(r),this.pendingHold=void 0};this.pendingHold={end:()=>{i(),t(this)},complete:()=>{i(),this.connectNow(),t(this)},fail:()=>{i();let e=this.fatalError();this.emitter.emit(`connectionError`,e),n(e)}}})}failNow(){let e=this.fatalError();return this.emitter.emit(`connectionError`,e),Promise.reject(e)}fatalError(){return new e.o(`Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.`,401)}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configBundleReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...i,kind:`full`,configs:Object.fromEntries(this.configs)}}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(t,n){return e.a(`test-config:${t}`,t,n)}},o=class{constructor(e,t,n){this.client=e,this.connection=t,this.trackedEvents=n}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold()}completeInitialization(){this.connection.complete()}failInitialization(){this.connection.fail()}};const s=(t,n)=>{let i=n?.logger??e.i(),s=new a(i,n?.values??{}),c=new r(i);return new o(new e.t(`test-client`,t,{logger:i,connection:{timeout:n?.timeout}},{transport:s,telemetry:{...e.n,trackedEvent:(e,t)=>c.record(e,t)}}),s,c.events)},c=e=>s({sdkName:`js-server-sdk`,sdkVersion:`1.13.1`},e);exports.ConfigDirectorConnectionError=e.o,exports.ConfigDirectorValidationError=e.c,exports.createTestClient=c;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as NativeValues, i as ConfigDirectorClient, l as NativeJsonValue, m as ConfigDirectorLogger, r as ConfigDirectorValidationError, t as ConfigDirectorConnectionError, u as NativeValue } from "./errors-
|
|
1
|
+
import { C as TrackedEventDetails, S as TrackedEventDetailValue, d as NativeValues, i as ConfigDirectorClient, l as NativeJsonValue, m as ConfigDirectorLogger, r as ConfigDirectorValidationError, t as ConfigDirectorConnectionError, u as NativeValue, x as TrackedEvent } from "./errors-BKtOuEGy.cjs";
|
|
2
2
|
|
|
3
3
|
//#region src/testing/TestClient.d.ts
|
|
4
4
|
/**
|
|
@@ -20,7 +20,8 @@ type TestClientOptions = {
|
|
|
20
20
|
/**
|
|
21
21
|
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since
|
|
22
22
|
* the test client sends no telemetry, every read that supplies a context with an invalid kind
|
|
23
|
-
* logs an error, rather than each invalid kind once per telemetry interval.
|
|
23
|
+
* logs an error, rather than each invalid kind once per telemetry interval. For the same reason,
|
|
24
|
+
* every tracked event that is not recorded as it was tracked logs a warning.
|
|
24
25
|
*/
|
|
25
26
|
logger?: ConfigDirectorLogger;
|
|
26
27
|
};
|
|
@@ -68,6 +69,14 @@ interface TestClient {
|
|
|
68
69
|
* to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
|
|
69
70
|
*/
|
|
70
71
|
failInitialization(): void;
|
|
72
|
+
/**
|
|
73
|
+
* Every event the code under test tracked through the client, in call order, as the SDK would
|
|
74
|
+
* report it: an event whose name does not have 1 to 150 characters is not recorded, and a value
|
|
75
|
+
* or details the SDK would leave out are missing from the record. A context whose kind is
|
|
76
|
+
* invalid is not recorded with its event. The limit of 1,000 events per telemetry batch does not
|
|
77
|
+
* apply.
|
|
78
|
+
*/
|
|
79
|
+
readonly trackedEvents: TrackedEvent[];
|
|
71
80
|
}
|
|
72
81
|
//#endregion
|
|
73
82
|
//#region src/testing.d.ts
|
|
@@ -89,5 +98,5 @@ interface TestClient {
|
|
|
89
98
|
*/
|
|
90
99
|
declare const createTestClient: (options?: TestClientOptions) => TestClient;
|
|
91
100
|
//#endregion
|
|
92
|
-
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, createTestClient };
|
|
101
|
+
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, type TrackedEvent, type TrackedEventDetailValue, type TrackedEventDetails, createTestClient };
|
|
93
102
|
//# sourceMappingURL=configdirector-server-testing.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-server-testing.d.cts","names":[],"sources":["../src/testing/TestClient.ts","../src/testing.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.d.cts","names":[],"sources":["../src/testing/TestClient.ts","../src/testing.ts"],"mappings":";;;AAcA;;;AAAA,KAAY,iBAAA;EAOV;;;;;;EAAA,MAAA,GAAS,YAAA;EAuBM;;;;EAlBf,OAAA;EAyCsB;;;;;;EAlCtB,MAAA,GAAS,oBAAA;AAAA;;;;;;;;;UAWM,UAAA;EAyCf;;;;EAAA,SApCS,MAAA,EAAQ,oBAAA;;;;ACzBnB;ED+BE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;;;;;EAM7B,WAAA,CAAY,GAAA;ECnCb;;;;EDyCC,aAAA,CAAc,MAAA,EAAQ,YAAA;;;;;EAMtB,kBAAA;;;;;EAMA,sBAAA;;;;;EAMA,kBAAA;;;;;;;;WASS,aAAA,EAAe,YAAA;AAAA;;;;;;;;;;;;AAlD1B;;;;;;;cCpBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as NativeValues, i as ConfigDirectorClient, l as NativeJsonValue, m as ConfigDirectorLogger, r as ConfigDirectorValidationError, t as ConfigDirectorConnectionError, u as NativeValue } from "./errors-
|
|
1
|
+
import { C as TrackedEventDetails, S as TrackedEventDetailValue, d as NativeValues, i as ConfigDirectorClient, l as NativeJsonValue, m as ConfigDirectorLogger, r as ConfigDirectorValidationError, t as ConfigDirectorConnectionError, u as NativeValue, x as TrackedEvent } from "./errors-Dk_CsOtN.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/testing/TestClient.d.ts
|
|
4
4
|
/**
|
|
@@ -20,7 +20,8 @@ type TestClientOptions = {
|
|
|
20
20
|
/**
|
|
21
21
|
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since
|
|
22
22
|
* the test client sends no telemetry, every read that supplies a context with an invalid kind
|
|
23
|
-
* logs an error, rather than each invalid kind once per telemetry interval.
|
|
23
|
+
* logs an error, rather than each invalid kind once per telemetry interval. For the same reason,
|
|
24
|
+
* every tracked event that is not recorded as it was tracked logs a warning.
|
|
24
25
|
*/
|
|
25
26
|
logger?: ConfigDirectorLogger;
|
|
26
27
|
};
|
|
@@ -68,6 +69,14 @@ interface TestClient {
|
|
|
68
69
|
* to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
|
|
69
70
|
*/
|
|
70
71
|
failInitialization(): void;
|
|
72
|
+
/**
|
|
73
|
+
* Every event the code under test tracked through the client, in call order, as the SDK would
|
|
74
|
+
* report it: an event whose name does not have 1 to 150 characters is not recorded, and a value
|
|
75
|
+
* or details the SDK would leave out are missing from the record. A context whose kind is
|
|
76
|
+
* invalid is not recorded with its event. The limit of 1,000 events per telemetry batch does not
|
|
77
|
+
* apply.
|
|
78
|
+
*/
|
|
79
|
+
readonly trackedEvents: TrackedEvent[];
|
|
71
80
|
}
|
|
72
81
|
//#endregion
|
|
73
82
|
//#region src/testing.d.ts
|
|
@@ -89,5 +98,5 @@ interface TestClient {
|
|
|
89
98
|
*/
|
|
90
99
|
declare const createTestClient: (options?: TestClientOptions) => TestClient;
|
|
91
100
|
//#endregion
|
|
92
|
-
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, createTestClient };
|
|
101
|
+
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, type TrackedEvent, type TrackedEventDetailValue, type TrackedEventDetails, createTestClient };
|
|
93
102
|
//# sourceMappingURL=configdirector-server-testing.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-server-testing.d.mts","names":[],"sources":["../src/testing/TestClient.ts","../src/testing.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.d.mts","names":[],"sources":["../src/testing/TestClient.ts","../src/testing.ts"],"mappings":";;;AAcA;;;AAAA,KAAY,iBAAA;EAOV;;;;;;EAAA,MAAA,GAAS,YAAA;EAuBM;;;;EAlBf,OAAA;EAyCsB;;;;;;EAlCtB,MAAA,GAAS,oBAAA;AAAA;;;;;;;;;UAWM,UAAA;EAyCf;;;;EAAA,SApCS,MAAA,EAAQ,oBAAA;;;;ACzBnB;ED+BE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;;;;;EAM7B,WAAA,CAAY,GAAA;ECnCb;;;;EDyCC,aAAA,CAAc,MAAA,EAAQ,YAAA;;;;;EAMtB,kBAAA;;;;;EAMA,sBAAA;;;;;EAMA,kBAAA;;;;;;;;WASS,aAAA,EAAe,YAAA;AAAA;;;;;;;;;;;;AAlD1B;;;;;;;cCpBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,r as a,t as o}from"./DefaultConfigDirectorClient-BaDqRkjV.mjs";import s from"node:events";const c=(e,t)=>({name:e.name,...t===void 0?{}:{context:t},...e.value===void 0?{}:{value:e.value},...e.details===void 0?{}:{details:e.details}});var l=class{constructor(e){this.logger=e,this.events=[]}record(e,t){switch(e.warnings.forEach(e=>this.logger.warn(a[e])),e.outcome){case`dropped`:return;case`admitted`:this.events.push(c(e.entry,t));return}}};const u={environmentId:`test-environment`,projectId:`test-project`};var d=class{constructor(e,t){this.logger=e,this.emitter=new s,this.configs=new Map,this.pendingDeliveries=[],this.armed=`nothing`,this.connected=!1,this.delivering=!1,this.encodeAll(t).forEach((e,t)=>this.configs.set(t,e))}setValue(e,t){let n=this.encode(e,t);this.configs.set(e,n),this.deliverIfConnected({...u,kind:`delta`,configs:{[e]:n}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(){this.armed=`hold`}complete(){this.pendingHold?this.pendingHold.complete():this.armed===`hold`&&(this.armed=`nothing`)}fail(){this.pendingHold?this.pendingHold.fail():this.armed=`failure`}connect(e){this.endAttempt();let t=this.armed;switch(this.armed=`nothing`,t){case`failure`:return this.failNow();case`hold`:return this.holdNow(e);default:return this.connectNow(),Promise.resolve(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.endAttempt()}dispose(){this.close(),this.emitter.removeAllListeners()}endAttempt(){this.connected=!1,this.pendingHold?.end()}connectNow(){this.connected=!0,this.deliver(this.fullUpdate())}holdNow(e){return new Promise((t,n)=>{let r=setTimeout(()=>this.pendingHold?.end(),e),i=()=>{clearTimeout(r),this.pendingHold=void 0};this.pendingHold={end:()=>{i(),t(this)},complete:()=>{i(),this.connectNow(),t(this)},fail:()=>{i();let e=this.fatalError();this.emitter.emit(`connectionError`,e),n(e)}}})}failNow(){let e=this.fatalError();return this.emitter.emit(`connectionError`,e),Promise.reject(e)}fatalError(){return new i(`Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.`,401)}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configBundleReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...u,kind:`full`,configs:Object.fromEntries(this.configs)}}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(t,n){return e(`test-config:${t}`,t,n)}},f=class{constructor(e,t,n){this.client=e,this.connection=t,this.trackedEvents=n}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold()}completeInitialization(){this.connection.complete()}failInitialization(){this.connection.fail()}};const p=(e,t)=>{let i=t?.logger??n(),a=new d(i,t?.values??{}),s=new l(i);return new f(new o(`test-client`,e,{logger:i,connection:{timeout:t?.timeout}},{transport:a,telemetry:{...r,trackedEvent:(e,t)=>s.record(e,t)}}),a,s.events)},m=e=>p({sdkName:`js-server-sdk`,sdkVersion:`1.13.1`},e);export{i as ConfigDirectorConnectionError,t as ConfigDirectorValidationError,m as createTestClient};
|
|
2
2
|
//# sourceMappingURL=configdirector-server-testing.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-server-testing.mjs","names":["createTestClient"],"sources":["../src/testing/InMemoryConnection.ts","../src/testing/TestClient.ts","../src/testing.ts"],"sourcesContent":["import EventEmitter from \"node:events\";\nimport type { ConfigBundle, ConfigDefinition, ConfigDirectorLogger, Transport, TransportEvents } from \"../types\";\nimport { ConfigDirectorConnectionError } from \"@shared/errors\";\nimport type { TestValue, TestValues } from \"./values\";\nimport { unconditionalConfig } from \"../native-values\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new EventEmitter();\n private readonly configs = new Map<string, ConfigDefinition>();\n private readonly pendingDeliveries: ConfigBundle[] = [];\n private armed: Armed = \"nothing\";\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.encodeAll(values).forEach((definition, key) => this.configs.set(key, definition));\n }\n\n public setValue(key: string, value: TestValue) {\n const definition = this.encode(key, value);\n this.configs.set(key, definition);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: definition } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((definition, key) => this.configs.set(key, definition));\n this.armed = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold() {\n this.armed = \"hold\";\n }\n\n public complete() {\n if (this.pendingHold) {\n this.pendingHold.complete();\n } else if (this.armed === \"hold\") {\n this.armed = \"nothing\";\n }\n }\n\n public fail() {\n if (this.pendingHold) {\n this.pendingHold.fail();\n } else {\n this.armed = \"failure\";\n }\n }\n\n public connect(timeout: number): Promise<this> {\n this.endAttempt();\n const armed = this.armed;\n this.armed = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow();\n case \"hold\":\n return this.holdNow(timeout);\n default:\n this.connectNow();\n return Promise.resolve(this);\n }\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public on<TName extends keyof TransportEvents>(name: TName, handler: (payload: TransportEvents[TName]) => void) {\n this.emitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(name: TName, handler?: (payload: TransportEvents[TName]) => void) {\n if (handler) {\n this.emitter.off(name, handler);\n } else {\n this.emitter.removeAllListeners(name);\n }\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.emitter.removeAllListeners();\n }\n\n private endAttempt() {\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow() {\n this.connected = true;\n this.deliver(this.fullUpdate());\n }\n\n private holdNow(timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n this.connectNow();\n resolve(this);\n },\n fail: () => {\n release();\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(): Promise<this> {\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError() {\n return new ConfigDirectorConnectionError(\n \"Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.\",\n 401,\n );\n }\n\n private deliverIfConnected(configBundle: ConfigBundle) {\n if (this.connected) {\n this.deliver(configBundle);\n }\n }\n\n private deliver(configBundle: ConfigBundle) {\n this.pendingDeliveries.push(configBundle);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configBundle: ConfigBundle) {\n try {\n this.emitter.emit(\"configBundleReceived\", configBundle);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigBundle {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigDefinition> {\n const encoded = new Map<string, ConfigDefinition>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, this.encode(key, value));\n }\n return encoded;\n }\n\n private encode(key: string, value: TestValue): ConfigDefinition {\n return unconditionalConfig(`test-config:${key}`, key, value);\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type { ConfigDirectorClient, ConfigDirectorLogger, IdentifyingSdkOptions } from \"../types\";\nimport { discardingTelemetryClient } from \"../telemetry/discarding\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`). Every context receives the\n * same value.\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since\n * the test client sends no telemetry, every read that supplies a context with an invalid kind\n * logs an error, rather than each invalid kind once per telemetry interval.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing,\n * targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.\n * Only the network connection and telemetry are replaced, so no request is ever made and nothing\n * is left running after the client is disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n}\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold();\n }\n\n public completeInitialization() {\n this.connection.complete();\n }\n\n public failInitialization() {\n this.connection.fail();\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const client = new DefaultConfigDirectorClient(\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n { transport: connection, telemetry: discardingTelemetryClient },\n );\n return new InMemoryTestClient(client, connection);\n};\n","import { createTestClient as createInMemoryTestClient } from \"./testing/TestClient\";\nimport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\n\nexport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\nexport type { TestValue, TestValues, TestJsonValue } from \"./testing/values\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server\n * that the test controls. No network connection is opened and no telemetry is sent.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient } from \"@configdirector/server-sdk/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * await testClient.client.initialize();\n * expect(testClient.client.getValue(\"new-checkout\", false)).toBe(true);\n *\n * testClient.setValue(\"new-checkout\", false);\n */\nexport const createTestClient = (options?: TestClientOptions): TestClient => {\n return createInMemoryTestClient({ sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"mHAcA,MAAM,EAAmB,CAAE,cAAe,mBAAoB,UAAW,eAAgB,CAEzF,IAAa,EAAb,KAAqD,CASnD,YACE,EACA,EACA,CAFiB,KAAA,OAAA,EATnB,KAAiB,QAAU,IAAI,EAC/B,KAAiB,QAAU,IAAI,IAC/B,KAAiB,kBAAoC,EAAE,CACvD,KAAQ,MAAe,UAEvB,KAAQ,UAAY,GACpB,KAAQ,WAAa,GAMnB,KAAK,UAAU,EAAO,CAAC,SAAS,EAAY,IAAQ,KAAK,QAAQ,IAAI,EAAK,EAAW,CAAC,CAGxF,SAAgB,EAAa,EAAkB,CAC7C,IAAM,EAAa,KAAK,OAAO,EAAK,EAAM,CAC1C,KAAK,QAAQ,IAAI,EAAK,EAAW,CACjC,KAAK,mBAAmB,CAAE,GAAG,EAAkB,KAAM,QAAS,QAAS,EAAG,GAAM,EAAY,CAAE,CAAC,CAGjG,YAAmB,EAAa,CAC9B,KAAK,QAAQ,OAAO,EAAI,CACxB,KAAK,mBAAmB,KAAK,YAAY,CAAC,CAG5C,cAAqB,EAAoB,CACvC,IAAM,EAAU,KAAK,UAAU,EAAO,CACtC,KAAK,QAAQ,OAAO,CACpB,EAAQ,SAAS,EAAY,IAAQ,KAAK,QAAQ,IAAI,EAAK,EAAW,CAAC,CACvE,KAAK,MAAQ,UACb,KAAK,mBAAmB,KAAK,YAAY,CAAC,CAG5C,MAAc,CACZ,KAAK,MAAQ,OAGf,UAAkB,CACZ,KAAK,YACP,KAAK,YAAY,UAAU,CAClB,KAAK,QAAU,SACxB,KAAK,MAAQ,WAIjB,MAAc,CACR,KAAK,YACP,KAAK,YAAY,MAAM,CA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AAI,EAAmB,EAAQ,GAAS,QAAU,EAAE,CAAC,CAOxE,OAAO,IAAI,EANI,IAAI,EACjB,cACA,EACA,CAAE,SAAQ,WAAY,CAAE,QAAS,GAAS,QAAS,CAAE,CACrD,CAAE,UAAW,EAAY,UAAW,EAA2B,CAChE,CACqC,EAAW,ECtGtC,EAAoB,GACxB,EAAyB,CAAE,QAAS,gBAAiB,WAAY,SAAe,CAAE,EAAQ"}
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.mjs","names":["createTestClient"],"sources":["../../shared/src/telemetry/RecordedTrackedEvents.ts","../src/testing/InMemoryConnection.ts","../src/testing/TestClient.ts","../src/testing.ts"],"sourcesContent":["import type { ConfigDirectorContext, ConfigDirectorLogger, TrackedEvent } from \"../types\";\nimport { trackedEventWarningMessages } from \"./tracked-events\";\nimport type { TrackedEventAdmission, TrackedEventEntry } from \"./tracked-events\";\n\nconst recordedEventOf = (entry: TrackedEventEntry, context: ConfigDirectorContext | undefined): TrackedEvent => ({\n name: entry.name,\n ...(context === undefined ? {} : { context }),\n ...(entry.value === undefined ? {} : { value: entry.value }),\n ...(entry.details === undefined ? {} : { details: entry.details }),\n});\n\nexport class RecordedTrackedEvents {\n public readonly events: TrackedEvent[] = [];\n\n constructor(private readonly logger: ConfigDirectorLogger) {}\n\n public record(admission: TrackedEventAdmission, context: ConfigDirectorContext | undefined): void {\n admission.warnings.forEach((warning) => this.logger.warn(trackedEventWarningMessages[warning]));\n switch (admission.outcome) {\n case \"dropped\":\n return;\n case \"admitted\":\n this.events.push(recordedEventOf(admission.entry, context));\n return;\n }\n }\n}\n","import EventEmitter from \"node:events\";\nimport type { ConfigBundle, ConfigDefinition, ConfigDirectorLogger, Transport, TransportEvents } from \"../types\";\nimport { ConfigDirectorConnectionError } from \"@shared/errors\";\nimport type { TestValue, TestValues } from \"./values\";\nimport { unconditionalConfig } from \"../native-values\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new EventEmitter();\n private readonly configs = new Map<string, ConfigDefinition>();\n private readonly pendingDeliveries: ConfigBundle[] = [];\n private armed: Armed = \"nothing\";\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.encodeAll(values).forEach((definition, key) => this.configs.set(key, definition));\n }\n\n public setValue(key: string, value: TestValue) {\n const definition = this.encode(key, value);\n this.configs.set(key, definition);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: definition } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((definition, key) => this.configs.set(key, definition));\n this.armed = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold() {\n this.armed = \"hold\";\n }\n\n public complete() {\n if (this.pendingHold) {\n this.pendingHold.complete();\n } else if (this.armed === \"hold\") {\n this.armed = \"nothing\";\n }\n }\n\n public fail() {\n if (this.pendingHold) {\n this.pendingHold.fail();\n } else {\n this.armed = \"failure\";\n }\n }\n\n public connect(timeout: number): Promise<this> {\n this.endAttempt();\n const armed = this.armed;\n this.armed = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow();\n case \"hold\":\n return this.holdNow(timeout);\n default:\n this.connectNow();\n return Promise.resolve(this);\n }\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public on<TName extends keyof TransportEvents>(name: TName, handler: (payload: TransportEvents[TName]) => void) {\n this.emitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(name: TName, handler?: (payload: TransportEvents[TName]) => void) {\n if (handler) {\n this.emitter.off(name, handler);\n } else {\n this.emitter.removeAllListeners(name);\n }\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.emitter.removeAllListeners();\n }\n\n private endAttempt() {\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow() {\n this.connected = true;\n this.deliver(this.fullUpdate());\n }\n\n private holdNow(timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n this.connectNow();\n resolve(this);\n },\n fail: () => {\n release();\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(): Promise<this> {\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError() {\n return new ConfigDirectorConnectionError(\n \"Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.\",\n 401,\n );\n }\n\n private deliverIfConnected(configBundle: ConfigBundle) {\n if (this.connected) {\n this.deliver(configBundle);\n }\n }\n\n private deliver(configBundle: ConfigBundle) {\n this.pendingDeliveries.push(configBundle);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configBundle: ConfigBundle) {\n try {\n this.emitter.emit(\"configBundleReceived\", configBundle);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigBundle {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigDefinition> {\n const encoded = new Map<string, ConfigDefinition>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, this.encode(key, value));\n }\n return encoded;\n }\n\n private encode(key: string, value: TestValue): ConfigDefinition {\n return unconditionalConfig(`test-config:${key}`, key, value);\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type { ConfigDirectorClient, ConfigDirectorLogger, IdentifyingSdkOptions } from \"../types\";\nimport type { TrackedEvent } from \"@shared/types\";\nimport { RecordedTrackedEvents } from \"@shared/telemetry/RecordedTrackedEvents\";\nimport { discardingTelemetryClient } from \"../telemetry/discarding\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`). Every context receives the\n * same value.\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since\n * the test client sends no telemetry, every read that supplies a context with an invalid kind\n * logs an error, rather than each invalid kind once per telemetry interval. For the same reason,\n * every tracked event that is not recorded as it was tracked logs a warning.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing,\n * targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.\n * Only the network connection and telemetry are replaced, so no request is ever made and nothing\n * is left running after the client is disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n\n /**\n * Every event the code under test tracked through the client, in call order, as the SDK would\n * report it: an event whose name does not have 1 to 150 characters is not recorded, and a value\n * or details the SDK would leave out are missing from the record. A context whose kind is\n * invalid is not recorded with its event. The limit of 1,000 events per telemetry batch does not\n * apply.\n */\n readonly trackedEvents: TrackedEvent[];\n}\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n public readonly trackedEvents: TrackedEvent[],\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold();\n }\n\n public completeInitialization() {\n this.connection.complete();\n }\n\n public failInitialization() {\n this.connection.fail();\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const recordedTrackedEvents = new RecordedTrackedEvents(logger);\n const client = new DefaultConfigDirectorClient(\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n {\n transport: connection,\n telemetry: {\n ...discardingTelemetryClient,\n trackedEvent: (admission, context) => recordedTrackedEvents.record(admission, context),\n },\n },\n );\n return new InMemoryTestClient(client, connection, recordedTrackedEvents.events);\n};\n","import { createTestClient as createInMemoryTestClient } from \"./testing/TestClient\";\nimport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\n\nexport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\nexport type { TestValue, TestValues, TestJsonValue } from \"./testing/values\";\nexport type { TrackedEvent, TrackedEventDetails, TrackedEventDetailValue } from \"@shared/types\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server\n * that the test controls. No network connection is opened and no telemetry is sent.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient } from \"@configdirector/server-sdk/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * await testClient.client.initialize();\n * expect(testClient.client.getValue(\"new-checkout\", false)).toBe(true);\n *\n * testClient.setValue(\"new-checkout\", false);\n */\nexport const createTestClient = (options?: TestClientOptions): TestClient => {\n return createInMemoryTestClient({ sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"oIAIA,MAAM,GAAmB,EAA0B,KAA8D,CAC/G,KAAM,EAAM,KACZ,GAAI,IAAY,IAAA,GAAY,EAAE,CAAG,CAAE,UAAS,CAC5C,GAAI,EAAM,QAAU,IAAA,GAAY,EAAE,CAAG,CAAE,MAAO,EAAM,MAAO,CAC3D,GAAI,EAAM,UAAY,IAAA,GAAY,EAAE,CAAG,CAAE,QAAS,EAAM,QAAS,CAClE,EAED,IAAa,EAAb,KAAmC,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AaA,GAAoB,EAAmC,IAA4C,CAC9G,IAAM,EAAS,GAAS,QAAU,GAAqB,CACjD,EAAa,IAAI,EAAmB,EAAQ,GAAS,QAAU,EAAE,CAAC,CAClE,EAAwB,IAAI,EAAsB,EAAO,CAa/D,OAAO,IAAI,EAZI,IAAI,EACjB,cACA,EACA,CAAE,SAAQ,WAAY,CAAE,QAAS,GAAS,QAAS,CAAE,CACrD,CACE,UAAW,EACX,UAAW,CACT,GAAG,EACH,cAAe,EAAW,IAAY,EAAsB,OAAO,EAAW,EAAQ,CACvF,CACF,CACF,CACqC,EAAY,EAAsB,OAAO,ECzHpE,EAAoB,GACxB,EAAyB,CAAE,QAAS,gBAAiB,WAAY,SAAe,CAAE,EAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-fROPEpwq.cjs`),t={sdkName:`js-server-sdk`,sdkVersion:`1.13.1`};function n(n,r){return e.t.from(n,t,r)}const r=(t,n)=>e.i(t,n);exports.ConfigDirectorInitializationError=e.s,exports.createClient=n,exports.createConsoleLogger=r;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as ConfigEvaluation, a as ConfigDirectorClientOptions, c as OfflineValues, f as ConfigDirectorContext, g as ConfigDirectorMetaContext, h as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConfigDirectorLogger, n as ConfigDirectorInitializationError, o as OfflineClientOptions, p as ConfigDirectorLogMessageDecorator, s as OfflineValue, v as ConfigValueType, y as EvaluationReason } from "./errors-
|
|
1
|
+
import { C as TrackedEventDetails, S as TrackedEventDetailValue, _ as ConfigEvaluation, a as ConfigDirectorClientOptions, b as TrackOptions, c as OfflineValues, f as ConfigDirectorContext, g as ConfigDirectorMetaContext, h as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConfigDirectorLogger, n as ConfigDirectorInitializationError, o as OfflineClientOptions, p as ConfigDirectorLogMessageDecorator, s as OfflineValue, v as ConfigValueType, w as Variation, y as EvaluationReason } from "./errors-BKtOuEGy.cjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/logger.d.ts
|
|
4
4
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
@@ -65,5 +65,5 @@ declare function createClient(serverSdkKey: string, clientOptions?: ConfigDirect
|
|
|
65
65
|
declare function createClient(clientOptions: OfflineClientOptions): ConfigDirectorClient;
|
|
66
66
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
|
|
67
67
|
//#endregion
|
|
68
|
-
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorMetaContext, type ConfigEvaluation, type ConfigValueType, type EvaluationReason, type OfflineClientOptions, type OfflineValue, type OfflineValues, createClient, createConsoleLogger };
|
|
68
|
+
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorMetaContext, type ConfigEvaluation, type ConfigValueType, type EvaluationReason, type OfflineClientOptions, type OfflineValue, type OfflineValues, type TrackOptions, type TrackedEventDetailValue, type TrackedEventDetails, type Variation, createClient, createConsoleLogger };
|
|
69
69
|
//# sourceMappingURL=configdirector-server.d.cts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as ConfigEvaluation, a as ConfigDirectorClientOptions, c as OfflineValues, f as ConfigDirectorContext, g as ConfigDirectorMetaContext, h as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConfigDirectorLogger, n as ConfigDirectorInitializationError, o as OfflineClientOptions, p as ConfigDirectorLogMessageDecorator, s as OfflineValue, v as ConfigValueType, y as EvaluationReason } from "./errors-
|
|
1
|
+
import { C as TrackedEventDetails, S as TrackedEventDetailValue, _ as ConfigEvaluation, a as ConfigDirectorClientOptions, b as TrackOptions, c as OfflineValues, f as ConfigDirectorContext, g as ConfigDirectorMetaContext, h as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConfigDirectorLogger, n as ConfigDirectorInitializationError, o as OfflineClientOptions, p as ConfigDirectorLogMessageDecorator, s as OfflineValue, v as ConfigValueType, w as Variation, y as EvaluationReason } from "./errors-Dk_CsOtN.mjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/logger.d.ts
|
|
4
4
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
@@ -65,5 +65,5 @@ declare function createClient(serverSdkKey: string, clientOptions?: ConfigDirect
|
|
|
65
65
|
declare function createClient(clientOptions: OfflineClientOptions): ConfigDirectorClient;
|
|
66
66
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
|
|
67
67
|
//#endregion
|
|
68
|
-
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorMetaContext, type ConfigEvaluation, type ConfigValueType, type EvaluationReason, type OfflineClientOptions, type OfflineValue, type OfflineValues, createClient, createConsoleLogger };
|
|
68
|
+
export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorContext, ConfigDirectorInitializationError, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorMetaContext, type ConfigEvaluation, type ConfigValueType, type EvaluationReason, type OfflineClientOptions, type OfflineValue, type OfflineValues, type TrackOptions, type TrackedEventDetailValue, type TrackedEventDetails, type Variation, createClient, createConsoleLogger };
|
|
69
69
|
//# sourceMappingURL=configdirector-server.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{i as e,s as t,t as n}from"./DefaultConfigDirectorClient-BaDqRkjV.mjs";const r={sdkName:`js-server-sdk`,sdkVersion:`1.13.1`};function i(e,t){return n.from(e,r,t)}const a=(t,n)=>e(t,n);export{t as ConfigDirectorInitializationError,i as createClient,a as createConsoleLogger};
|
|
2
2
|
//# sourceMappingURL=configdirector-server.mjs.map
|
|
@@ -11,6 +11,12 @@ type ConfigState = {
|
|
|
11
11
|
type: ConfigType;
|
|
12
12
|
value: string | undefined | null;
|
|
13
13
|
valueId?: string | undefined | null;
|
|
14
|
+
variation?: {
|
|
15
|
+
id: string;
|
|
16
|
+
name?: string | undefined | null;
|
|
17
|
+
} | undefined | null;
|
|
18
|
+
ruleId?: string | undefined | null;
|
|
19
|
+
shareId?: string | undefined | null;
|
|
14
20
|
};
|
|
15
21
|
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
16
22
|
interface ConfigDirectorLogger {
|
|
@@ -24,24 +30,72 @@ interface ConfigDirectorLogMessageDecorator {
|
|
|
24
30
|
}
|
|
25
31
|
/**
|
|
26
32
|
* Why an evaluation returned the value it did. `found-match` returns a value from ConfigDirector,
|
|
27
|
-
* and `cached` a value kept on the device while a client SDK waits for live values.
|
|
33
|
+
* and `cached` a value kept on the device while a client SDK waits for live values.
|
|
34
|
+
* `rollout-skipped-no-identifier` returns the default targeting rule value: a server SDK skipped a
|
|
35
|
+
* percentage rollout because the context has no `id` to place it in a share. `value-missing`
|
|
28
36
|
* returns the in-code default value because the config has no value. Every other reason returns the
|
|
29
37
|
* in-code default value because of an error: the config does not exist (`config-state-missing`), no
|
|
30
38
|
* values have arrived yet (`client-not-ready`), or the value cannot be read as the type of the in-code
|
|
31
39
|
* default value.
|
|
32
40
|
*/
|
|
33
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
41
|
+
type EvaluationReason = "found-match" | "rollout-skipped-no-identifier" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
42
|
+
/**
|
|
43
|
+
* One of the values a config can serve, such as the control or a treatment of an experiment.
|
|
44
|
+
*/
|
|
45
|
+
type Variation = {
|
|
46
|
+
/** The ID ConfigDirector assigned to the variation, which stays the same when it is renamed. */id: string; /** The variation's name, when it has one. */
|
|
47
|
+
name?: string;
|
|
48
|
+
};
|
|
34
49
|
/**
|
|
35
50
|
* One evaluation of a config: the value it returned, why, and the context it was evaluated for.
|
|
36
51
|
*/
|
|
37
52
|
type ConfigEvaluation<T extends ConfigValueType = ConfigValueType> = {
|
|
38
53
|
/** The config key that was evaluated. */key: string; /** The value returned, which is the in-code default value when {@link isDefaultValue} is `true`. */
|
|
39
54
|
value: T; /** The ID ConfigDirector assigned to the value returned, when ConfigDirector sent one with it. */
|
|
40
|
-
valueId?: string;
|
|
55
|
+
valueId?: string;
|
|
56
|
+
/**
|
|
57
|
+
* The variation that was served. It is `undefined` when the config has no variations or the
|
|
58
|
+
* in-code default value is returned.
|
|
59
|
+
*/
|
|
60
|
+
variation?: Variation; /** Whether the evaluation returned the in-code default value. */
|
|
41
61
|
isDefaultValue: boolean; /** Why the evaluation returned this value. */
|
|
42
62
|
reason: EvaluationReason; /** The context the config was evaluated for, if any. */
|
|
43
63
|
context?: ConfigDirectorContext;
|
|
44
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* A value in the details of a tracked event: a string, a number, a boolean, or an array or object
|
|
67
|
+
* of such values.
|
|
68
|
+
*/
|
|
69
|
+
type TrackedEventDetailValue = string | number | boolean | TrackedEventDetailValue[] | {
|
|
70
|
+
[key: string]: TrackedEventDetailValue;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Details of a tracked event, such as the plan a customer chose. Details with more than 20
|
|
74
|
+
* top-level keys, or larger than 1 KB as JSON, are left out and the event is still reported.
|
|
75
|
+
*/
|
|
76
|
+
type TrackedEventDetails = {
|
|
77
|
+
[key: string]: TrackedEventDetailValue;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* What a tracked event carries besides its name.
|
|
81
|
+
*/
|
|
82
|
+
type TrackOptions = {
|
|
83
|
+
/**
|
|
84
|
+
* A number the event measures, such as an amount of money, a count or a duration. A value that
|
|
85
|
+
* is not a finite number is left out and the event is still reported.
|
|
86
|
+
*/
|
|
87
|
+
value?: number; /** Details of the event. */
|
|
88
|
+
details?: TrackedEventDetails;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* An event the code under test tracked, as a test client recorded it.
|
|
92
|
+
*/
|
|
93
|
+
type TrackedEvent = {
|
|
94
|
+
/** The name the event was tracked with. */name: string; /** The context the event was tracked for, if any. */
|
|
95
|
+
context?: ConfigDirectorContext; /** The value the event was tracked with, when it is a finite number. */
|
|
96
|
+
value?: number; /** The details the event was tracked with, when they are within the limits. */
|
|
97
|
+
details?: TrackedEventDetails;
|
|
98
|
+
};
|
|
45
99
|
/**
|
|
46
100
|
* The context to be sent to ConfigDirector: the user or other entity, such as a device or an
|
|
47
101
|
* organization, that configs are evaluated for. This context will be used for targeting rules
|
|
@@ -323,8 +377,8 @@ interface ConfigDirectorClient {
|
|
|
323
377
|
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
|
|
324
378
|
/**
|
|
325
379
|
* Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
|
|
326
|
-
* was served
|
|
327
|
-
* telemetry.
|
|
380
|
+
* was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
|
|
381
|
+
* counted in telemetry.
|
|
328
382
|
*
|
|
329
383
|
* @returns The evaluation, whose `value` is what {@link getValue} returns
|
|
330
384
|
* @param configKey The config key to evaluate
|
|
@@ -369,6 +423,21 @@ interface ConfigDirectorClient {
|
|
|
369
423
|
context?: ConfigDirectorContext;
|
|
370
424
|
configKeys?: string[];
|
|
371
425
|
}): Record<string, ConfigState>;
|
|
426
|
+
/**
|
|
427
|
+
* Reports to ConfigDirector that something happened, such as a completed checkout, so it can be
|
|
428
|
+
* counted. The event is sent with the next telemetry batch. `track` never throws, and does nothing
|
|
429
|
+
* in `offline` mode.
|
|
430
|
+
*
|
|
431
|
+
* An event counts for an experiment only when it is tracked for a context with an `id`, the one
|
|
432
|
+
* the experiment's config was evaluated for. Without a context, or for a context without an
|
|
433
|
+
* `id`, the event is still reported.
|
|
434
|
+
*
|
|
435
|
+
* @param eventName The name of the event, 1 to 150 characters. An event with any other name is
|
|
436
|
+
* not reported and a warning is logged.
|
|
437
|
+
* @param context The context the event happened for (optional)
|
|
438
|
+
* @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
|
|
439
|
+
*/
|
|
440
|
+
track(eventName: string, context?: ConfigDirectorContext, options?: TrackOptions): void;
|
|
372
441
|
on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
|
|
373
442
|
off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
|
|
374
443
|
/**
|
|
@@ -395,5 +464,5 @@ declare class ConfigDirectorInitializationError extends Error {
|
|
|
395
464
|
constructor(message: string);
|
|
396
465
|
}
|
|
397
466
|
//#endregion
|
|
398
|
-
export { ConfigEvaluation as _, ConfigDirectorClientOptions as a, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigDirectorMetaContext as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u, ConfigValueType as v, EvaluationReason as y };
|
|
399
|
-
//# sourceMappingURL=errors-
|
|
467
|
+
export { TrackedEventDetails as C, TrackedEventDetailValue as S, ConfigEvaluation as _, ConfigDirectorClientOptions as a, TrackOptions as b, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigDirectorMetaContext as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u, ConfigValueType as v, Variation as w, TrackedEvent as x, EvaluationReason as y };
|
|
468
|
+
//# sourceMappingURL=errors-BKtOuEGy.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-BKtOuEGy.d.cts","names":[],"sources":["../../shared/src/types.ts","../../shared/src/native-values.ts","../src/types.ts","../../shared/src/errors.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,OAAA;EACA,SAAA;IAAc,EAAA;IAAY,IAAA;EAAA;EAC1B,MAAA;EACA,OAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;;AAblB;;;;;KA0BY,gBAAA;;;;KAeA,SAAA;EAtCJ,gGAwCN,EAAA,UAtCA;EAwCA,IAAA;AAAA;;;;KAMU,gBAAA,WAA2B,eAAA,GAAkB,eA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