@configdirector/server-sdk 1.10.0 → 1.11.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.
@@ -22,7 +22,7 @@ interface ConfigDirectorLogger {
22
22
  interface ConfigDirectorLogMessageDecorator {
23
23
  decorateMessage(message: string): string;
24
24
  }
25
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
25
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
26
26
  type ConfigEvaluation = {
27
27
  key: string;
28
28
  value: ConfigValueType;
@@ -41,9 +41,11 @@ type ConfigDirectorContext = {
41
41
  * The context's identifier. This should be a value that uniquely identifies the user or other
42
42
  * entity among contexts of the same {@link kind}.
43
43
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
44
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
45
- * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
46
- * could result in the context being assigned to a different percentile.
44
+ * the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
45
+ * stores for the app install or the website, so it stays the same until the app is uninstalled
46
+ * or the site's data is cleared. However, keep in mind that this value is used for segmenting
47
+ * contexts in percentage rollouts, and changes to the {@link id} could result in the context
48
+ * being assigned to a different percentile.
47
49
  */
48
50
  id?: string;
49
51
  /**
@@ -87,9 +89,90 @@ type ConfigDirectorMetaContext = {
87
89
  appVersion?: string;
88
90
  appName?: string;
89
91
  };
90
- type ConnectionMode = "streaming" | "polling";
92
+ type ConnectionMode = "streaming" | "polling" | "offline";
93
+ //#endregion
94
+ //#region ../shared/src/native-values.d.ts
95
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
96
+ [key: string]: NativeJsonValue;
97
+ };
98
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
99
+ [key: string]: NativeJsonValue;
100
+ };
101
+ type NativeValues = Record<string, NativeValue>;
91
102
  //#endregion
92
103
  //#region src/types.d.ts
104
+ /**
105
+ * One value an offline client serves for a config key. The config type follows from the value: a
106
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
107
+ * or array (`json`).
108
+ */
109
+ type OfflineValue = NativeValue;
110
+ /**
111
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
112
+ * value's config type is decided. Every context receives the same value.
113
+ */
114
+ type OfflineValues = NativeValues;
115
+ /**
116
+ * Connection options of the {@link ConfigDirectorClient}
117
+ */
118
+ type ConnectionOptions = {
119
+ /**
120
+ * The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
121
+ * If set to `streaming`, the connection will remain open and receive updates whenever
122
+ * config state is updated on the ConfigDirector dashboard.
123
+ * When set to `polling`, there will be an initial request to retrieve config state during
124
+ * initialization, and additional requests on a `pollingInterval`.
125
+ * When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
126
+ * the values read from {@link file} or given in {@link values} to every context, or the in-code
127
+ * default values when neither is given. No SDK key is needed.
128
+ *
129
+ * Defaults to `streaming`
130
+ */
131
+ mode?: ConnectionMode;
132
+ /**
133
+ * The path of a JSON file holding the values to serve in `offline` mode, resolved against the
134
+ * process working directory. The file holds one object with a value per config key, such as
135
+ * `{ "new-checkout": true, "max-items": 20 }`; see {@link OfflineValue} for how the config type
136
+ * of each value is decided. A file that is missing, unreadable, not a JSON object, or holding a
137
+ * value such as `null` makes `initialize` reject with a `ConfigDirectorInitializationError`.
138
+ *
139
+ * Only one of `file` and `values` can be given, and only in `offline` mode; otherwise
140
+ * `initialize` rejects.
141
+ */
142
+ file?: string;
143
+ /**
144
+ * The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
145
+ * `initialize` reject with a `ConfigDirectorInitializationError`.
146
+ *
147
+ * Only one of `file` and `values` can be given, and only in `offline` mode; otherwise
148
+ * `initialize` rejects.
149
+ */
150
+ values?: OfflineValues;
151
+ /**
152
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
153
+ * effect in the other modes.
154
+ *
155
+ * Defaults to 300 seconds (5 minutes). The minimum is 60 seconds. A value below the minimum is
156
+ * raised to the minimum and a warning is logged.
157
+ */
158
+ pollingInterval?: number;
159
+ /**
160
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
161
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
162
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
163
+ * If streaming is disabled, if the operation times out, it will not be retried. This option has
164
+ * no effect in `offline` mode.
165
+ *
166
+ * Defaults to 3,000 milliseconds (3 seconds)
167
+ */
168
+ timeout?: number;
169
+ /**
170
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
171
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
172
+ * a proxy for the client SDK. This option has no effect in `offline` mode.
173
+ */
174
+ url?: string;
175
+ };
93
176
  /**
94
177
  * Configuration options for the {@link ConfigDirectorClient}
95
178
  */
@@ -101,41 +184,7 @@ type ConfigDirectorClientOptions = {
101
184
  /**
102
185
  * Connection options
103
186
  */
104
- connection?: {
105
- /**
106
- * The connection mode to be used, one of `streaming` (default) or `polling`.
107
- * If set to `streaming`, the connection will remain open and receive updates whenever
108
- * config state is updated on the ConfigDirector dashboard.
109
- * When set to `polling`, there will be an initial request to retrieve config state during
110
- * initialization, and additional requests on a `pollingInterval`.
111
- *
112
- * Defaults to `streaming`
113
- */
114
- mode?: ConnectionMode;
115
- /**
116
- * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
117
- * effect when the `mode` is set to `streaming`.
118
- *
119
- * Defaults to 300 seconds (5 minutes). The minimum is 60 seconds. A value below the minimum is
120
- * raised to the minimum and a warning is logged.
121
- */
122
- pollingInterval?: number;
123
- /**
124
- * The timeout, in milliseconds, to be used in initialization and when updating the context.
125
- * If streaming is enabled, the operation (initialization or context update) may still succeed
126
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
127
- * If streaming is disabled, if the operation times out, it will not be retried.
128
- *
129
- * Defaults to 3,000 milliseconds (3 seconds)
130
- */
131
- timeout?: number;
132
- /**
133
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
134
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
135
- * a proxy for the client SDK.
136
- */
137
- url?: string;
138
- };
187
+ connection?: ConnectionOptions;
139
188
  /**
140
189
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
141
190
  * logger set to 'warn' level.
@@ -195,6 +244,14 @@ type ConfigDirectorClientOptions = {
195
244
  */
196
245
  hooks?: ClientHooks;
197
246
  };
247
+ /**
248
+ * The options of a client created without an SDK key: the connection mode is `offline`.
249
+ */
250
+ type OfflineClientOptions = ConfigDirectorClientOptions & {
251
+ connection: ConnectionOptions & {
252
+ mode: "offline";
253
+ };
254
+ };
198
255
  type ClientEvents = {
199
256
  configsUpdated: {
200
257
  keys: string[];
@@ -301,5 +358,20 @@ interface ConfigDirectorClient {
301
358
  dispose(): void;
302
359
  }
303
360
  //#endregion
304
- export { ConfigDirectorLogger as a, ConfigValueType as c, ConfigDirectorLogMessageDecorator as i, ConfigDirectorClientOptions as n, ConfigDirectorLoggingLevel as o, ConfigDirectorContext as r, ConfigDirectorMetaContext as s, ConfigDirectorClient as t };
305
- //# sourceMappingURL=types-BvNBpCHC.d.mts.map
361
+ //#region ../shared/src/errors.d.ts
362
+ declare class ConfigDirectorConnectionError extends Error {
363
+ readonly name: string;
364
+ readonly status?: number;
365
+ constructor(message: string, status?: number);
366
+ }
367
+ declare class ConfigDirectorValidationError extends Error {
368
+ readonly name: string;
369
+ constructor(message: string);
370
+ }
371
+ declare class ConfigDirectorInitializationError extends Error {
372
+ readonly name: string;
373
+ constructor(message: string);
374
+ }
375
+ //#endregion
376
+ export { ConfigValueType 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 };
377
+ //# sourceMappingURL=errors-npfIYhSQ.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-npfIYhSQ.d.mts","names":[],"sources":["../../shared/src/types.ts","../../shared/src/native-values.ts","../src/types.ts","../../shared/src/errors.ts"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/server-sdk",
3
- "version": "1.10.0",
3
+ "version": "1.11.1",
4
4
  "description": "Javascript server SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -1,6 +0,0 @@
1
- import e,{EventEmitter as t}from"node:events";import{createHash as n,randomUUID as r}from"node:crypto";import{DateTime as i}from"luxon";import*as a from"semver";import{rapidhash as o}from"rapidhash-js";var s=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},c=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},te=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 f=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var p=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=f.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===f.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=f.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new l(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new te({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new ee(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=f.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new d(`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 u(`${n} must be a function`);return e}};const m=e=>new p(e),h=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},g=9e4;var _=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=m({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(),g);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||h(g,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=r(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new s(`${`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()}},v=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new s(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new s(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new s(`Failed to parse the response from the server: ${e}`):new s(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new s(`${`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()}},y=class extends v{constructor(e){super(),this.options=e,this.eventEmitter=new t,this._sessionId=r(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await h(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 b=/^(?:0|[1-9][0-9]*)$/,x=/~(?![01])/,S=Object.prototype.propertyIsEnumerable,C=e=>{if(!x.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},w=(e,t)=>{if(Array.isArray(e))return b.test(t)&&S.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return S.call(e,t)?e[t]:void 0},ne=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=C(t);if(e===void 0||(n=w(n,e),n===void 0))return}return n},re=(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}},ie=(e,t,n)=>{let r=t.toLowerCase(),i=T(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=T(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}},T=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!ae(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},ae=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},oe=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=E(e),a=E(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}},E=e=>{let t=i.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},se=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=a.coerce(e),o=n.map(e=>a.coerce(e)),s=o[0]??null;switch(r){case`=`:return D(i,s);case`<`:return O(i,s,a.lt);case`<=`:return O(i,s,a.lte);case`>`:return O(i,s,a.gt);case`>=`:return O(i,s,a.gte);case`is one of`:return o.some(e=>D(i,e));case`is not one of`:return!o.some(e=>D(i,e));default:return!1}},D=(e,t)=>e!==null&&t!==null&&a.eq(e,t),O=(e,t,n)=>e!==null&&t!==null&&n(e,t),k=Symbol(`absent`),A=Symbol(`unknown-attribute`),j=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,M=e=>e===k||e==null?``:j(e)?N(e):``,N=e=>typeof e==`string`?e:String(e),P=e=>e===k?void 0:e,F=e=>e===A?`unknown-attribute`:e===k?`absent`:j(e)?`scalar`:Array.isArray(e)?`array`:`object`,I=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(j).map(N);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}},L=e=>e?.context?.kind??`user`;var R=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=F(n),i=n===k||n===A?void 0:n;return n===A?{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 re(M(t),e.operator,n);case`number`:return ie(P(t),e.operator,n);case`datetime`:return oe(M(t),e.operator,n);case`semver`:return se(M(t),e.operator,n);case`array`:return I(P(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return z(t?.context?.id);case`name`:return z(t?.context?.name);case`kind`:return L(t);case`appName`:return z(t?.metadata?.appName);case`appVersion`:return z(t?.metadata?.appVersion);case`traits`:return e.trait?z(ne(e.trait,t?.context?.traits)):k;default:return A}}};const z=e=>e??k;var B=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!V(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 V=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),H=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number(o(r,{seed:15426857351n})%1000n)/10};var U=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new R,this.segmentEvaluator=new B(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{id:e.id,key:e.key,type:e.type,value:this.explain(e,t,n).value}}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[],a;for(let o of r){if(a){i.push({ruleId:o.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let r=this.explainRule(o,e,t,n);i.push(r.explanation),r.value!==void 0&&(a={ruleId:o.id,value:r.value})}return{value:a?.value??e.target?.defaultValue,servedBy:a?{kind:`rule`,ruleId:a.ruleId}:{kind:`default`},rules:i}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a;return e.type==`percentage`?a=this.explainPercentage(e.percentages??[],t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),a!==void 0&&(i.outcome=`matched`),{explanation:i,value: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},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:H({configId:t.id,contextIdentifier:i,contextKind:L(n)}),o=[],s=0,c;for(let t of e){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,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}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`}if(!a){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}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 W=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},G=e=>e===`number`||e===`bigint`,K=new Set([`boolean`,`integer`,`float`]),ce=(e,t)=>{let n=e.value,r=W(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return pe(n,t,r,e.valueId);if(typeof t==`string`)return K.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=le(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(G(typeof t)&&e.type===`integer`){let i=ue(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(G(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=de(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`}},le=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},ue=e=>{let t=q(e);return t==null?void 0:Math.trunc(t)},de=e=>q(e),q=e=>{if(!e||!fe(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},fe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},pe=(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 me(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`}}},me=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},J={off:-1,error:0,warn:1,info:2,debug:3},he=()=>{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 ge=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=he()}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){J[this.level]>=J[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},_e=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const Y=(e,t)=>new ge(e??`warn`,t??new _e),ve=(e,t)=>new URL(e,t?.toString()),ye=(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.`},be=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,xe=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!be(t))return!1;return!0},Se=e=>e==null||typeof e==`string`&&xe(e),Ce=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},we=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},Te=e=>{let t=e?.kind;return Se(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:we(Ce(t),128)}};var Ee=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??(this.startTime=new Date),this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}};const X=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,Z=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}},Q=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},De=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 Oe=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 Q(e.discreteEvents)&&Q(e.aggregatedEvents)&&De(e.droppedEvents)}async sendReport(e){try{let t=await h(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},ke=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}))}},Ae=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||(this.startTime=new Date);let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},$=class{constructor(e){this.aggregator=new ke,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new Ae(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},je=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)}}},Me=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 X(e.defaultValue,this.valueIdGenerator),evaluatedValue:await X(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},Ne=class extends ${constructor(e){super(e),this.invalidContextSubmissions=new Ee,this.reporter=new Oe(e),this.contexts=new je(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new Me(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,n=L({context:t}),r=t?.anonymous?void 0:t?.id;r&&this.contexts.set(`${n}:${r}`,{...t,kind:n});let i={...e.evaluation,contextId:r,contextKind:r===void 0?void 0:n};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(i))}recordInvalidContext(e){return this.invalidContextSubmissions.record(e)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Z({value:e.defaultValue,type:e.type}),evaluatedValue:Z({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},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const Pe=(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`)},Fe=Math.ceil(128/Math.log2(62)),Ie=async e=>Pe(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Fe),Le=new URL(`https://server-sdk-api.configdirector.com`),Re={"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":()=>{}},ze=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Be=class{constructor(t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??Y(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.validateSdkKeyPresence(t),this.configEvaluator=new U(this.logger);let a=this.parseUrl(r?.connection?.url)??Le;this.connectionMode=r?.connection?.mode??`streaming`,this.usageEventCollector=i?.telemetry??this.buildTelemetryCollector(t,n,a,r),this.transport=i?.transport??this.buildTransport(t,n,a,r),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=ye(e,{defaultSeconds:300,minimumSeconds:60});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTelemetryCollector(e,t,n,r){let i=r?.telemetry?.eventQueueLimit??5e3;return new Ne({sdkKey:e,sdkIdentity:t,metaContext:r?.metadata??{},logger:this.logger,baseUrl:n,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(i*.7),contextLimit:Math.floor(i*.3),urlFactory:ve,valueIdGenerator:Ie})}buildTransport(e,t,n,r){return new(this.getTransportConstructor(this.connectionMode))({serverSdkKey:e,baseUrl:n,metaContext:{...r?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:this.resolvePollingIntervalForMode(r?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return y;default:return _}}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])=>ze(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.getValueFromConfigDefinition(e,t,n.defaultValue,n.context);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){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){let i=this.contextToEvaluate(r);if(t){let r=this.configEvaluator.evaluate(t,{context:i,metadata:this.metaContext},this.configSet?.segments),a=ce(r,n);return this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,type:r.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:i}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}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`;return this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,defaultValue:n,requestedType:W(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:i}),n}}contextToEvaluate(e){let t=Te(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:Re[this.usageEventCollector.recordInvalidContext(t.kindSample)](this.logger,t.kindSample);return}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new c(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new c(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`)}validateDefaultValue(e){if(e==null)throw new c(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new c(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){let t=this.contextToEvaluate(e?.context);if(!this.configSet)return{};let n=Object.entries(this.configSet.configs),r=e?.configKeys?n.filter(([t])=>e.configKeys?.includes(t)):n;return Object.fromEntries(r.map(([e,n])=>[e,this.configEvaluator.evaluate(n,{context:t,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{c as i,Y as n,s as r,Be as t};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-CJqto-ZO.mjs.map